typestar

Decision trees in Python

A model you can read: depth, splits, and the rules it learned.

from sklearn.datasets import load_iris
from sklearn.tree import DecisionTreeClassifier, export_text

X, y = load_iris(return_X_y=True)
tree = DecisionTreeClassifier(max_depth=2, random_state=0).fit(X, y)

print(tree.get_depth(), tree.get_n_leaves())
print(export_text(tree, feature_names=load_iris().feature_names))

How it works

  1. max_depth is the main guard against memorising the training set.
  2. export_text prints the tree as nested conditions.
  3. get_depth and get_n_leaves describe what it built.

Keywords and builtins used here

The run, in numbers

Lines
8
Characters to type
315
Tokens
72
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 39 seconds.

Type this snippet

Step 4 of 4 in Models, step 15 of 25 in Machine learning with scikit-learn.

← Previous Next →