Overfitting, Pruning and Real-World Trees
ID3 keeps splitting until every leaf is pure. On clean data that's fine. On real data with noise, "pure leaves" means memorizing the noise: one leaf for every weird delivery that happened to be late because the security guard was chatty. You've seen this disease before, in §2.2 with polynomials.
Watching a tree overfit
Bolt's late-delivery data has two numeric features, distance (km) and hour (18:00 to 02:00, written 18–26). The true rule is "late if distance > 3.2, or if it's 21:00–23:00 and distance > 1.5." On top of that, 15% of labels are flipped at random: unexplained lateness. So even a perfect model can reach only about 85% accuracy. We grow trees of increasing maximum depth:
import numpy as np
rng = np.random.default_rng(1)
def make_orders(n):
dist = rng.uniform(0, 5, n) # km
hour = rng.uniform(18, 26, n) # 18:00 .. 02:00
late = (dist > 3.2) | ((hour > 21) & (hour < 23) & (dist > 1.5)) # the true rule
flip = rng.random(n) < 0.15 # 15% label noise: unexplained lateness
return np.column_stack([dist, hour]), (late ^ flip).astype(int)
X_tr, y_tr = make_orders(200)
X_te, y_te = make_orders(5000)
def entropy(y):
p = np.bincount(y, minlength=2) / len(y)
p = p[p > 0]
return -(p * np.log2(p)).sum()
def best_split(X, y):
best = (0.0, None, None) # (gain, feature, threshold)
H = entropy(y)
for f in range(X.shape[1]):
values = np.unique(X[:, f])
for t in (values[:-1] + values[1:]) / 2: # candidate thresholds: midpoints
left = X[:, f] <= t
g = H - (left.mean() * entropy(y[left]) + (~left).mean() * entropy(y[~left]))
if g > best[0]:
best = (g, f, t)
return best
def grow(X, y, depth, max_depth):
if depth == max_depth or entropy(y) == 0:
return int(np.bincount(y, minlength=2).argmax())
g, f, t = best_split(X, y)
if f is None:
return int(np.bincount(y, minlength=2).argmax())
left = X[:, f] <= t
return (f, t, grow(X[left], y[left], depth + 1, max_depth), grow(X[~left], y[~left], depth + 1, max_depth))
def predict(node, x):
while isinstance(node, tuple):
f, t, l, r = node
node = l if x[f] <= t else r
return node
def accuracy(tree, X, y):
return np.mean([predict(tree, x) == t for x, t in zip(X, y)])
print("depth | train acc | test acc")
for d in [1, 2, 3, 4, 6, 8, 12, 20]:
tree = grow(X_tr, y_tr, 0, d)
print(f"{d:5d} | {accuracy(tree, X_tr, y_tr):9.3f} | {accuracy(tree, X_te, y_te):8.3f}")depth | train acc | test acc
1 | 0.815 | 0.778
2 | 0.815 | 0.778
3 | 0.840 | 0.776
4 | 0.915 | 0.823
6 | 0.950 | 0.787
8 | 0.980 | 0.772
12 | 1.000 | 0.758
20 | 1.000 | 0.758
It's the U-shape again, now in accuracy (so it's upside down). Training accuracy climbs to a perfect 1.000. Test accuracy peaks at depth 4 (0.823, close to the ~0.85 ceiling) and then declines as the tree carves out tiny regions around noisy points. Depth is the tree's complexity knob, just like polynomial degree.
Two ways to stop overfitting
1. Pre-pruning (early stopping)
Stop growing a branch when:
- a maximum depth is reached;
- a node has fewer than
min_samplesexamples; - the best gain is below a threshold;
- the split is not statistically significant, which is the χ² test.
χ² pruning (AIMA §19.3) asks: is this split's apparent gain real, or could it come from random noise? Suppose a node has \(p\) positives and \(n\) negatives, and a split sends \(p_k, n_k\) to child \(k\). If the attribute were irrelevant, we'd expect \(\hat p_k = p \cdot \frac{p_k+n_k}{p+n}\) positives in child \(k\) (and similarly \(\hat n_k\)). The deviation
$$ \Delta = \sum_k \frac{(p_k - \hat p_k)^2}{\hat p_k} + \frac{(n_k - \hat n_k)^2}{\hat n_k} $$follows a χ² distribution with \(v-1\) degrees of freedom under the "irrelevant" hypothesis. If \(\Delta\) is below the 5% critical value, the split is not significant, so don't make it.
The danger of pre-pruning is the horizon effect. A split might look useless on its own but enable great splits below it. XOR is the extreme case: neither attribute alone has any gain.
2. Post-pruning (grow, then cut)
Grow the full tree, then remove parts that don't help. This is usually better, because it sees the whole tree before deciding.
Reduced-error pruning (simple and effective):
- Split the data into training and validation sets (§2.4).
- Grow the full tree on the training set.
- For each internal node (bottom-up), try replacing its subtree with a leaf predicting the majority class. If validation accuracy doesn't decrease, keep the change.
- Repeat until any further pruning would hurt validation accuracy.
Rule post-pruning (C4.5): convert the tree into one rule per path, remove any precondition whose removal doesn't hurt the estimated accuracy, then sort the rules by accuracy. Rules are pruned independently, which is more flexible than cutting whole subtrees.
Cost-complexity pruning (CART, and scikit-learn's ccp_alpha): minimize \(\text{Error}(T) + \alpha \cdot |\text{leaves}(T)|\). This is regularization exactly as in §2.4: a penalty on complexity, with \(\alpha\) tuned by cross-validation.
Max depth is polynomial degree. Cost-complexity \(\alpha\) is ridge's \(\lambda\). Reduced-error pruning is validation-based model selection. χ² pruning is a statistical test of "signal vs noise." Every model family has a complexity knob, and the bias–variance tradeoff always applies.
Real-world extensions
Continuous attributes
For a numeric attribute like distance, test a threshold "distance ≤ t". Which values of t should you try? Sort the examples by the attribute. The only thresholds that can be optimal are midpoints between adjacent examples with different labels. For \(n\) examples there are at most \(n-1\) candidates, so evaluate the gain of each and keep the best. (The code above tries all midpoints, which is simpler and slightly slower.) A numeric attribute can be reused deeper in the tree with a different threshold, unlike a categorical attribute in ID3.
Temperature: 40, 48, 60, 72, 80, 90 with labels No, No, Yes, Yes, Yes, No. The label changes between 48→60 and between 80→90, so the candidates are \(t = 54\) and \(t = 85\).
- \(t=54\): ≤54 gives [0+, 2−] (H = 0), >54 gives [3+, 1−] (H = 0.811). Remainder = \(\frac46(0.811) = 0.541\). H(parent) = B(3/6) = 1, so the gain is 0.459.
- \(t=85\): ≤85 gives [3+, 2−] (H = 0.971), >85 gives [0+, 1−] (H = 0). Remainder = \(\frac56(0.971) = 0.809\), so the gain is 0.191.
Choose \(t = 54\).
Missing values
- Fill in the most common value at that node (among examples with the same class, if known).
- C4.5 sends a fraction of the example down each branch, proportional to how many training examples went each way, and combines the predictions with those weights.
Attributes with costs
If measuring an attribute is expensive (a blood test vs. asking a question), use \(\text{Gain}^2/\text{Cost}\) or similar, which trades informativeness against cost. This is value of information versus price, as in §5.1.
Regression trees
To predict a number, each leaf stores the mean of its examples, and splits are chosen to reduce variance (equivalently, squared error) instead of entropy. It's the same algorithm with a different impurity measure.
Ensembles: making high variance an asset
Single trees are unstable, as you saw when deleting D3 in §6.3 flipped the root. §2.3 told us that averaging models trained on different data reduces variance. Two hugely successful methods build on this:
- Random forests (bagging): train hundreds of deep trees, each on a bootstrap resample of the data, and each choosing from a random subset of features at every split. Average their votes. The individual trees overfit in different ways, and averaging cancels the noise. This is often the best "out-of-the-box" model for tabular data.
- Gradient boosting (XGBoost, LightGBM): train shallow trees sequentially, each one fitting the errors of the ensemble so far. Boosting reduces bias. It wins a large share of tabular ML competitions.
from sklearn.tree import DecisionTreeClassifier, export_text
from sklearn.model_selection import cross_val_score
for depth in [2, 4, 6, None]:
clf = DecisionTreeClassifier(criterion="entropy", max_depth=depth, random_state=0)
print(depth, cross_val_score(clf, X_tr, y_tr, cv=5).mean())
clf = DecisionTreeClassifier(criterion="entropy", max_depth=4).fit(X_tr, y_tr)
print(export_text(clf, feature_names=["distance", "hour"])) # human-readable rulescriterion="entropy" gives information gain, and the default is Gini. Tune max_depth, min_samples_leaf or ccp_alpha by cross-validation, never on the test set.
Chapter summary
- Trees = readable disjunctions of conjunctions. They can represent any Boolean function, but some only with huge trees.
- Entropy \(H = -\sum p \log_2 p\) measures impurity. Gain = H(parent) − weighted H(children).
- ID3 is greedy hill climbing on gain, with inductive bias toward short trees and high-gain attributes near the root.
- Information gain favours many-valued attributes, so use gain ratio. Gini is a common alternative.
- Trees overfit as depth grows. Control them with pre-pruning (depth, χ²) or post-pruning (reduced-error, cost-complexity).
- Trees have high variance, and random forests average it away.