Sub topic 13
Reading a tree as rules
This chapter assumes you can train a scikit-learn DecisionTreeClassifier, you know what Gini impurity and a split threshold are, and you have seen feature importances. Here you will turn a fitted tree into if-then rules, trace one prediction, and judge how far you can trust those rules.
Why a tree is a rule list
Every path from the root to a leaf is a conjunction of conditions. Each internal node adds one test of the form feature <= threshold. A leaf holds the prediction. So a tree with L leaves is a set of L rules, and every input satisfies exactly one of them.
The three rules are:
- IF petal length <= 2.45 THEN setosa.
- IF petal length > 2.45 AND petal width <= 1.75 THEN versicolor.
- IF petal length > 2.45 AND petal width > 1.75 THEN virginica.
The rules do not overlap, and together they cover the whole feature space. A general rule list, such as one written by a domain expert, gives neither guarantee. This is why trees are easy to audit: you can show a reviewer the full decision logic on one page.
Exporting rules as text
export_text prints the tree with one indented line per test. The code below fits the depth-3 tree from earlier chapters and prints it.
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)
clf.fit(X_train, y_train)
print(export_text(clf, feature_names=data.feature_names, show_weights=True))The output follows this layout:
|--- petal length (cm) <= 2.45
| |--- class: 0
|--- petal length (cm) > 2.45
| |--- petal width (cm) <= 1.75
| | |--- ...Three details matter when you read it:
- A line ending in
class: kis a leaf. The number is the class index, not a name. Check it againstdata.target_names. - The
<=branch is the "yes" branch. The>branch is the "no" branch. A missing value is not handled this way, and it is a separate concern covered below. - With
show_weights=True, each leaf also lists how many training samples of each class reached it. Those counts tell you how pure the leaf is, and they matter more than the class label alone.
Tracing one prediction
A global rule dump answers "what does the model do". A stakeholder usually asks "why did it say that for this case". To answer, follow the path for a single row. decision_path returns a sparse matrix that marks every node the sample visits.
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
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)
def explain(model, x, feature_names, class_names):
tree = model.tree_
path = model.decision_path(x.reshape(1, -1)).indices
for node in path[:-1]:
f, t = tree.feature[node], tree.threshold[node]
op = "<=" if x[f] <= t else ">"
print(f"{feature_names[f]} = {x[f]:.2f} {op} {t:.2f}")
leaf = path[-1]
counts = tree.value[leaf][0]
share = counts / counts.sum()
k = int(np.argmax(share))
print(f"leaf {leaf}: {int(tree.n_node_samples[leaf])} training samples")
print(f"prediction: {class_names[k]} (leaf share {share[k]:.2f})")
explain(clf, X_test[0], data.feature_names, data.target_names)Each printed line is one condition the sample satisfied, written with the sample's own value. This makes the explanation concrete: "petal width = 1.90 > 1.75" is easier to check than "the tree went right".
The code normalizes tree.value[leaf] because scikit-learn versions differ. Older versions store raw class counts there, and newer ones store class fractions. Dividing by the sum gives a share in both cases.
Simplifying a rule
A raw path can test the same feature twice, for example x <= 5.0 and then x <= 3.2. Only the tightest bound matters, so you can merge these into x <= 3.2. Paths can also include conditions that never change the outcome. Both leaf siblings may predict the same class, which happens because the split still reduced impurity. In that case the split reduces uncertainty but does not change the label, and a rule summary can drop it.
When you present rules to non-specialists, three edits help:
- Round thresholds to sensible values. A threshold of 2.45 came from the midpoint between two training values. Presenting it as 2.5 changes the model slightly, so re-check accuracy if you do this.
- Name classes and features in domain language.
- Attach the leaf support (sample count) and purity to each rule.
How much to trust a rule
A readable rule is not automatically a reliable one. These are the main caveats.
Leaf purity is optimistic
A deep tree fits training data until leaves are pure. A leaf that says "100% versicolor" may hold three samples. The training share overstates the real probability of that class. Use n_node_samples to see support, and prefer rules backed by many samples. Pruning and min_samples_leaf raise the minimum support of every rule.
Rules are unstable
A small change in the training data can change the root split and rewrite the whole tree. Two trees with the same accuracy can give different rules. You can check this: fit trees on several bootstrap resamples and compare their root features and thresholds. If they disagree, treat any single rule as one plausible description, not as a finding about the world.
Correlated features hide each other
When two features carry almost the same information, the tree picks one at each split, often by a tiny margin. The other feature then looks irrelevant in the rules and in feature importances. Reading "the tree never uses feature B" as "feature B does not matter" is a common mistake.
Rules describe prediction, not cause
A rule such as "IF tenure <= 6 months THEN churn" says that the pattern held in the training data. It does not say that changing tenure would change churn. Splits also reflect how the data was collected, so a sampling bias in the data becomes a rule in the tree.
Thresholds are midpoints
The split search places each threshold halfway between two neighbouring training values. The exact number, like 2.45, is a product of the sample and is not a natural boundary. Do not describe it as a precise cutoff.
Missing values
Whether a tree handles missing values depends on the library and version. Recent scikit-learn releases support missing values in DecisionTreeClassifier for some splitters, and older ones raise an error. If your pipeline imputes values, the rules include the imputed values, so a rule can fire on a number that was never observed.
Size limits readability
Interpretability depends on size. A tree of depth 3 has at most 8 rules and fits on a screen. A tree of depth 12 can have thousands of leaves, and printing it does not make it understandable. The same controls you used against overfitting (max_depth, min_samples_leaf, ccp_alpha) are also your readability controls. When stakeholders need to review the model, choose the smallest tree whose cross-validated score is close to the best, because the extra accuracy of a larger tree rarely justifies rules nobody can read.
| Property | Shallow, pruned tree | Deep, unpruned tree |
|---|---|---|
| Number of rules | Few | Many |
| Leaf support | High | Often very low |
| Stability across resamples | Better | Poor |
| Readable by a reviewer | Yes | No |
Putting it into practice
- Fit and tune the tree with cross-validation as in earlier chapters.
- Print the rules with
export_text(..., show_weights=True). - For the cases that matter, run a path trace like
explain. - Check each leaf's support and class share before you quote it.
- Refit on a few bootstrap samples and see whether the top splits agree.
Exercise
A leaf in your exported tree reads "class: 1" with weights [0, 3, 0]. A colleague says this rule predicts class 1 with 100% certainty. What do you reply, and what two changes would make the rule more trustworthy?
Show answer
The leaf is pure on only 3 training samples, so 100% is a training share, not a reliable probability. The real chance of class 1 for new cases that reach this leaf could be much lower. To make such rules more trustworthy, raise the minimum support of each leaf (for example with a larger minsamplesleaf) and prune the tree with cost-complexity pruning (ccp_alpha) chosen by cross-validation. You can also check that the rule survives refitting on bootstrap resamples.
Exercise
In the explain function, why does the loop run over path[:-1] and not over every node in path?
Show answer
The last node in the path is the leaf. A leaf has no split test, so it has no feature or threshold to report. The loop prints only the internal nodes, and the leaf is handled afterwards to report its sample count and class share.