Sub topic 9
Pruning: pre-pruning and cost-complexity
This chapter assumes you can train a scikit-learn DecisionTreeClassifier. It also assumes you know that Gini impurity measures how mixed a node is, and that a tree grown without limits overfits. Here you will learn the two ways to control tree size: stopping growth early (pre-pruning) and cutting back a full tree (post-pruning, using cost-complexity pruning).
Why prune at all
A tree grown until every leaf is pure fits the training data perfectly, including its noise. Training accuracy reaches 100%, but validation accuracy falls behind. The tree has high variance: a small change in the training data can produce a very different tree.
Pruning limits complexity so the tree keeps only the splits that generalize. There are two families.
| Approach | When it acts | Mechanism | Main risk |
|---|---|---|---|
| Pre-pruning | While growing | Refuses a split that fails a rule | Stops too early and misses a useful split below a weak one |
| Post-pruning | After full growth | Removes subtrees that add little | Costs more compute, since the full tree must be built first |
Pre-pruning
Pre-pruning adds stopping rules to the greedy growth procedure. In scikit-learn these are hyperparameters of the tree.
max_depthcaps the number of levels below the root.min_samples_splitis the minimum number of samples a node needs before it may be split.min_samples_leafis the minimum number of samples each child must keep. A split that would create a smaller leaf is rejected.max_leaf_nodescaps the total number of leaves. The tree is then grown best-first, expanding the node with the largest impurity decrease.min_impurity_decreaserejects any split whose weighted impurity decrease is below the threshold.
These rules are cheap, because the tree never grows the parts that would be discarded. The weakness is that they are myopic. Growth is greedy, so a split that looks weak now may enable a very good split one level further down. The classic case is an XOR-like pattern. No single split improves purity much, but two levels of splits separate the classes perfectly. A strict min_impurity_decrease would stop at the root and never find it.
Choose pre-pruning values by cross-validation rather than by guessing:
from sklearn.datasets import load_iris
from sklearn.model_selection import GridSearchCV, 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
)
grid = GridSearchCV(
DecisionTreeClassifier(random_state=0),
param_grid={
"max_depth": [2, 3, 4, None],
"min_samples_leaf": [1, 3, 5, 10],
},
cv=5,
)
grid.fit(X_train, y_train)
print("best params:", grid.best_params_)
print("cv accuracy:", round(grid.best_score_, 3))
print("test accuracy:", round(grid.score(X_test, y_test), 3))The test set is used once, at the end. All choices are made from cross-validation on the training data.
Cost-complexity pruning
Cost-complexity pruning (also called weakest-link pruning) grows the full tree first, then removes branches. It scores a tree T with a penalized error:
R_alpha(T) = R(T) + alpha * |T|R(T)is the total impurity of the leaves, with each leaf weighted by the fraction of training samples it holds. It measures how well the tree fits the training data.|T|is the number of leaves.alpha(ccp_alphain scikit-learn) is a non-negative price per leaf.
When alpha = 0, the full tree wins, since it always has the lowest R(T). As alpha grows, each leaf costs more, so smaller trees become preferable. For a large enough alpha, the tree collapses to the root alone.
The weakest link
You do not need to try every possible subtree. For any internal node t, let T_t be the subtree rooted at t. Compare two options: keep the subtree, or collapse t into a single leaf. Collapsing raises the impurity from R(T_t) to R(t), and removes |T_t| - 1 leaves. The break-even alpha for that node is:
alpha_eff(t) = (R(t) - R(T_t)) / (|T_t| - 1)This is the impurity you lose per leaf you save. A small value means the subtree adds little for its size. The algorithm repeats these steps:
- Compute
alpha_efffor every internal node. - Collapse the node with the smallest value. That node is the weakest link.
- Recompute and repeat until only the root remains.
The result is a nested sequence of trees, each a pruned version of the one before. Each tree in the sequence is the best subtree for a range of alpha values.
Using it in scikit-learn
The method cost_complexity_pruning_path returns the sequence of effective alphas and the total leaf impurity of each pruned tree. You then choose one alpha by cross-validation:
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) guards against tiny negative values that floating-point arithmetic can produce for the first alpha. Scikit-learn rejects a negative ccp_alpha.
Choosing alpha well
Picking the alpha with the highest mean cross-validation score is the simplest rule, but it has two weaknesses.
- Ties and plateaus. On small datasets such as iris, many alphas give nearly identical scores. The loop above keeps the first best score, which is the smallest alpha and so the largest tree among the ties. A simpler tree with the same score is usually preferable.
- Noise in the estimate. A difference of 0.5 percentage points between two alphas is often within the fold-to-fold variation. Treating it as real selects noise.
A common remedy is the one-standard-error rule. Compute the mean and standard error of the cross-validation scores for each alpha. Find the best mean score, then choose the largest alpha whose mean is within one standard error of it. This picks the simplest tree that is statistically as good as the best one.
A second subtlety is that the alpha path comes from the full training set, but the cross-validation folds fit trees on 80% of it. Those trees have slightly different splits, so the same alpha value does not correspond to exactly the same pruned tree. The mismatch is small and is normally ignored, but it is one reason to prefer a coarse, stable choice of alpha over a fine one.
Comparing the two approaches
| Question | Pre-pruning | Cost-complexity |
|---|---|---|
| Number of knobs | Several (depth, leaf size, and so on) | One (`ccp_alpha`) |
| Sees the effect of deeper splits | No, it decides greedily | Yes, it prunes a fully grown tree |
| Training cost | Lower | Higher, since the full tree is grown |
| Interpretation of the knob | Direct (a depth of 3 is easy to understand) | Indirect (alpha is in impurity units per leaf) |
You can combine them. A loose min_samples_leaf of 3 to 5 removes tiny leaves cheaply, and ccp_alpha then does the fine tuning. Treat the combination as a joint search in GridSearchCV, because the best alpha depends on how large the tree already is.
Common mistakes
- Tuning on the test set. Selecting alpha or depth by looking at test accuracy leaks information. Use cross-validation on the training data.
- Comparing alphas across datasets. Alpha depends on the impurity scale and on the sample weighting. A good value for one problem means nothing for another.
- Reading a flat curve as success. If cross-validation scores barely change as the tree shrinks, the data may be easy, or the signal may be weak. Check the number of leaves, not only accuracy.
- Forgetting class imbalance. Pruning favors the majority class, because splitting off a small minority region rarely lowers total impurity enough to justify a leaf. Consider
class_weight="balanced"and a metric other than accuracy.
Exercise
A fitted tree has an internal node t with R(t) = 0.08. The subtree below t has 4 leaves and total leaf impurity R(Tt) = 0.02. What is the effective alpha for t, and at which values of ccpalpha is t collapsed into a leaf?
Show answer
alphaeff(t) = (0.08 - 0.02) / (4 - 1) = 0.06 / 3 = 0.02. The node is collapsed when ccpalpha is at least 0.02 (scikit-learn prunes a subtree when its effective alpha is less than or equal to ccp_alpha). For a smaller alpha, the subtree's reduction in impurity is worth its extra leaves, so it is kept.
Exercise
Why can pre-pruning with a strict minimpuritydecrease fail on an XOR-shaped dataset, and why does cost-complexity pruning not have this problem?
Show answer
On XOR data no single split lowers impurity much, so a strict minimpuritydecrease rejects the root split and the tree stops with one leaf, even though two levels of splits would separate the classes perfectly. Cost-complexity pruning first grows the full tree without any such test, so the useful two-level structure exists. It then judges the whole subtree by the impurity it removes per leaf, instead of judging each split in isolation.