Sub topic 13
Reading a tree as rules
This chapter assumes you can fit a scikit-learn DecisionTreeClassifier and know what a split threshold is. A fitted tree is a set of if-then rules. Reading those rules lets you check that the model is sensible and explain its predictions.
From paths to rules
Every path from the root to a leaf is one rule. The conditions along the path are joined with AND, and the leaf gives the prediction. Because each sample ends in exactly one leaf, the rules do not overlap. A tree with L leaves is therefore a list of L rules.
Reading the right-hand path gives this rule: IF petal length > 2.45 AND petal width > 1.75 THEN virginica.
Printing the rules
export_text prints the whole tree with indentation. Each indent level is one more condition.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, export_text
data = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
data.data, data.target, test_size=0.3, random_state=0, stratify=data.target
)
clf = DecisionTreeClassifier(max_depth=3, random_state=0).fit(X_train, y_train)
print(export_text(clf, feature_names=data.feature_names))For a flat list of rules, walk the tree_ object. A node with children_left == -1 is a leaf.
def leaf_rules(clf, feature_names, class_names):
t = clf.tree_
rules = []
def walk(node, conditions):
if t.children_left[node] == -1:
label = class_names[t.value[node][0].argmax()]
rules.append((conditions, label, int(t.n_node_samples[node])))
return
name = feature_names[t.feature[node]]
thr = t.threshold[node]
walk(t.children_left[node], conditions + [f"{name} <= {thr:.2f}"])
walk(t.children_right[node], conditions + [f"{name} > {thr:.2f}"])
walk(0, [])
return rules
for conditions, label, n in leaf_rules(clf, data.feature_names, data.target_names):
print("IF", " AND ".join(conditions), "THEN", label, f"({n} training samples)")To explain a single prediction, call clf.decision_path(x). It returns the nodes that one sample passed through, which is the exact rule that fired.
What to check in each rule
- Support. A leaf with few training samples is a weak rule. Its prediction rests on very little data.
- Purity. Look at the class counts in the leaf. A leaf that predicts class A from 60% A and 40% B is less certain than the label suggests.
- Plausibility. Do the thresholds make domain sense? A split at a value no one could have measured, or on an ID-like column, signals a problem in the data.
- Depth. Rules with many conditions are hard to read and often fit noise.
Caveats
Rules describe how the model predicts. They do not show cause and effect. If two features are correlated, the tree may pick either one, and a small change in the training data can swap them. A different set of rules can then give almost the same accuracy. Check rules against the validation score before you trust them. A tree that overfits gives rules that are easy to read but do not generalize.
Exercise
A leaf covers 3 training samples, all of class "virginica", and sits at depth 6. Why should you hesitate to trust this rule, even though the leaf is perfectly pure?
Show answer
The rule rests on only 3 samples, so the purity may be chance. The depth of 6 means six conditions were stacked to isolate those samples, which is typical of overfitting. Check the rule on held-out data, or limit depth or raise minsamplesleaf and see whether the rule survives.