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 equicorrelated predictors, , and use it to explain the random feature subsets of random forests.
- Compute the out-of-bag fraction , 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 , train a model on each and average their predictions, how much would we gain?
Fix and let be the prediction of a learner trained on a random training set of size drawn from . The aggregated predictor averages over training sets:
For squared loss and any target value , expand around ; the cross term vanishes because :
So the aggregate is never worse, at any point and for any , 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 and there is little to gain.
Fresh training sets are not available, so bagging draws them from the data itself: bootstrap samples , each of draws with replacement. The result approximates , 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 if, across training sets, the class it predicts most often there is the most probable class at . 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.
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 estimatesBagged 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 and let be the trees' predictions there. They are identically distributed, with variance and pairwise correlation , both taken over the training data and the resampling.
Expand the variance of the sum into variances and covariances, each equal to :
Simplify:
As the second term vanishes and the variance falls to , not to zero. Adding trees never hurts, since the variance decreases in , 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.
At a point , each tree's prediction has variance , and any two trees have correlation . What is the variance of the average of trees?
Show the answer
0.41
. 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 would gain about 0.2. The lever is the correlation.
A random forest (Breiman, 2001) attacks directly: at every split, a tree may choose only among features drawn at random. Strong features can no longer dominate the top of every tree, so the trees diversify. A smaller lowers but also weakens each tree, raising its bias and variance, so there is a sweet spot. The defaults its inventors suggested are for classification and 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 features, only 5 of them informative, and . How often does a split get to choose among no informative feature at all?
: more than half of all splits must pick among noise features only. With it is about 0.13. Small decorrelates the trees, but when the signal is sparse it wastes splits; that is when a larger , or screening out noise features first, pays off.
Random forests and extremely randomized trees
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 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 random splits. A node then costs instead of for examples, the trees are more diverse, and the averaged boundary is smoother. Their default is for classification and for regression.
| Method | Randomness per tree | Split search | Typical effect |
|---|---|---|---|
| Bagging | bootstrap sample | best split over all features | variance falls, but the trees stay strongly correlated |
| Random forest | bootstrap sample, plus random features per split | best split among the features | lower correlation; the usual default |
| Extremely randomized trees | random features and random thresholds; full sample | best of random splits | lowest correlation and fastest; slightly more bias per tree |
Out-of-bag error: validation for free
A given example is missed by one draw with probability , so by all independent draws of a bootstrap sample with probability
Take logarithms and expand with :
The limit is approached from below, and fast: about at and at . So each tree leaves out about 36.8% of the examples, and each example is left out by about of the trees.
The out-of-bag (OOB) prediction for example aggregates only the trees whose bootstrap samples excluded , 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.
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
. 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
| Setting | Effect | Practical choice |
|---|---|---|
| Number of trees | variance falls with ; more trees never overfit | a few hundred to a few thousand; stop when the OOB error flattens |
| Features per split | trades correlation between trees against each tree's strength | the most influential setting; try , and neighbors, judged by OOB error or cross-validation |
| Leaf size or depth | larger leaves give smoother, lower-variance but more biased trees | fully grown is a good default; larger leaves for noisy regression |
| Sample per tree | bootstrap with replacement, or a subsample without replacement | subsamples decorrelate the trees and speed them up; much of the theory assumes them |
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.
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?
- The error falls sharply, just as for trees
- The model becomes nonlinear and can fit curves
- Little changes: least squares is stable, so the bootstrap fits are close to each other and their average is close to the original fit
- 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 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 predictors with variance and correlation has variance : more trees never hurt, but the floor is set by the correlation.
- Random forests lower by choosing each split among random features (suggested defaults for classification, for regression); extremely randomized trees also randomize the thresholds.
- A bootstrap sample leaves out a fraction of the examples, so each example is out-of-bag for about 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.
Trees at a point have variance and pairwise correlation . What does the variance of their average approach as the number of trees grows?
Show the answer
B.
. The shared part of the trees' fluctuations, caused by their common training data, never averages out.
A training set has examples. What is the probability that a given example is left out of a bootstrap sample?
- 0.200
- 0.328
- 0.368
- 0.500
Show the answer
B. 0.328
. As grows this rises toward .
Lowering , the number of features a random-forest split may consider, typically has which effect?
- It lowers the correlation between trees but makes each tree weaker, so the error is smallest at an intermediate value
- It always lowers the error, because the trees become more diverse
- It reduces each tree's bias
- 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 in , but trees forced to split on poor features fit worse and vary more. The best balances the two, and it depends on how many features are informative.
What distinguishes extremely randomized trees from a standard random forest?
- They use deeper trees
- They grow trees one after another, each correcting the previous ones
- They draw split thresholds at random and, by default, train every tree on the full sample instead of a bootstrap sample
- 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 random features, one random threshold between the node's minimum and maximum, and keep the best of these splits; the extra randomness lowers the correlation between trees, so they can afford to use the whole sample.
You tune by picking the value with the lowest out-of-bag error, and report that error as your expected test error. What is wrong?
- Nothing: out-of-bag error is unbiased
- Out-of-bag error cannot be computed for random forests
- The out-of-bag error always overestimates the test error
- 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
- The Bootstrap · Resampling your data to measure uncertainty.
- Random Forest Theory · Strength, correlation, out-of-bag error and consistency.
- Feature Importance & Its Pitfalls · Impurity, permutation and conditional importance.
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.