Sub topic 3
Why Single Trees Overfit: Bias and Variance
This chapter assumes you know how a decision tree picks splits (the previous chapter), what a train/test split is, and how to read accuracy and mean squared error. It explains why a fully grown tree scores almost perfectly on its training data and still predicts poorly on new data. It also sets up the reason a forest of trees can fix this.
Two sources of error
Suppose you collect a training set, fit a model, and measure its error on new data. The error comes from three parts. For squared error at a point x it splits like this:
expected error = bias^2 + variance + irreducible noise- Bias is the gap between the model's average prediction and the true value. The average is taken over many different training sets drawn from the same source. High bias means the model class is too rigid to capture the real pattern. This is called underfitting.
- Variance is how much the prediction at x changes from one training set to another. High variance means the model is sensitive to the particular samples it saw. This is called overfitting.
- Irreducible noise is randomness in the labels that no model can predict, such as mislabeled rows or hidden factors.
You only ever have one training set, so bias and variance are not directly visible. They are properties of the learning procedure across hypothetical training sets. You can estimate them by resampling, and this chapter does that below.
The decomposition above is exact for squared error, which makes it a clean fit for regression. For classification with 0/1 loss the pieces do not add up as neatly. The intuition still holds, and the code later in this chapter measures variance as disagreement between models.
Why a fully grown tree has low bias
By default, scikit-learn's DecisionTreeClassifier keeps splitting until every leaf is pure or cannot be split further. Each split carves the feature space into smaller rectangles. With no depth limit, the tree can build a rectangle around nearly any individual training point.
This gives the tree very low bias. It can represent very complicated decision boundaries, so the average prediction across training sets can get close to the truth. It also drives training error to zero in most datasets. The exception is rows with identical features and different labels, which no split can separate.
Zero training error is not evidence of a good model. It is a warning sign, because the tree is flexible enough to memorize.
Why it also has high variance
A tree that memorizes also memorizes noise. Consider a region of the data where 90% of the labels are class 1 and 10% are class 0 by chance. A shallow tree predicts class 1 for the whole region. A deep tree keeps splitting until it isolates each class 0 point in its own tiny leaf. On new data those leaves fire at random and produce wrong predictions.
Trees have a second, structural source of variance: splits are chosen greedily from the top down, so early decisions determine everything below them. If a small change in the data makes a different feature slightly better at the root, the whole subtree below it is built from different partitions. The change cascades.
Two more details make this worse:
- Few samples per leaf. Deep in the tree, each decision rests on a handful of rows. A statistic computed from five rows is noisy, so the chosen threshold is noisy.
- Piecewise-constant output. A tree predicts a constant in each rectangle. A smooth or diagonal boundary is approximated by a staircase, and the exact position of the steps depends on the sample.
Seeing the trade-off
The experiment below fits trees of increasing depth on a dataset where 10% of the labels are flipped at random (flip_y=0.1). This label noise makes the effect easy to see.
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=1000, n_features=20, n_informative=5,
flip_y=0.1, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0
)
for depth in [1, 2, 3, 5, 8, 12, None]:
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
tree.fit(X_train, y_train)
print(
f"max_depth={str(depth):>4} "
f"train={tree.score(X_train, y_train):.3f} "
f"test={tree.score(X_test, y_test):.3f} "
f"leaves={tree.get_n_leaves()}"
)The exact numbers depend on your scikit-learn version, but the pattern is stable:
- Training accuracy rises with depth and reaches 1.000 when
max_depth=None. - Test accuracy rises at first, then flattens or falls. The fully grown tree typically has the largest gap between train and test accuracy.
- The number of leaves grows quickly. A tree with hundreds of leaves on 700 training rows has roughly one or two rows per leaf.
| Setting | Bias | Variance | Train accuracy | Test accuracy |
|---|---|---|---|---|
| Very shallow (`max_depth=1`) | High | Low | Low | Low, close to train |
| Moderate depth | Medium | Medium | Medium | Usually the best |
| Fully grown | Low | High | Near 1.0 | Noticeably below train |
The gap between train and test accuracy is a cheap diagnostic. A large gap points to variance. If both are poor and close together, the problem is bias.
Measuring variance directly
You can measure variance by simulating "many training sets". Draw many random subsets of the training data, fit a tree on each, and check how often individual trees disagree with the majority prediction on the same test points.
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=1000, n_features=20, n_informative=5,
flip_y=0.1, random_state=0,
)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=0
)
rng = np.random.default_rng(0)
half = len(X_train) // 2
for depth in [3, None]:
preds = []
for _ in range(50):
idx = rng.choice(len(X_train), size=half, replace=False)
tree = DecisionTreeClassifier(max_depth=depth, random_state=0)
tree.fit(X_train[idx], y_train[idx])
preds.append(tree.predict(X_test))
preds = np.array(preds) # shape (50, n_test)
majority = preds.mean(axis=0) > 0.5
disagreement = (preds != majority).mean()
print(f"max_depth={str(depth):>4} disagreement with majority={disagreement:.3f}")Each of the 50 trees sees a different half of the data. If the learning procedure had low variance, the trees would mostly agree. The fully grown trees disagree with the majority noticeably more often than the depth-3 trees. That extra disagreement is variance. The depth-3 trees are more stable but have higher bias, so their stability is not free.
Fixing variance by constraining the tree
One remedy is to limit how much the tree can memorize. This is called regularization or pruning. The main controls in scikit-learn are:
max_depth: caps the number of splits along any path.min_samples_leaf: requires each leaf to hold at least this many rows, which stops the tree from isolating single points.min_samples_split: refuses to split nodes with fewer rows than this.ccp_alpha: cost-complexity pruning, which removes branches whose improvement is too small for their size.
These controls trade variance for bias. A smaller tree is more stable, but it can no longer represent fine structure. You choose the setting by cross-validation, and the best setting still leaves a single tree with a real compromise between the two errors.
The other remedy: average many trees
There is a different way to reduce variance without increasing bias much. Grow deep, low-bias trees, each on a different resampled dataset, and average their predictions. Averaging cancels the parts of each tree's error that are due to its particular sample.
For B models whose predictions each have variance s² and pairwise correlation r, the variance of their average is:
variance of average = r * s^2 + (1 - r) * s^2 / BThis formula sets up the rest of the tutorial:
- If the trees were independent (r = 0), variance would shrink as 1/B, so adding trees would drive it toward zero.
- If the trees were identical (r = 1), averaging would change nothing.
- In practice trees trained on overlapping data are correlated, so the first term, r times s², sets a floor. To go lower, you must make the trees less correlated.
The next chapters build on these two goals. Bootstrap sampling and bagging produce different datasets for each tree. Random feature subsets at each split then lower the correlation r.
Edge cases and common mistakes
- Reading training accuracy as quality. A fully grown tree scores near 100% on training data by construction. Compare train and test scores, or use cross-validation.
- Assuming more depth means better. On clean, low-noise data a deep tree may generalize fine. Overfitting depends on the noise level and sample size, not on depth alone.
- Confusing variance with randomness at training time. A tree with a fixed
random_stateis deterministic. The variance here is about sensitivity to the data, not to the random seed. Seed-related variation does exist when ties between features are broken randomly, but it is small compared to data-driven variation. - Ignoring bias in shallow trees. If a tree is already stable and still inaccurate, averaging more copies will not help. Averaging reduces variance, not bias.
- Duplicated feature vectors with different labels. No tree can reach 100% training accuracy there. The training score caps at the fraction of rows the leaves can separate.
Exercise
A fully grown decision tree scores 1.00 on its training set and 0.82 on a held-out test set. A depth-2 tree scores 0.78 on training and 0.77 on test. Which model has higher variance, which has higher bias, and why?
Show answer
The fully grown tree has higher variance. Its large gap between train and test scores (0.18) shows it fits the particular training sample, including noise. The depth-2 tree has higher bias. Its training score is low (0.78), so it cannot capture the pattern even on data it has seen, and its small train-test gap (0.01) shows it is stable. The fully grown tree still has the better test score, so lower bias outweighs higher variance here.
Exercise
Using the formula variance of average = r s^2 + (1 - r) s^2 / B, suppose s^2 = 1.0 and r = 0.3. What is the variance of the average for B = 10 and for B = 1000? What does the result say about adding more trees?
Show answer
For B = 10: 0.3 + 0.7 / 10 = 0.37. For B = 1000: 0.3 + 0.7 / 1000 = 0.3007. Going from 10 to 1000 trees lowers the variance only from 0.37 to about 0.30. The floor is r * s^2 = 0.3, so beyond a point more trees help little. To reduce variance further you must lower the correlation r between trees.