Skip to content

Export decision trees as dictionaries with tree.export_dict #20428

Closed

Description

@luxedo

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!

Activity

  1. defoishugo commented on Jun 30, 2021

    @defoishugo
    Contributor

    This is a nice idea.
    Are you looking for someone to develop that? I can do it if the community consider this feature as useful.

  2. luxedo commented on Jun 30, 2021

    @luxedo
    ContributorAuthor

    Great to hear!
    I really like to give it a try too

    This is a nice idea.
    Are you looking for someone to develop that? I can do it if the community consider this feature as useful.

  3. NicolasHug commented on Jun 30, 2021

    @NicolasHug
    Member

    Thanks for the proposal @luxedo ,

    I like this representation because:
    The inference function is very simple.
    Removes sklearn dependency for inference
    It can be easily ported to other languages
    It's very descriptive and good for educational purposes

    I'm not sure these argument completely align with the purpose and the needs of scikit-learn.

    Purely in terms of readability, this doesn't seem to add much value compared to the current export_text, export_graphviz or plot_tree that we support.

    Regarding prediction: sure this is portable and simple, but this will also be very slow compared to the built-in Cython implementation. I'm not sure who/what would benefit from exporting scikit-learn tree in such format, for prediction purpose.

    If really your goal is to teach students how decision trees work, I'm afraid scikit-learn might not be the best tool for that. There are packages specifically dedicated to implement ML algorithms in a simple and educational way though, for example https://github.com/rushter/MLAlgorithms or https://github.com/eriklindernoren/ML-From-Scratch

  4. thomasjpfan commented on Jun 30, 2021

    @thomasjpfan
    Member

    Purely in terms of readability, this doesn't seem to add much value compared to the current export_text, export_graphviz or plot_tree that we support.

    I see two reasons to have a dict representation:

    1. Visualizations of the trees. With a dict representation, one does not need to know the inner structure of the Tree object to figure out how to navigate the tree for their visualization. export_text, export_graphviz, plot_tree can all just "clients" using the dict representation.

    2. Libraries that serialize our trees such as hummingbird or onnx needs to keep track of changes of sklearn's internal tree data structure to convert it into their format.

    TLDR: I am basically highlighting @luxedo's third point that the dictionary representation is more portable. As with any new feature, the downside is more maintenance.

    Thank you for the proposal @luxedo ! I am closing this issue because it is a duplicate of #20051

  5. luxedo commented on Jun 30, 2021

    @luxedo
    ContributorAuthor

    Thanks for the feedback! I'm sorry I didn't searched for that issue before. It is quite an easy find XP

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