Sub topic 7
Why deep trees overfit
This chapter assumes you can read basic Python and scikit-learn code. You should know what training and test sets are, and you should have seen how a tree picks splits with Gini impurity (the previous chapters cover this). Here we look at what goes wrong when a tree keeps splitting. We cover how to see the problem, why it happens, and why trees are especially prone to it.
What overfitting means for a tree
A model overfits when it learns patterns that belong to the training sample but not to the process that produced the data. Its training score looks excellent. Its score on new data is clearly worse.
A decision tree can overfit more easily than most models. With no limits, the growing procedure keeps splitting until every leaf is pure, or until no feature can separate the remaining samples. If no two training rows have identical features but different labels, such a tree reaches 100% training accuracy. That perfect score does not show the tree is good. It shows the tree can memorize.
Seeing the gap
The script below builds a dataset where 15% of labels are flipped at random. This simulates label noise. It then trains trees of increasing depth and prints training and test accuracy.
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(
n_samples=600,
n_features=10,
n_informative=3,
n_redundant=0,
flip_y=0.15,
class_sep=1.0,
random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
print("depth leaves train test")
for depth in [1, 2, 3, 4, 6, 8, 12, None]:
clf = DecisionTreeClassifier(max_depth=depth, random_state=0)
clf.fit(X_train, y_train)
print(
f"{str(depth):>5} {clf.get_n_leaves():>6} "
f"{clf.score(X_train, y_train):.3f} {clf.score(X_test, y_test):.3f}"
)Exact numbers depend on your scikit-learn version, but the pattern is stable:
- Training accuracy rises with depth and reaches 1.000 for the unlimited tree.
- Test accuracy rises at first, flattens, and then stays flat or drops.
- The number of leaves grows quickly. Past a certain depth, the tree adds leaves that fit noise.
The distance between the training and test columns is the generalization gap. Its growth is the main symptom of overfitting.
Why the tree keeps splitting on noise
Three properties of the algorithm combine to produce this behavior.
Splitting never makes impurity worse
Gini impurity and entropy are concave functions of the class proportions. Because of this, the weighted impurity of two children is never higher than the impurity of the parent. A split that only separates noise still has a decrease of zero or more. Unless you set a stopping rule, the tree has no built-in reason to refuse it.
Each level has less data
Suppose a split divides a node roughly in half. After about 8 levels, a 420-sample training set leaves nodes with only a handful of samples each. Every later split is chosen using that handful. Impurity computed from 5 samples is a very noisy estimate of the true class mix at that region of feature space. The tree picks the feature and threshold that best fit those 5 points, and with 10 features and many candidate thresholds, some split will always look good by chance.
Greedy search commits early
The tree picks the best split at each node and never revisits it. A split that is chosen because of a few noisy rows near the top changes every subtree below it. This makes the whole structure sensitive to the sample, as the next section shows.
Overfitting as variance
In statistical terms, a model's error has a bias part and a variance part. Bias is error from assumptions that are too simple. Variance is how much the fitted model changes when the training sample changes.
A shallow tree has high bias and low variance. A depth-1 tree (a stump) cannot represent many real patterns, but it changes little from one sample to the next. A fully grown tree has low bias and high variance. It can represent almost any pattern, but small changes in the data produce a different tree.
| Setting | Bias | Variance | Typical symptom |
|---|---|---|---|
| Very shallow tree | High | Low | Train and test both low |
| Moderate depth | Medium | Medium | Train a bit above test |
| Fully grown tree | Low | High | Train near 1.0, test much lower |
You can measure variance directly. The next script trains many trees on bootstrap resamples of the training set (random draws with replacement, same size as the original). It then reports how often an individual tree's test prediction disagrees with the majority vote of all of them. A high rate means the predictions depend heavily on which rows were in the sample.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(
n_samples=600,
n_features=10,
n_informative=3,
n_redundant=0,
flip_y=0.15,
class_sep=1.0,
random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
rng = np.random.RandomState(0)
def disagreement(depth, n_models=30):
preds = []
for _ in range(n_models):
idx = rng.choice(len(X_train), size=len(X_train), replace=True)
clf = DecisionTreeClassifier(max_depth=depth, random_state=0)
clf.fit(X_train[idx], y_train[idx])
preds.append(clf.predict(X_test))
preds = np.array(preds)
majority = (preds.mean(axis=0) >= 0.5).astype(int)
return (preds != majority).mean()
for depth in [2, 4, 8, None]:
print(f"depth={depth}: disagreement with majority = {disagreement(depth):.3f}")Expect the disagreement rate to grow with depth. This is the instability that bagging and random forests later exploit, because averaging many high-variance trees cancels part of the variance.
Signal versus noise in the data
Noise is not the only cause. Three data conditions make overfitting worse.
- Label noise. Mislabeled or inherently random outcomes give the tree something to memorize. Noise in the target is the most common reason for the pattern above.
- Small samples. Fewer rows mean the later splits rest on very few points.
- Many irrelevant or high-cardinality features. Each extra feature adds more candidate splits, so the chance that some split looks useful by luck increases. A categorical feature with many levels, or an ID-like numeric column, can be used to isolate individual rows.
An ID column is the extreme case. If every row has a unique value, a tree can use it to carve out one row per leaf and reach perfect training accuracy without learning anything.
Diagnosing overfitting in practice
Use these checks, in this order:
- Compare training and held-out scores. A large gap (for example 1.00 versus 0.80) is the first warning.
- Look at tree size. Compare
get_n_leaves()andget_depth()with the number of training rows. If leaves are close to the number of rows, the tree is memorizing. - Inspect leaf sizes. Many leaves with 1 to 3 samples are a red flag. The
tree_.n_node_samplesarray shows the sample count at every node. - Plot a validation curve. Score on held-out data across a range of depths. The best depth is near the point where the held-out score stops improving.
The snippet below prints how many leaves hold very few samples in the unlimited tree from the first script's data.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
X, y = make_classification(
n_samples=600,
n_features=10,
n_informative=3,
n_redundant=0,
flip_y=0.15,
class_sep=1.0,
random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0, stratify=y
)
clf = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
tree = clf.tree_
is_leaf = tree.children_left == -1
leaf_sizes = tree.n_node_samples[is_leaf]
print("training rows:", len(X_train))
print("depth:", clf.get_depth(), "leaves:", clf.get_n_leaves())
print("leaves with <= 3 samples:", int(np.sum(leaf_sizes <= 3)))
print("median leaf size:", float(np.median(leaf_sizes)))A median leaf size of 1 or 2 on a noisy dataset confirms the tree has split down to individual points.
Common mistakes
- Tuning on the test set. If you pick the depth by looking at test accuracy and then report that same number, the estimate is optimistic. The next chapter covers cross-validation, which fixes this.
- Reading a single train/test split as exact. On small data, one split can give a noisy gap. The conclusion that deep trees overfit holds across splits, but the exact numbers move.
- Assuming more depth is always worse. Some datasets are nearly noise-free, and deeper trees help for longer. The right depth depends on the data.
- Confusing a large tree with an overfit tree. Overfitting is defined by the gap to held-out performance, not by size alone.
The remedies are stopping rules and pruning, which later chapters cover. Both reduce variance by accepting some extra bias.
Exercise
A fully grown decision tree scores 1.00 on training data and 0.79 on a held-out test set. You then set max_depth=4 and get 0.88 on training data and 0.82 on the test set. Which tree is better, what changed in terms of bias and variance, and why is the second tree's lower training score not a problem?
Show answer
The depth-4 tree is better because it scores higher on held-out data (0.82 versus 0.79), and held-out performance is what matters. Limiting depth added some bias (it can no longer fit every training row, so the training score fell from 1.00 to 0.88) and reduced variance (it no longer memorizes noise, so the gap shrank from 0.21 to 0.06). A lower training score is expected when a model stops fitting noise. A caveat is that if you chose depth 4 by looking at this test set, the 0.82 is slightly optimistic and should be confirmed with cross-validation.
Exercise
Why does a tree with no stopping rule still choose to split a node whose remaining label differences are pure noise, and why do those splits tend to be unreliable?
Show answer
Weighted child impurity is never higher than the parent's impurity for Gini or entropy, so any split has a decrease of zero or more, and the tree has no reason to stop while a node is impure. The splits are unreliable because deep nodes contain only a few samples. Impurity estimated from so few points is dominated by chance, and with many features and thresholds to try, some candidate will separate those few points well by luck. That split does not carry over to new data.