Simple Algorithm
Machine Learning · Descent · 22 min

Bagging & Random Forests

Averaging many noisy trees into one strong model.

A fully grown tree has low bias and very high variance. Average hundreds of them, each grown on a bootstrap resample, and the variance collapses while the bias barely moves; restrict every split to a few random features and it falls further still. This lesson derives why averaging works, exactly how far it can go, and how the examples each tree leaves out give a free estimate of the test error.

What you’ll learn

  • Define bootstrap aggregation and explain, from the bias–variance decomposition, why it helps unstable low-bias learners and barely changes stable ones.
  • Derive the variance of an average of BB equicorrelated predictors, ρσ2+(1−ρ)σ2/B\rho\sigma^2+(1-\rho)\sigma^2/B, and use it to explain the random feature subsets of random forests.
  • Compute the out-of-bag fraction (1−1/n)n→e−1(1-1/n)^n\to e^{-1}, and estimate test error from out-of-bag predictions without a holdout set.
  • Choose a forest's hyperparameters, and compare bagging, random forests and extremely randomized trees.

Bootstrap aggregation

Bagging (Breiman, 1996) starts from a thought experiment. If we could draw many independent training sets from the data distribution PP, train a model on each and average their predictions, how much would we gain?

DerivationWhy averaging over training sets helps
  1. fA(x)=ED[f^D(x)]f_A(\mathbf x)=\E_\data\big[\hat f_\data(\mathbf x)\big]

    Fix x\mathbf x and let f^D(x)\hat f_\data(\mathbf x) be the prediction of a learner trained on a random training set D\data of size nn drawn from PP. The aggregated predictor averages over training sets:

  2. ED[(y−f^D(x))2]=(y−fA(x))2+Var⁡D[f^D(x)]\E_\data\big[(y-\hat f_\data(\mathbf x))^2\big]=\big(y-f_A(\mathbf x)\big)^2+\Var_\data\big[\hat f_\data(\mathbf x)\big]

    For squared loss and any target value yy, expand around fAf_A; the cross term vanishes because ED[f^D(x)−fA(x)]=0\E_\data\big[\hat f_\data(\mathbf x)-f_A(\mathbf x)\big]=0:

  3. ED[(y−f^D(x))2] ≥ (y−fA(x))2\E_\data\big[(y-\hat f_\data(\mathbf x))^2\big]\ \ge\ \big(y-f_A(\mathbf x)\big)^2

    So the aggregate is never worse, at any point and for any yy, and it gains exactly the learner's variance across training sets. Unstable learners, whose predictions swing with the sample, gain most; for a stable learner f^D≈fA\hat f_\data\approx f_A and there is little to gain.

  4. f^bag(x)=1B∑b=1Bf^Db∗(x)\hat f_{\text{bag}}(\mathbf x)=\frac1B\sum_{b=1}^B\hat f_{\data_b^*}(\mathbf x)

    Fresh training sets are not available, so bagging draws them from the data itself: BB bootstrap samples D1∗,…,DB∗\data_1^*,\dots,\data_B^*, each of nn draws with replacement. The result approximates fAf_A, except that each bootstrap tree sees only about 63% of the distinct examples, so its bias can differ slightly from that of a tree grown on the full sample.

For classification, the bagged trees' class proportions are averaged (or their labels put to a majority vote); averaging proportions gives smoother class-probability estimates. Breiman also noted a caveat for voting. Call the base classifier order-correct at x\mathbf x if, across training sets, the class it predicts most often there is the most probable class at x\mathbf x. At such points the aggregated vote makes the Bayes-optimal prediction, even if single classifiers often err; where the classifier is not order-correct, aggregation can make things worse. Fully grown trees are the classic beneficiaries, since their bias is low and their instability high.

python
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier

bag = BaggingClassifier(DecisionTreeClassifier(), n_estimators=500,
                        oob_score=True, random_state=0).fit(X_train, y_train)
rf = RandomForestClassifier(n_estimators=500, max_features="sqrt",
                            oob_score=True, random_state=0).fit(X_train, y_train)
print(bag.oob_score_, rf.oob_score_)    # out-of-bag accuracy estimates

Bagged trees and a random forest in scikit-learn. The out-of-bag scores, explained below, come for free with the fit.

Averaging correlated trees

Bagged trees are not independent: they are grown from the same data, so they share its quirks. Fix x\mathbf x and let T1,…,TBT_1,\dots,T_B be the trees' predictions there. They are identically distributed, with variance σ2\sigma^2 and pairwise correlation ρ≥0\rho\ge0, both taken over the training data and the resampling.

