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
max_depthis the main guard against memorising the training set.export_textprints the tree as nested conditions.get_depthandget_n_leavesdescribe what it built.
Keywords and builtins used here
print
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.
Step 4 of 4 in Models, step 15 of 25 in Machine learning with scikit-learn.