Five friends each guess the answer to a yes/no question. Each is right 60% of the time. If you ask one friend, you are right 60% of the time. If you take the majority of the five, and their mistakes are independent of each other, you are right 68.3% of the time. With 101 friends it is 97.9%. But if the friends all copy one another, the crowd is right 60% of the time, however large it is.
That is the whole idea of this lesson: averaging many noisy predictors helps in proportion to how different their mistakes are. A fully grown decision tree (P3.B3) is a very noisy predictor: it fits its training data perfectly and changes a lot when the data change. We will build many trees whose mistakes are different on purpose, average them, and measure what we gain.
One deep tree has high variance
P3.B3 grew a tree until every leaf held a single class. Such a tree has almost no bias: it can draw any boundary made of rectangles. But in the language of P3.A5 it has high variance: change a few training points and its boundary changes a lot. The widget below makes this concrete. Move the slider to one tree and look at the jagged boundary that bends around single points.
If we could train a thousand such trees on a thousand independent training sets and average them, the variance would fall by a large factor. We cannot: we have one training set. The bootstrap gives a way to get many different training sets out of one.
Averaging many predictors
Take predictors (for example, trees) and average their predictions at one input. Suppose each has variance , and each pair has correlation . Here measures how much two trees make the same mistakes: it is the correlation between their predictions at the same input, over the randomness used to grow them (the training sample and the choices made while growing). The variance of a sum is the sum of all the variances and covariances (P1.D4), and each covariance is .
Write for the average. Then
Two cases to remember.
- Independent errors (): the variance is . This is the law of large numbers at work (P1.D8): the average of independent draws has of the variance of one draw.
- Identical errors (): the variance is . Averaging copies of one predictor changes nothing.
In between, adding more predictors shrinks only the second term. As grows the variance approaches the floor . With the numbers of P3.A5’s exercise (): for the variance is if and if , and with no number of models can push it below .
What about the bias? The average of predictors that are all drawn the same way has the same expected value as one of them. So averaging leaves the bias unchanged and lowers the variance, as P3.A5 previewed. This is why we average models with low bias and high variance, such as deep trees, and why averaging a stable model (one that hardly changes with the data, such as a straight-line fit) gains little.
Two things decide how much averaging helps: how large is, and how small we can make . The next two sections are two ways to make the trees differ.
The bootstrap: many data sets from one
A bootstrap sample of a data set with examples is made by drawing times with replacement: pick an example at random, write it down, put it back, repeat. Some examples are picked twice or more, and some are never picked.
Take five examples A to E. One seeded draw of five gave E, D, C, B, B: the example B appears twice, and A was left out. The bootstrap sample has four distinct examples out of five.
How many are left out, on average? Fix one example. In one draw it is missed with probability . The draws are independent, so it is missed in all of them with probability
(This is a standard limit from calculus.) So about of the examples are out-of-bag for a given bootstrap sample, and about of the distinct examples appear in it. The limit is reached quickly: the exact values are for , for and for . For the exact value is .
Two details. A bootstrap sample still has rows, but they are not different examples: about distinct ones, some repeated. And the bootstrap is an old statistical idea (Efron, 1979) for estimating how much an estimate would vary; P1.D9 used it for that. Here we use it to build different training sets.
Bagging: one tree per bootstrap sample
Bagging is short for bootstrap aggregating (Breiman, 1996). The recipe:
- For : draw a bootstrap sample of the training set and grow a deep tree on it.
- To predict, ask all trees. Regression: average their numbers. Classification: take the majority vote. (scikit-learn averages the trees’ class probabilities instead of counting votes; with fully grown trees on data where no two identical inputs have different labels, every leaf holds a single class and the two agree.)
Why does this work? Each tree sees a different version of the data (about 63% of the distinct examples, some repeated), so the trees make somewhat different mistakes: . Each tree is deep, so its bias is low. Averaging then lowers the variance, and the bias stays about that of one bootstrap tree. A bootstrap tree has seen fewer distinct examples than a tree trained on all the data, so its bias can be slightly higher.
The trees are still correlated, because they all learn from the same data. That is the floor above. Random forests lower it.
Random forests: also hide some features
Suppose one feature is much stronger than the others. Every bootstrap tree will put it at the top, and the trees will look alike: stays high. A random forest (Breiman, 2001) adds a second source of randomness. At each split, the tree may look at only a random subset of the features, picks the best split among those, and tries again at the next node with a fresh random subset. In scikit-learn the size of the subset is max_features.
- For classification the default is
max_features="sqrt": about of the features. - For regression the default is
max_features=1.0, which means all features, so a scikit-learn regression forest with default settings is bagging of trees. (Some other libraries use one third of the features for regression by default, for example R’srandomForest, following a rule of thumb from the original forest literature. scikit-learn’s regression default has always been all the features, so you must setmax_featuresyourself to get the one-third rule.)
These are defaults, not laws. The subset size is a setting to tune.
Smaller subsets make the trees more different, but when few features carry signal a very small subset makes each tree much worse. The sweep below shows a middle value winning.
See it: more trees smooth the boundary
The data are made up: two interleaved crescents (classes 0 and 1), 100 training points and 400 test points, with noise, so the classes overlap and no boundary is perfect. The forests were grown ahead of time, 100 trees each, with scikit-learn. The slider chooses how many of them vote.
Things to try.
- One tree. In the bagging setting the boundary is a patchwork of rectangles with small islands around single points. The training accuracy is below 100% (96%), because a bootstrap tree has never seen about a third of the training points. The test accuracy is 86.25%.
- Slide to 10, then 100. Islands shrink and the boundary becomes a smoother curve that follows the crescents. The test accuracy is 89% at and 89.5% at . The training accuracy reaches 100% by : the forest has memorised the training points and it still does better on new points than the single tree.
- Look at the colours. Pale cells are close votes. They sit along the boundary, where the trees disagree. A forest’s vote share carries more information than its yes/no answer, though it is not a calibrated probability (P3.A10).
- Random forest. Switch to one random feature per split. Single trees get worse (the first tree has 81.5% test accuracy against 86.25%), but the boundary of a 100-tree forest is smooth and the test accuracy (90.25%) is as good as bagging’s (89.5%) or a little better. (One or two points on 400 test points is within chance.)
A worked example in scikit-learn
The same data in code. This block is not run in the browser (scikit-learn is not available there); it is the code and its real output from a local run, with scikit-learn 1.8. The data come from a seeded generator, so you can reproduce every number.
import numpy as np
from sklearn.ensemble import BaggingClassifier, RandomForestClassifier
from sklearn.tree import DecisionTreeClassifier
def moons(n, noise, rng): # two interleaved half-circles plus noise
m = n // 2
t = rng.uniform(0, np.pi, m)
a = np.c_[np.cos(t), np.sin(t)]
t = rng.uniform(0, np.pi, m)
b = np.c_[1 - np.cos(t), 0.5 - np.sin(t)]
X = np.r_[a, b] + noise * rng.standard_normal((2 * m, 2))
y = np.r_[np.zeros(m, int), np.ones(m, int)]
p = rng.permutation(2 * m)
return X[p], y[p]
rng = np.random.default_rng(0)
X_train, y_train = moons(100, 0.3, rng) # 100 training points
X_test, y_test = moons(400, 0.3, rng) # 400 fresh points for testing
tree = DecisionTreeClassifier(random_state=0).fit(X_train, y_train)
bag = BaggingClassifier(DecisionTreeClassifier(), n_estimators=100,
oob_score=True, random_state=0).fit(X_train, y_train)
rf = RandomForestClassifier(n_estimators=100, oob_score=True,
random_state=0).fit(X_train, y_train)
print("tree train %.3f test %.3f" % (tree.score(X_train, y_train), tree.score(X_test, y_test)))
print("bagging train %.3f test %.3f oob %.3f" % (bag.score(X_train, y_train), bag.score(X_test, y_test), bag.oob_score_))
print("forest train %.3f test %.3f oob %.3f" % (rf.score(X_train, y_train), rf.score(X_test, y_test), rf.oob_score_))
print("features tried per split:", rf.estimators_[0].max_features_, "of", rf.n_features_in_)
tree train 1.000 test 0.858
bagging train 1.000 test 0.895 oob 0.870
forest train 1.000 test 0.902 oob 0.880
features tried per split: 1 of 2
(The oob column is explained in the out-of-bag section below. The exact test accuracies are 0.8575, 0.895 and 0.9025, which the print shows rounded to three decimals.) Every model gets the training set exactly right, so training accuracy cannot tell them apart; the test set can. The single tree scores 85.75% on the test points and the forests 89.5% and 90.25%. This is one data set. A loop over seeds 1 to 20 of the same generator (not shown) gives 20 more data sets of the same kind: there, the forest beat the single tree in 19 of the 20, and so did the bagged trees, with mean test accuracies of 86.3% for one tree, 88.7% for bagging and 88.8% for the forest. The gain here is a few points: real, but not dramatic.
How many trees?
More trees lower the second term of the variance formula, , and leave the floor alone. So the gain per tree shrinks quickly. The numbers below are from the widget’s data: test accuracy of the first trees on the 400 test points.
| Trees | Bagging | Random forest |
|---|---|---|
| 1 | 86.25% | 81.5% |
| 5 | 89% | 83.75% |
| 10 | 89% | 89.75% |
| 30 | 89.75% | 89.75% |
| 100 | 89.5% | 90.25% |
The accuracy rises fast and then levels off. A tied vote counts as class 0 (as in scikit-learn), so small even can dip: at bagging scores 85% and the forest 78.25%. On one finite test set of 400 points the curve also wobbles by a point or so.
Breiman (2001) proved that the forest’s generalisation error converges to a limit as trees are added, instead of rising. So adding trees does not make a forest overfit more; the gain just levels off. More trees cost time to train and to predict, and memory, in proportion to . A common practice is to take a few hundred trees and stop when the out-of-bag error (below) stops falling.
Out-of-bag error: a free validation set
Each tree is trained on a bootstrap sample, so about 36.8% of the training examples are out-of-bag for it: the tree never saw them. This gives a validation set for free.
- For each training example, collect the trees for which it is out-of-bag. With trees that is about trees.
- Let only those trees predict the example (vote or average).
- Compare with its true label. The fraction of right answers (or the mean squared error) is the out-of-bag (OOB) score.
Every prediction in step 2 comes from trees that never saw that example, as in a validation set (P3.A4), yet no data were held back: all examples are still used for training. In scikit-learn, set oob_score=True and read oob_score_.
Two small- effects. With , only the 36.8% of examples that the single tree missed can be scored (the widget shows 36 of 100); the chance that an example is in-bag for all of trees is , about at . And each example is scored by only about trees, a smaller crowd than the whole forest, so the OOB error tends to be a little pessimistic.
Is it right? Check it against a held-out set. On the crescent data, the OOB accuracy is 87% for the bagged trees against 89.5% on the test points, and 88% against 90.25% for the forest. On the 20-feature data of the next section, averaged over 20 data sets, the OOB accuracy is about 0.5 to 2.5 points below the test accuracy for every setting of max_features tried. So in these made-up examples the OOB score is close to the test score and a little low.
The OOB score is only as trustworthy as the bootstrap’s assumption that examples are independent draws. If the data have groups (several rows from the same patient) or a time order, an out-of-bag row can have near-twins in the training part of its bag, and the OOB score will be too optimistic: use a split that respects the groups or time (P3.A4). And if you tune many settings against the OOB score, it stops being an untouched estimate, as with any validation set.
Tuning the feature subset
Using all 20 features is bagging. On 20 made-up data sets with 20 features (5 informative), a middle setting won: 10 features per split gave 84.6% test accuracy, against 83.8% for bagging, 83.2% for the default and 77.8% for one feature at a time. The gaps between 4, 10 and 20 are about a point, and the best value differs on other data. So max_features is a dial between trees that are individually strong and trees that are different from each other, and the OOB score is a cheap way to set it.
Go deeper The max_features experiment in code
The experiment uses made-up data with 20 features, of which only 5 carry signal, 300 training and 1200 test examples, and forests of 100 trees, repeated for 20 seeded data sets. The printed numbers are the mean test and out-of-bag accuracy over the 20 data sets, from a local run.
import numpy as np
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
settings = (1, 2, 4, 10, 20) # max_features; 4 is the default "sqrt" for 20 features
test = {m: [] for m in settings}
oob = {m: [] for m in settings}
for s in range(20): # 20 made-up data sets: 20 features, 5 informative
X, y = make_classification(n_samples=1500, n_features=20, n_informative=5, n_redundant=0,
n_clusters_per_class=2, flip_y=0.05, random_state=100 + s)
Xa, Xb, ya, yb = train_test_split(X, y, train_size=300, random_state=s)
for m in settings:
rf = RandomForestClassifier(n_estimators=100, max_features=m, oob_score=True,
random_state=0).fit(Xa, ya)
test[m].append(rf.score(Xb, yb))
oob[m].append(rf.oob_score_)
print("max_features test oob")
for m in settings:
print("%12d %.3f %.3f" % (m, np.mean(test[m]), np.mean(oob[m])))max_features test oob
1 0.778 0.753
2 0.810 0.795
4 0.832 0.821
10 0.846 0.838
20 0.838 0.832Which features matter?
A forest can report how much each feature mattered.
Impurity-based importance (scikit-learn’s feature_importances_) adds up, over all splits that use a feature and over all trees, how much each split reduced the impurity (P3.B3), and scales the totals to sum to 1. It is free, but it has two weaknesses. It is computed from the training data, so a feature that lets trees fit noise is rewarded. And it favours features with many distinct values (continuous features over yes/no features), because a feature with many possible split points gets more chances to find a split that looks good by luck.
Permutation importance (introduced for random forests in Breiman, 2001, and available for any model as permutation_importance in sklearn.inspection) works on held-out data: shuffle one feature’s values, which breaks its link with the target, and measure how much the score drops. A feature the model relies on causes a large drop. A useless feature causes a drop near zero.
In a made-up test where only a two-valued feature matters, impurity importance ranked a pure-noise feature with 1000 distinct values first (0.662 against 0.338), while permutation importance on held-out data got the order right (accuracy drop 0.188 against 0.014).
Go deeper The importance demonstration in code
The target depends only on x_signal, a feature with two values. x_noise is unrelated to the target and has 1000 distinct values.
import numpy as np
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
rng = np.random.default_rng(0)
n = 1000
x_signal = rng.integers(0, 2, n) # informative, only 2 distinct values
x_noise = rng.standard_normal(n) # unrelated to y, many distinct values
p = 1 / (1 + np.exp(-1.5 * (2 * x_signal - 1))) # y depends on x_signal only
y = (rng.random(n) < p).astype(int)
X = np.c_[x_signal, x_noise]
Xa, Xb, ya, yb = X[:500], X[500:], y[:500], y[500:]
rf = RandomForestClassifier(n_estimators=300, random_state=0).fit(Xa, ya)
print("impurity signal %.3f noise %.3f" % tuple(rf.feature_importances_))
pi = permutation_importance(rf, Xb, yb, n_repeats=30, random_state=0) # on held-out data
print("permutation signal %.3f noise %.3f" % tuple(pi.importances_mean))impurity signal 0.338 noise 0.662
permutation signal 0.188 noise 0.014Permutation importance has its own trap: if two features carry the same information, shuffling one leaves the other to cover for it, and both look unimportant. And neither measure says that changing a feature would change the outcome: importance describes the model, not the world.
Where forests shine and where they do not
Strengths. On tabular data (rows of mixed numeric and category-like columns) a random forest with default settings is a strong baseline. It needs no feature scaling (trees only compare a feature with thresholds), handles features of different scales and kinds, picks up interactions and non-linear effects, tolerates some irrelevant features, and has few settings that matter much (max_features, and the minimum leaf size for noisy data). Trees can be grown in parallel, and the OOB score tunes it without a validation set.
Limits.
- No extrapolation. A tree predicts a stored value from its training data, so a regression forest never predicts outside the range of the training targets. In the second cell below, a tree trained on for between 0 and 1 answers 2 at both and . A linear model would extend the line.
- Hard to interpret. One small tree can be read as a flowchart. Hundreds of deep trees cannot. Importances and partial-dependence plots summarise the forest but do not explain a single prediction.
- Size and speed. The model stores large trees and every prediction walks through all of them. This matters for memory-limited devices and for tight response times.
- Probabilities. The vote share is not a calibrated probability; check it (P3.A10) before using it as one.
- Raw signals. For images, audio and text, where the useful features are not given, neural networks (Part 4) learn them; forests on raw pixels do poorly by comparison.
Compared with boosting. Bagging grows deep, low-bias trees in parallel and averages away their variance. Boosting (P3.B5) grows shallow trees one after another, each correcting the errors left by the previous ones, and lowers bias. They share the tree-building machinery and are often the two best choices for a tabular problem.
Try it: bootstrap, variance, and a tiny forest in NumPy
The first cell checks the 63.2% and the variance formula by simulation. The second grows a small regression tree in NumPy (one input, split by squared error), bags it on the noisy curve of P3.A5, and measures bias² and variance over 100 training sets (it takes a few seconds). It also shows that a tree cannot extrapolate.
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
The output of the first cell, on the machine used for this lesson, is below. The simulated variances match the formula to within sampling error, and the bootstrap sample of 5 matches the example in the text.
sample of 5: E D C B B | left out: A
n=100: 0.635 of the examples appear (spread 0.031); formula 0.634; limit 0.632
example 0 is out-of-bag in 357 of 1000 samples (expected about 366)
B rho simulated formula
4 0.0 0.0397 0.0400
4 0.5 0.1001 0.1000
4 1.0 0.1594 0.1600
50 0.5 0.0816 0.0816
Runs real Python in your browser. First run downloads about 9 MB (once; your browser keeps it).
B bias2 var total (with noise)
1 0.0023 0.1041 0.196
4 0.0018 0.0562 0.148
16 0.0018 0.0467 0.139
y = 2x, trained on [0, 1]: tree at x = 0.5, 1.5, 3 -> [0.98 2. 2. ]
Read the table the way P3.A5 taught. The bias² stays near 0.002 for every : averaging did not change it. The variance falls from 0.104 for one bootstrap tree to 0.047 for 16, so the total expected error falls from 0.196 to 0.139 (the noise is part of every total and cannot be removed).
Go deeper Estimating the correlation from the table
Solving for , with (one tree) and , gives . The formula then predicts a variance of for four trees, close to the measured , and a floor of : even a thousand trees could not take the variance much below it. The formula treats all pairs as having the same correlation and is estimated from the same simulation, so this is a consistency check, not an independent proof.
Common misunderstandings
Intuition
A panel of experts, each of whom studied a slightly different set of case files, votes on a diagnosis. Each expert is individually moody: a small change in the files changes their opinion. But the moods point in different directions, so the vote is steady. If you hire experts who all trained under the same professor and read the same files, their errors agree and the vote is no steadier than one expert. A random forest also tells each expert to look at only some of the symptoms at each step, so they do not all follow the same obvious clue. The analogy breaks in one place: our trees are not independent, and the whole lesson is about how much that correlation costs.
Math
Averaging identically distributed predictors leaves the expected value unchanged: , so the bias is that of one predictor.
The probability that a given example is missing from a bootstrap sample of is . Out-of-bag voting for example uses the set of trees .
Code
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=300, max_features="sqrt",
oob_score=True, n_jobs=-1, random_state=0)
rf.fit(X_train, y_train)
print(rf.oob_score_) # validation-style accuracy, no held-out set needed
print(rf.feature_importances_) # impurity-based: check with permutation_importanceSet random_state for repeatable results (P1.G3): the bootstrap draws and feature subsets are random.
Check your understanding
Ten models each have prediction variance , and any two of them have correlation . What is the variance of their average, and what does it approach as more such models are added?
The variance is . Adding models removes only the second term, so it approaches the floor . The value would hold only for independent models. Independence would also let the variance approach , but these models are correlated. The value is the variance of one model, which averaging does lower.
A bootstrap sample is drawn from a training set of 1000 examples. Roughly what share of the distinct training examples is missing from it?
Each example is missed with probability , the limit . The value is the share that does appear. The shares and do not come from the calculation.
Why does a random forest let each split look at only a random subset of the features?
If one strong feature dominates, bagged trees all split on it first and look alike, which keeps high. Hiding features forces variety. It does not make a single tree better at fitting; the gain comes from the trees being less alike. Speed is a side benefit, not the purpose, and the accuracy does change. Pruning is not part of the method.
A student computes the out-of-bag score of a forest. What does the score measure?
Each example is scored by the trees whose bootstrap sample missed it, so no tree that predicts it has seen it. Scoring each tree on the full training set would include examples it was trained on. A separate test set is a different method that does hold data back. The share of trees voting correctly is a vote margin, not the accuracy of the majority vote.
A random forest is trained to predict house prices, and the training prices range from to . What will it predict for a house far larger and better than any in the training set?
Each tree returns the mean of some training targets, so the forest returns an average of such means and cannot leave the range of the training targets. A linear model would continue the trend, a forest does not. It does not raise an error. It also does not fall back to the overall average: a house like the largest training houses lands in leaves with the highest prices.
Exercises
- A bootstrap sample of examples is drawn with replacement. What is the probability that a given example is missing from it, and how many distinct examples does a sample contain on average?
Show answer
The probability is . By linearity of expectation (P1.D4) the expected number of distinct examples is . - A forest has trees and 100 training examples. About what share of the examples is out-of-bag for no tree at all, so they get no OOB prediction? And at ?
Show answer
An example gets no OOB prediction if it is in-bag for every tree: probability with (the limit is ). At that is about , about 1 example in 100. At it is , so only about 36 of 100 get a prediction, as the widget shows. - A regression forest in scikit-learn 1.8 is trained on a table with features and default settings. How many features does each split look at? And a classification forest with default settings?
Show answer
Regression:max_features=1.0, all 16, so it is bagging of trees. Classification:max_features="sqrt", which is features per split. - Widget: in the bagging setting, move from to and note the training accuracy and the test accuracy at both ends. Which of them changes more, and why?
Show answer
The training accuracy goes from 96% to 100%, and the test accuracy from 86.25% to 89.5%. The training accuracy was already high; the single tree misses a few training points because its bootstrap sample left them out. The test accuracy is the one that shows the gain from averaging. - In the box on estimating the correlation, the estimate was and the single-tree variance was . What is the lowest variance that a bagged ensemble of these trees could reach, and what would you change to push it lower?
Show answer
The floor is . Adding trees cannot go below it; the trees must be made less correlated, for example by letting each split use a random subset of the features. (With the single input of that cell there is no subset to choose from.) - A colleague says: “My forest’s impurity importance ranks the customer ID column (a different number for every row) as the most important feature, so IDs predict churn.” What is probably going on, and what would you do?
Show answer
A column with a different value for every row offers many split points, and trees can use it to memorise training rows. Impurity importance, computed from the training data, rewards that. Compute permutation importance on held-out data: a column that does not generalise gives a drop near zero. Also remove identifiers from the features.
Next: P3.B5 builds trees one after another instead of in parallel, so that each tree corrects the errors of the earlier ones: boosting lowers bias where bagging lowers variance. P3.A6 and P4.17 return to the same variance-reduction idea through penalties and dropout.