DerivationVariance of an average of equicorrelated predictors
  1. Var⁡(1B∑b=1BTb)=1B2[∑bVar⁡Tb+∑b≠b′Cov⁡(Tb,Tb′)]=1B2[Bσ2+B(B−1)ρσ2]\Var\Big(\frac1B\sum_{b=1}^BT_b\Big)=\frac1{B^2}\Big[\sum_b\Var T_b+\sum_{b\ne b'}\Cov(T_b,T_{b'})\Big]=\frac1{B^2}\Big[B\sigma^2+B(B-1)\rho\sigma^2\Big]

    Expand the variance of the sum into BB variances and B(B−1)B(B-1) covariances, each equal to ρσ2\rho\sigma^2:

  2. Var⁡(1B∑b=1BTb)=ρσ2+1−ρB σ2\Var\Big(\frac1B\sum_{b=1}^BT_b\Big)=\rho\sigma^2+\frac{1-\rho}{B}\,\sigma^2

    Simplify:

  3. lim⁡B→∞Var⁡(1B∑b=1BTb)=ρσ2\lim_{B\to\infty}\Var\Big(\frac1B\sum_{b=1}^BT_b\Big)=\rho\sigma^2

    As B→∞B\to\infty the second term vanishes and the variance falls to ρσ2\rho\sigma^2, not to zero. Adding trees never hurts, since the variance decreases in BB, but the floor is set by the correlation. The mean of the average equals the mean of one tree, so bagging leaves the bias of the (bootstrap) trees unchanged.

Predict before you look

At a point x\mathbf x, each tree's prediction has variance σ2=1\sigma^2=1, and any two trees have correlation ρ=0.4\rho=0.4. What is the variance of the average of B=50B=50 trees?

Show the answer

0.41

0.4+0.6/50=0.4120.4+0.6/50=0.412. With infinitely many trees it would be 0.4, so going from 50 trees to a million gains only 0.012, while lowering the correlation to ρ=0.2\rho=0.2 would gain about 0.2. The lever is the correlation.

A random forest (Breiman, 2001) attacks ρ\rho directly: at every split, a tree may choose only among mtry<dm_{\text{try}}<d features drawn at random. Strong features can no longer dominate the top of every tree, so the trees diversify. A smaller mtrym_{\text{try}} lowers ρ\rho but also weakens each tree, raising its bias and variance, so there is a sweet spot. The defaults its inventors suggested are ⌊d⌋\lfloor\sqrt d\rfloor for classification and ⌊d/3⌋\lfloor d/3\rfloor for regression, with trees grown out to leaves of size 1 for classification and 5 for regression. Libraries differ: scikit-learn's random forest regressor, for instance, defaults to all features, which is plain bagging.

Think first There are d=100d=100 features, only 5 of them informative, and mtry=10m_{\text{try}}=10. How often does a split get to choose among no informative feature at all?

(9510)/(10010)≈0.58\binom{95}{10}\big/\binom{100}{10}\approx0.58: more than half of all splits must pick among noise features only. With mtry=33m_{\text{try}}=33 it is about 0.13. Small mtrym_{\text{try}} decorrelates the trees, but when the signal is sparse it wastes splits; that is when a larger mtrym_{\text{try}}, or screening out noise features first, pays off.

Random forests and extremely randomized trees

text
RANDOM-FOREST(data D of size n, number of trees B, features per split m_try, leaf size n_min)
    for b = 1..B:
        D_b = n draws from D with replacement             # bootstrap sample
        grow a tree on D_b; at every node:
            draw m_try of the d features at random, without replacement
            choose the best split among those features only
            stop splitting nodes with fewer than n_min examples   # no pruning
    regression:      f(x) = average of the B trees' predictions
    classification:  average the trees' class proportions (or take a majority vote)

Random forests combined two earlier ideas: bagging, and random feature selection, which Ho's random subspace method (1998) applied once per tree and Amit & Geman (1997) at every node.

Extremely randomized trees (Geurts, Ernst & Wehenkel, 2006) randomize further. Each tree sees the whole training sample, with no bootstrap. At each node they draw KK features and, for each one, a single threshold uniformly at random between the feature's smallest and largest value in the node, and keep the best of these KK random splits. A node then costs O(Km)\order{Km} instead of O(Kmlog⁡m)\order{Km\log m} for mm examples, the trees are more diverse, and the averaged boundary is smoother. Their default KK is d\sqrt d for classification and dd for regression.

MethodRandomness per treeSplit searchTypical effect
Baggingbootstrap samplebest split over all dd featuresvariance falls, but the trees stay strongly correlated
Random forestbootstrap sample, plus mtrym_{\text{try}} random features per splitbest split among the mtrym_{\text{try}} featureslower correlation; the usual default
Extremely randomized treesrandom features and random thresholds; full samplebest of KK random splitslowest correlation and fastest; slightly more bias per tree

