Skip to content

sklearn.tree.export_dict #20051

Open
Open

Description

@jwilber

Currently, there are two options to get the decision tree representations: export_graphviz and export_text.

I would like to add export_dict, which will output the decision as a nested dictionary.

While you can convert the graphviz representation using cli tools, it's a bit unruly and is a weird workflow. When converting back, the nesting is also kind of weird, with /n chars floating around.

The main utility for json/dict representations are

  1. That they're far easier to work with for any front-end work.
  2. Working with a dict allows you to use the representation easily for any downstream tasks using the decision tree (that aren't raw inference).

Activity

  1. ayush714 commented on May 6, 2021

    @ayush714

    Can I work on this feature?

  2. nok commented on May 16, 2021

    @nok
    Contributor

    @jwilber Can you describe your desired data structure of a tree with multiple branches please?
    (I'm the developer of the sklearn-porter which solves similar issues.)

  3. jwilber commented on May 16, 2021

    @jwilber
    Author

    I’ve written a method that yields the same result as export_graphviz, but in a nested dict.

    See output example here (though the data here is slightly massaged to work better with d3): https://observablehq.com/@jwilber/visualize-decision-trees-from-sklearn

    I was opening an issue here to see if there’s any interest - if so I’d open a PR. If you think your lib is a good fit lmk and I can either open a pr or send you the code!

  4. nok commented on May 16, 2021

    @nok
    Contributor

    A core developer can answer your question whether it's possible to add a export_dict method to export model data or not I guess. A purpose is to use the data and to visualize it individually.

    The porter can already exports the model data of a decicion tree and tanspiles it to another programming language.

    Finally I can give you some feedback to your visualization. Great work, but what are the advantages in comparison to the output of the export_graphviz method? For me it's really difficult to compare the values visually. The branches have all the same width and color. The font size is very small. The visualization isn't compact, so how would it looks like if the tree is very large with many features and classes? I think the main advantage of your work is that we can make the visualization interactive and more useable for analysis. What do you think?

  5. jwilber commented on May 16, 2021

    @jwilber
    Author

    Sorry, this whole interaction is very confusing to me. I’m just trying to see if sklearn devs desire a PR as described or not. I’m not sure where your library fits here?

    I appreciate the feedback! But the visual I linked is just a 10 minute chunk of d3 code to verify that the function’s output will work for some arbitrary tree generated from sklearn. Not a project itself, and outside the scope of this issue.

    Reasons for not wanting export_graphviz detailed in comment one.

  6. thomasjpfan commented on May 17, 2021

    @thomasjpfan
    Member

    I see export_dict as another way to serialize and inspect the tree without having to go through Python object. Going through the Python object can be a bit involved as demonstrated by our example. Other libraries has similar functions to serialized trees into something human readable such as: LightGBM's model_to_string or XGBoost's Model IO.

    I am overall +0.5 on adding this to sklearn. It has secondary benefit of making it a little easier to export the trees into another format. I suggest we wait to see other's opinions before working on this.

  7. luxedo commented on Jul 1, 2021

    @luxedo
    Contributor

    Hi! I just like to add the description of the issue I just posted.

    Describe the workflow you want to enable

    In my opinion It would be great to have the dict representation of decision trees in the library.

    Describe your proposed solution

    The interface would be the similar to tree.export_text, maybe tree.export_dict?

    Additional context

    More than once I manually exported a decision tree from a model to a dictionary like so:

    tree = {
      "feature": "feature 1",
      "value": 0.5,
      "left": {
        "feature": "feature 2",
        "value": 0.1,
        "left": "category 1",
        "right": "category 2"
      },
      "right": "category 3"
    }

    And then run the tree with a simple recursive function like:

    def run_tree(leaf, data):
        if not isinstance(leaf, dict):
            return leaf
        next_leaf = leaf["left"] if data[leaf["feature"]] <= leaf["value"] else leaf["right"]
        return run_tree(
            next_leaf,
            data,
        )

    I like this representation because:

    1. The inference function is very simple.
    2. Removes sklearn dependency for inference
    3. It can be easily ported to other languages
    4. It's very descriptive and good for educational purposes

    My quick implementation of export_dict:

    def export_dict(clf, feature_names=None):
        tree = clf.tree_
        if feature_names is None:
            feature_names = range(clf.max_features_)
        
        # Build tree nodes
        tree_nodes = []
        for i in range(tree.node_count):
            if (tree.children_left[i] == tree.children_right[i]):
                tree_nodes.append(
                    clf.classes_[np.argmax(tree.value[i])]
                )
            else:
                tree_nodes.append({
                    "feature": feature_names[tree.feature[i]],
                    "value": tree.threshold[i],
                    "left": tree.children_left[i],
                    "right": tree.children_right[i],
                })
        
        # Link tree nodes
        for node in tree_nodes:
            if isinstance(node, dict):
                node["left"] = tree_nodes[node["left"]]
            if isinstance(node, dict):
                node["right"] = tree_nodes[node["right"]]
        
        # Return root node
        return tree_nodes[0]

    If this is a good idea I'd be glad to help!

    The main reason this feature would be useful for me is that I can easily port decision trees to other places. I already put some trees in web applications and microcontrollers. I would love to help if this would benefit the community as well.

  8. ogrisel commented on Jun 29, 2023

    @ogrisel
    Member

    I would rather be in favor of returning a dict of numpy arrays instead of a list/array of dicts.

    Either outputs can then be turned into a pandas dataframe easily.

  9. JustinDula commented on May 6, 2024

    @JustinDula

    This would be a useful feature.

    For an industry use-case, this would it easier to export trees to text for transmission over protocols such as MQTT to edge devices, which may need to perform inference on the tree but not have scikit-learn. While export_text (or other methods) can produce outputs that are relatively simple to parse, a dict that could be JSON-serialized would be extremely simple and portable.

  10. lcrmorin commented on Mar 1, 2026

    @lcrmorin

    I've recently found myself in need of this and wrote some custom function to do it.... I've even pushed it to write sql inference code. Some standard json extraction would be a good start.

  11. lcrmorin commented on Aug 24, 2026

    @lcrmorin

    I've figured I could do the PR for this since it would be quite close to export text, with an option to dump it into a json... Maybe some of the code (tests) could be refactored so that its doesn't feel like a copy paste.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions