Skip to content
BIASED

Bagging and random forests

Trees grown on bootstrap samples and averaged, the variance of an average of correlated trees and its floor, random feature subsets, out-of-bag error and the 63.2%, the traps of feature importance, and extremely randomized trees.

One training set, many trees

The topic Bias–variance decomposition found the weak spot of a deep tree: its bias is small and its variance is large. It also found the cure in principle. An average of models trained by the same procedure has the same expectation as one of them, so it keeps the small bias, while its variance can be much smaller.

The catch is practical. Averaging over independent training sets needs many training sets, and we have one. The bootstrap from the topic Confidence intervals and the bootstrap (Probability Theory) gets around this: a resample of nn points drawn with replacement from the training set DD stands in for a fresh training set from the same distribution.

Bagging (bootstrap aggregation, Breiman, 1996) uses resamples to manufacture training sets.

  1. Draw BB bootstrap samples of nn points each from DD.
  2. Grow a tree on each, to full depth, without pruning.
  3. Average the trees: their mean prediction for regression; for classification (classes {0,1}\{0, 1\} in this topic), the mean of their class-1 probabilities or a majority vote.

With Tb(x)T_b(x) the prediction of tree bb, the ensemble predicts

f^B(x)=1B∑b=1BTb(x).\hat f_B(x) = \frac1B \sum_{b=1}^B T_b(x).

The trees are identically distributed, so the expectation of their average is the expectation of one bootstrap tree. Bagging does not change the bias, apart from a small increase: each tree sees only about 63% of the distinct points and is slightly cruder than a tree on all of DD. All the gain is in the variance.

So bagging helps unstable methods, whose output moves a lot when a few training points change: deep trees, greedy selection of a feature subset, neural networks. For stable methods it gains little and can slightly hurt. Nearest neighbours with a large kk already average many targets. Least squares on a few features barely moves between resamples. The sample mean does not move at all on average: averaged over resamples, the bootstrap mean is the sample mean itself.

How much variance is left

At a fixed point xx, let τ2(x)\tau^2(x) be the variance of one tree's prediction over the randomness of DD and of the resampling. This is not σ2\sigma^2, the noise variance. If the BB trees were independent, the variance of their average would be τ2/B\tau^2 / B.

They are not independent: all of them grow from the same DD. That is why, in the topic Bias–variance decomposition, fifty bagged trees cut the variance of a deep tree about sevenfold, not fiftyfold.

The topic Joint distributions and independence (Probability Theory) averaged nn estimates with a common variance and a common pairwise correlation. Here the estimates are trees. With ρ(x)\rho(x) the correlation between the predictions of two trees, that result reads

Var⁡f^B(x)=ρτ2+1−ρB τ2.\operatorname{Var} \hat f_B(x) = \rho\tau^2 + \frac{1 - \rho}{B}\,\tau^2 .

The second term vanishes as BB grows. The first one is a floor. With toy numbers τ2=1\tau^2 = 1 and ρ=0.3\rho = 0.3, one tree has variance 11, ten trees 0.3+0.07=0.370.3 + 0.07 = 0.37, a hundred trees 0.3070.307, and no number of trees goes below 0.30.3.

Beyond a few dozen trees, more trees buy almost nothing. Only a smaller ρ\rho can lower the floor. To lower it, we first need to know where the correlation comes from.

Where the correlation comes from

Each tree has two sources of randomness: the training set DD, shared by all trees, and its own draw Θb\Theta_b, the bootstrap sample (and, in the next block, random features). Given DD, the draws Θ1,…,ΘB\Theta_1, \dots, \Theta_B are independent. Write TT for the prediction at xx of one such tree.

Condition on DD and apply the law of total variance from the topic Conditional expectation (Probability Theory):

Var⁡f^B=Var⁡D(E[f^B∣D])+ED[Var⁡(f^B∣D)].\operatorname{Var} \hat f_B = \operatorname{Var}_D\big(\mathbb E[\hat f_B \mid D]\big) + \mathbb E_D\big[\operatorname{Var}(\hat f_B \mid D)\big].

Given DD, the ensemble averages BB independent, identically distributed trees. Its conditional mean is that of one tree, and its conditional variance is 1/B1/B of one tree's:

Var⁡f^B=Var⁡D(E[T∣D])+1B ED[Var⁡(T∣D)].\operatorname{Var} \hat f_B = \operatorname{Var}_D\big(\mathbb E[T \mid D]\big) + \frac1B\, \mathbb E_D\big[\operatorname{Var}(T \mid D)\big].

At B=1B = 1 this splits the variance of one tree into two parts:

τ2=Var⁡D(E[T∣D])⏟from the training set+ED[Var⁡(T∣D)]⏟from the resampling.\tau^2 = \underbrace{\operatorname{Var}_D\big(\mathbb E[T \mid D]\big)}_{\text{from the training set}} + \underbrace{\mathbb E_D\big[\operatorname{Var}(T \mid D)\big]}_{\text{from the resampling}} .