Out-of-bag error: validation for free

DerivationThe out-of-bag fraction
  1. Pr⁡[ i∉D∗ ]=(1−1n)n\Pr\big[\,i\notin\data^*\,\big]=\Big(1-\frac1n\Big)^n

    A given example is missed by one draw with probability 1−1/n1-1/n, so by all nn independent draws of a bootstrap sample with probability

  2. nln⁡(1−1n)=−1−12n−O(1n2)⟹(1−1n)n=e−1(1−12n+O(1n2))n\ln\Big(1-\frac1n\Big)=-1-\frac1{2n}-\order{\frac1{n^2}}\quad\Longrightarrow\quad\Big(1-\frac1n\Big)^n=e^{-1}\Big(1-\frac1{2n}+\order{\frac1{n^2}}\Big)

    Take logarithms and expand ln⁡(1−u)=−u−u2/2−…\ln(1-u)=-u-u^2/2-\dots with u=1/nu=1/n:

  3. (1−110)10≈0.349,(1−1100)100≈0.366,e−1≈0.368\Big(1-\tfrac1{10}\Big)^{10}\approx0.349,\qquad\Big(1-\tfrac1{100}\Big)^{100}\approx0.366,\qquad e^{-1}\approx0.368

    The limit e−1≈0.368e^{-1}\approx0.368 is approached from below, and fast: about 0.3490.349 at n=10n=10 and 0.3660.366 at n=100n=100. So each tree leaves out about 36.8% of the examples, and each example is left out by about B/eB/e of the BB trees.

The out-of-bag (OOB) prediction for example ii aggregates only the trees whose bootstrap samples excluded ii, and the OOB error averages the loss of these predictions over all examples. Every OOB prediction comes from trees that never saw the example, so the OOB error behaves like a test error, with no holdout set and no refitting. Breiman reported empirical evidence that it is about as accurate as a test set of the same size as the training set. Two cautions apply. Each OOB prediction uses only about a third of the trees, so with few trees the OOB error is pessimistic. And like any error estimate, it turns optimistic if you tune hyperparameters by minimizing it and then report that minimum.

Predict before you look

A random forest has 500 trees and a large training set. In about how many of the trees is a given training example out-of-bag?

Show the answer

184 trees

500×(1−1/n)n≈500/e≈184500\times(1-1/n)^n\approx500/e\approx184. Each OOB prediction averages about 184 trees: fewer than the full forest, but enough that, with hundreds of trees, the OOB error closely tracks the error of the whole forest.

Tuning, strengths and limits

SettingEffectPractical choice
Number of trees BBvariance ρσ2+(1−ρ)σ2/B\rho\sigma^2+(1-\rho)\sigma^2/B falls with BB; more trees never overfita few hundred to a few thousand; stop when the OOB error flattens
Features per split mtrym_{\text{try}}trades correlation between trees against each tree's strengththe most influential setting; try d\sqrt d, d/3d/3 and neighbors, judged by OOB error or cross-validation
Leaf size or depthlarger leaves give smoother, lower-variance but more biased treesfully grown is a good default; larger leaves for noisy regression
Sample per treebootstrap with replacement, or a subsample without replacementsubsamples decorrelate the trees and speed them up; much of the theory assumes them
Random forests have few settings, and their defaults are hard to beat by much; this robustness is a large part of their popularity.

Forests train in parallel and need no feature scaling. They also have limits: a forest is no longer a readable rule set; like its trees, it cannot extrapolate beyond the range of the training targets; averaging pulls predicted probabilities that should be near 0 or 1 inward, so forest probabilities often benefit from recalibration (Niculescu-Mizil & Caruana, 2005; Calibration & Proper Scoring Rules); and its impurity-based importances are biased. Bagging reduces the variance of low-bias trees. The opposite strategy, reducing the bias of high-bias trees by fitting them in sequence, is Boosting.

Check your understanding

You bag ordinary least-squares linear regression, with 500 bootstrap fits, on a dataset where the linear model is appropriate. Compared with a single least-squares fit, what happens?

  1. The error falls sharply, just as for trees
  2. The model becomes nonlinear and can fit curves
  3. Little changes: least squares is stable, so the bootstrap fits are close to each other and their average is close to the original fit
  4. The error rises, because each bootstrap fit sees fewer distinct points
Show the answer

C. Little changes: least squares is stable, so the bootstrap fits are close to each other and their average is close to the original fit

Least squares is a smooth function of the data, so resampling perturbs it only slightly and the bagged average is close to the original fit; the variance term Var⁡D[f^D]\Var_\data[\hat f_\data] there was small to begin with. Bagging pays off for unstable learners such as deep trees, whose predictions jump with the sample.

