Sub topic 9
Pruning: pre-pruning and cost-complexity
This chapter assumes you can train a scikit-learn tree, know why deep trees overfit, and can run cross-validation. Pruning limits tree size so the model generalizes better.
Two ways to prune
A fully grown tree keeps splitting until its leaves are pure. That fits noise in the training data. Pruning reduces this in two ways:
- Pre-pruning stops growth early. You set limits such as
max_depth,min_samples_leaf, ormin_impurity_decreasebefore training. - Post-pruning grows a large tree, then removes branches that add little. Scikit-learn implements cost-complexity pruning for this.
Pre-pruning is simple and fast. Its weakness is that it is short-sighted. A split that looks weak can enable a strong split below it, and a depth limit may cut that off. Post-pruning sees the whole tree before deciding.
How cost-complexity pruning works
Cost-complexity pruning scores a tree with this formula:
R_alpha(T) = R(T) + alpha * |leaves(T)|
Here R(T) is the total impurity of the leaves, and |leaves(T)| is the number of leaves. The parameter alpha is the price of each leaf. At alpha = 0 you keep the full tree. As alpha grows, the tree must justify every leaf, so smaller trees win.
The algorithm repeatedly removes the branch whose removal raises impurity the least per leaf saved (the "weakest link"). This produces a sequence of nested trees, from the full tree down to a single root node. Each tree in the sequence is optimal for a range of alpha values.
Choosing alpha with cross-validation
Scikit-learn gives you the candidate alphas through cost_complexity_pruning_path. You then pick the one with the best cross-validation score on the training data. The test set stays untouched until the end.
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_val_score
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
)
path = DecisionTreeClassifier(random_state=0).cost_complexity_pruning_path(X_train, y_train)
best_alpha, best_score = 0.0, -1.0
for alpha in path.ccp_alphas:
alpha = max(float(alpha), 0.0)
tree = DecisionTreeClassifier(random_state=0, ccp_alpha=alpha)
score = cross_val_score(tree, X_train, y_train, cv=5).mean()
if score > best_score:
best_alpha, best_score = alpha, score
pruned = DecisionTreeClassifier(random_state=0, ccp_alpha=best_alpha).fit(X_train, y_train)
print("chosen ccp_alpha:", best_alpha)
print("leaves:", pruned.get_n_leaves())
print("test accuracy:", pruned.score(X_test, y_test))The max(..., 0.0) guard protects against tiny negative values caused by floating-point error. The strict > comparison means ties go to the smaller alpha, which is the larger tree. If you prefer simpler models on ties, use >= so later (larger) alphas win.
Common errors
- Tuning on the test set. Choose alpha with cross-validation on training data only. Otherwise your test accuracy is optimistic.
- Combining everything blindly. Setting
max_depth,min_samples_leaf, andccp_alphatogether is allowed, but the limits interact. Tune one family at a time, or search them jointly withGridSearchCV. - Reading alpha across datasets. Alpha depends on the impurity scale and sample count. A value that works on one dataset says little about another.
- Expecting accuracy to always rise. Pruning mainly lowers variance. On clean data a pruned tree may score the same as the full tree with far fewer leaves, and that is still a win.
Exercise
A tree trained with ccpalpha=0 has 12 leaves. You raise ccpalpha to a larger value and refit. What happens to the number of leaves, and why?
Show answer
The number of leaves stays the same or decreases. A larger alpha charges more for each leaf, so branches whose impurity reduction does not cover that cost are pruned away.
Exercise
Why is cost-complexity pruning less short-sighted than a max_depth limit?
Show answer
It grows the full tree first, so it can keep a weak split that leads to a strong split below it. A depth limit cuts growth before that later split is ever seen.