This formula and the one of the previous block hold for every BB, so their parts match: ρτ2=Var⁡D(E[T∣D])\rho\tau^2 = \operatorname{Var}_D(\mathbb E[T \mid D]) and (1−ρ)τ2=ED[Var⁡(T∣D)](1 - \rho)\tau^2 = \mathbb E_D[\operatorname{Var}(T \mid D)] (Hastie, Tibshirani and Friedman, 2009, Section 15.4.1).

Averaging removes the variance that the resampling adds and none of the variance that the training set causes. The floor is the variance of the infinitely large ensemble E[T∣D]\mathbb E[T \mid D]. It is a variance, so ρ≥0\rho \ge 0 always. To lower the floor, the trees must depend less on the training set as a whole: they must be decorrelated.

Random forests: decorrelating the trees

Bagged trees are alike because they are grown greedily from similar samples. If one feature predicts the target well, nearly every bootstrap tree splits on it at the root, and the trees share their top structure.

A random forest (Breiman, 2001) changes one line of the tree-growing algorithm. At every split, draw mm of the dd features at random and search for the best split among those mm only. Different trees, and different nodes of one tree, are forced to use different features, so the trees are less correlated. Each tree also gets worse: its bias and its variance τ2\tau^2 grow. So mm trades ρ\rho against τ2\tau^2 and the bias.

The recommended defaults are m=⌊d⌋m = \lfloor \sqrt d \rfloor with leaves of size 1 for classification, and m=⌊d/3⌋m = \lfloor d/3 \rfloor with leaves of size 5 for regression, but mm is a parameter to tune. Bagging is the case m=dm = d. Library defaults differ: scikit-learn's RandomForestClassifier draws d\sqrt d features, while RandomForestRegressor uses all dd, so its default regression forest is bagging.

Take Friedman's function in 10 dimensions, five of them irrelevant, with n=200n = 200 and noise σ2=1\sigma^2 = 1. Estimating the two parts of the previous block from 40 training sets with 25 trees each gives, for one tree:

τ2\tau^2 ρ\rho floor ρτ2\rho\tau^2 bias²
bagging, m=10m = 10 11.11 0.105 1.17 3.83
forest, m=3m = 3 15.52 0.043 0.66 5.26

A bootstrap tree varies more than the full-sample tree of the previous topic (11.1111.11 against 9.349.34), because its resample adds randomness of its own. The bias² of bagging, 3.833.83, is the previous topic's 3.613.61 up to simulation noise.

The forest's trees are individually worse, but their correlation falls by more than half, and the floor falls from 1.171.17 to 0.660.66. Yet the forest loses. The restricted search often misses the five relevant features, and the extra bias eats the gain: with unlimited trees, the expected test error is about 1+3.83+1.17=6.01 + 3.83 + 1.17 = 6.0 for bagging and 1+5.26+0.66=6.91 + 5.26 + 0.66 = 6.9 for the forest.

When the signal is spread over many features, the trade goes the other way. Take two Gaussian classes in 30 dimensions, each feature carrying a little of the signal, as the pixels of an image do, with 300 training points. On 2,000 new points a single tree errs on 34.3% of them with all 30 features and on 36.4% with m=5m = 5. After 150 trees, bagging errs on 20.4% and the forest on 18.0%.

More trees do not overfit

Extra depth makes a tree overfit. Extra trees do not do that to a forest. As BB grows, f^B\hat f_B converges to its limit E[T∣D]\mathbb E[T \mid D] (Breiman, 2001), and new trees only remove the random variation around that limit.

In the 30-dimensional example the forest's test error is 39.1% with its first tree alone, then 25.3% with 10 trees, 19.3% with 50, 18.0% with 150 and 17.4% with 500. For squared error the expected test error falls with every tree, as the variance formula shows. The curve of one particular forest can still wobble on the way, and a majority vote need not improve at every step.

The limit itself can overfit. If it does, the fix is the trees: their depth or the minimum leaf size are tuned, not their number.

A forest has a second reading. For regression, a tree predicts at xx the mean target of the training points in the leaf of xx. So a forest predicts a weighted average of the training targets,

f^B(x)=∑i=1nwi(x) yi,\hat f_B(x) = \sum_{i=1}^n w_i(x)\, y_i ,

where wi(x)w_i(x) is the average over trees of [xi shares a leaf with x]/(leaf size)[x_i \text{ shares a leaf with } x] / (\text{leaf size}). This is the topic Nearest neighbours again, with neighbourhoods learned from the target. Points are close if they often share a leaf, and features that do not matter do not count in the distance.

Out-of-bag error

A bootstrap sample misses some points. A given point is not chosen in one draw with probability 1−1/n1 - 1/n, and in none of the nn draws with probability

(1−1n)n⟶e−1≈0.368.\Big(1 - \frac1n\Big)^n \longrightarrow e^{-1} \approx 0.368 .

The topic Confidence intervals and the bootstrap met the same number when the bootstrap failed for the maximum. So a bootstrap sample holds, on average, a fraction 1−(1−1/n)n1 - (1 - 1/n)^n of the distinct points: 0.6510.651 for n=10n = 10, 0.6340.634 for n=100n = 100, and 1−1/e≈0.6321 - 1/e \approx 0.632 in the limit.

Every point is therefore left out of about 36.8% of the trees, and those trees are an honest test of it. The out-of-bag (OOB) prediction of xix_i averages only the trees whose bootstrap sample did not contain ii. The OOB error is the error of these predictions over the training set. It estimates the test error almost for free, much like the cross-validation of the topic Validation and overfitting, and nothing is set aside: every point is used both for training and for evaluation. With few trees it is slightly pessimistic, because each OOB prediction averages only about B/eB/e of them.

On the breast cancer data (569 tumours, 30 features, benign or malignant), 30% of the points are held out to compare:

from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
 
X, y = load_breast_cancer(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
rf = RandomForestClassifier(300, oob_score=True, random_state=0).fit(Xtr, ytr)
print(round(rf.oob_score_, 3), round(rf.score(Xte, yte), 3))
0.967 0.953

The OOB accuracy is 0.9670.967, the held-out accuracy 0.9530.953.

The OOB error is honest only for the forest itself. Choosing mm, the leaf size or the features by comparing OOB errors reuses the same points for selection, so the winner's OOB error is optimistic. A step before the forest that used the targets of all points, such as keeping the features most correlated with yy, is the leakage of the topic Data, features and leakage: each point's label has already been seen. When OOB results drive such choices, keep a separate test set for the final assessment.

Feature importance and its traps

A forest cannot be read the way one tree can, but it can rank the features. Two measures are common.

  • Impurity importance (mean decrease in impurity, MDI): add up the impurity gains of all splits on feature jj over all trees, weighted by the number of points each split sees, and normalize. It is free, since the gains are computed during training.
  • Permutation importance: shuffle the values of feature jj in held-out or OOB data, which breaks its link with the target and keeps its distribution, and measure how much the error grows. It works for any fitted model.

Both have traps.

Impurity importance is computed on the training data and favours features with many distinct values. Fully grown trees split on whatever lowers the training impurity, noise included, and a continuous feature offers far more thresholds to fit noise with than a binary one (Strobl et al., 2007). In a simulation the label depends only on x1x_1; x2x_2 is binary noise and x3x_3 continuous noise. The impurity importances are 0.6610.661, 0.0080.008 and 0.3310.331: a third goes to pure noise. Permutation importance on held-out data gives 0.2270.227, −0.016-0.016 and −0.008-0.008, correctly zero for both noise features up to random error.

Correlated features distort the ranking. On the breast cancer data the top feature, worst perimeter, has impurity importance 0.1340.134. Add an exact copy of it, and the twins get 0.1080.108 and 0.1240.124, together 0.2320.232. With mm features per split, two copies make the same information available at more splits, so the pair takes importance from the other features, and the copy now ranks first. In bagging every split sees all features, and the twins only share: 0.2120.212 and 0.2040.204 against 0.4150.415 for the feature alone. Either way, scores of correlated features read one at a time do not say how important the group is.

Permuting a correlated feature creates impossible inputs, such as a large radius with a small perimeter. The model is then measured where there are no data, and such scores can grossly overstate correlated features (Hooker, Mentch and Zhou, 2021).

Importance is not causation. Both measures describe what a fitted model uses, not what would happen if the feature were changed in the world.

Extra trees and the limits of averaging

Random forests randomize the features. Extremely randomized trees (extra trees, Geurts, Ernst and Wehenkel, 2006) randomize the thresholds too. At each node they draw KK features, draw for each one cut point uniformly between its minimum and maximum in the node, and keep the best of these KK random splits. Each tree grows on the whole training set, not a bootstrap sample, to keep the bias low, and the random cuts supply the diversity. The trees are cheaper to grow, with no sorting and no threshold search, and more strongly decorrelated. On the breast cancer split, 300 extra trees reach test accuracy 0.9420.942 against 0.9530.953 for the forest: often similar, sometimes better, depending on the data.

What averaging cannot do:

  • The bias stays. Averaging cannot correct a systematic error that all trees share. A forest of stumps, trees of depth 1, has the bias of one randomized stump. That average stump can be an additive function of the features, a sum of functions of one feature each, but it has no interactions.
  • The floor stays. Correlated trees leave ρτ2\rho\tau^2 however many are averaged, and a smaller mm lowers ρ\rho only at the price of worse trees.
  • Size and speed. Hundreds of deep trees take memory and prediction time.
  • No extrapolation. A regression forest averages leaf means, so its predictions stay within the range of the training targets.

So averaging attacks the variance and leaves the bias alone. It needs deep, low-bias trees, and it can do nothing about an error that every tree makes. The topic Gradient boosting builds the ensemble the other way round. The trees are small and grown one after another, and each new tree is fitted to the errors that the sum of the previous ones still makes, so the bias falls step by step. That turns out to be gradient descent, carried out in a space of functions.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.