Key takeaways

  • Averaging a learner over training sets removes exactly its variance across them; bagging approximates this with bootstrap samples, which helps unstable, low-bias learners such as deep trees and barely changes stable ones.
  • An average of BB predictors with variance σ2\sigma^2 and correlation ρ\rho has variance ρσ2+(1−ρ)σ2/B\rho\sigma^2+(1-\rho)\sigma^2/B: more trees never hurt, but the floor ρσ2\rho\sigma^2 is set by the correlation.
  • Random forests lower ρ\rho by choosing each split among mtrym_{\text{try}} random features (suggested defaults d\sqrt d for classification, d/3d/3 for regression); extremely randomized trees also randomize the thresholds.
  • A bootstrap sample leaves out a fraction (1−1/n)n→e−1≈0.368(1-1/n)^n\to e^{-1}\approx0.368 of the examples, so each example is out-of-bag for about B/eB/e trees, and the out-of-bag error estimates the test error for free.
  • Forests are robust and need little tuning, but they cannot extrapolate, their probabilities may need calibration, and their impurity-based importances are biased.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Trees at a point x\mathbf x have variance σ2\sigma^2 and pairwise correlation ρ\rho. What does the variance of their average approach as the number of trees grows?

  1. 00
  2. ρσ2\rho\sigma^2
  3. σ2/B\sigma^2/B
  4. (1−ρ)σ2(1-\rho)\sigma^2
Show the answer

B. ρσ2\rho\sigma^2

Var⁡(Tˉ)=ρσ2+(1−ρ)σ2/B→ρσ2\Var(\bar T)=\rho\sigma^2+(1-\rho)\sigma^2/B\to\rho\sigma^2. The shared part of the trees' fluctuations, caused by their common training data, never averages out.

Question 2

A training set has n=5n=5 examples. What is the probability that a given example is left out of a bootstrap sample?

  1. 0.200
  2. 0.328
  3. 0.368
  4. 0.500
Show the answer

B. 0.328

(1−1/5)5=0.85≈0.328(1-1/5)^5=0.8^5\approx0.328. As nn grows this rises toward e−1≈0.368e^{-1}\approx0.368.

Question 3

Lowering mtrym_{\text{try}}, the number of features a random-forest split may consider, typically has which effect?

  1. It lowers the correlation between trees but makes each tree weaker, so the error is smallest at an intermediate value
  2. It always lowers the error, because the trees become more diverse
  3. It reduces each tree's bias
  4. It has no effect when the trees are fully grown
Show the answer

A. It lowers the correlation between trees but makes each tree weaker, so the error is smallest at an intermediate value

Diversity lowers ρ\rho in ρσ2+(1−ρ)σ2/B\rho\sigma^2+(1-\rho)\sigma^2/B, but trees forced to split on poor features fit worse and vary more. The best mtrym_{\text{try}} balances the two, and it depends on how many features are informative.

Question 4

What distinguishes extremely randomized trees from a standard random forest?

  1. They use deeper trees
  2. They grow trees one after another, each correcting the previous ones
  3. They draw split thresholds at random and, by default, train every tree on the full sample instead of a bootstrap sample
  4. They prune each tree by cost-complexity
Show the answer

C. They draw split thresholds at random and, by default, train every tree on the full sample instead of a bootstrap sample

Extra-Trees pick, for each of KK random features, one random threshold between the node's minimum and maximum, and keep the best of these KK splits; the extra randomness lowers the correlation between trees, so they can afford to use the whole sample.

Question 5

You tune mtrym_{\text{try}} by picking the value with the lowest out-of-bag error, and report that error as your expected test error. What is wrong?

  1. Nothing: out-of-bag error is unbiased
  2. Out-of-bag error cannot be computed for random forests
  3. The out-of-bag error always overestimates the test error
  4. Taking the minimum over several noisy estimates selects partly for luck, so the reported value is optimistic; confirm on held-out data or with nested validation
Show the answer

D. Taking the minimum over several noisy estimates selects partly for luck, so the reported value is optimistic; confirm on held-out data or with nested validation

For one fixed setting the OOB error is a fair estimate (slightly pessimistic with few trees). Minimizing it over settings reintroduces selection bias, exactly as with cross-validation.

Go deeper

Further reading

  • L. Breiman, "Bagging predictors," Machine Learning 24(2), 123–140 (1996).
  • L. Breiman, "Random forests," Machine Learning 45(1), 5–32 (2001).
  • P. Geurts, D. Ernst & L. Wehenkel, "Extremely randomized trees," Machine Learning 63(1), 3–42 (2006).
  • T. Hastie, R. Tibshirani & J. Friedman, The Elements of Statistical Learning, 2nd ed. (Springer, 2009), §8.7 and chapter 15.