Settings

Theme
Lite Mode (saves mobile data)

In Lite Mode, animations and videos don't play until you tap them, and their size is shown first. Interactive widgets still work.

Text size

Back up or move your progress →

Part 3: Classical Machine LearningClassic Algorithms

Bagging and random forests

P3.B440 min●●○ IntermediateReviewed Dec 2, 2026

Why this matters for machine learning

A single fully grown decision tree fits its training data perfectly and changes a lot when the data change. Averaging many trees that were trained on resampled data keeps the flexibility and removes much of that instability, which makes random forests a strong default for tabular data.

  • Boosting also combines many trees, but builds them one after another to reduce bias instead of averaging them to reduce variance. (P3.B5: Boosting)
  • The data left out of each bootstrap sample give an out-of-bag error, a validation estimate that needs no separate validation set. (P3.A4: Train, validation and test sets)
  • Isolation forests, a method for finding unusual examples, also build many random trees, but they use them to measure how easily a point is isolated. (P3.C5: Anomaly detection)
  • Dropout in neural networks is often described as training and averaging a very large crowd of thinned networks. (P4.17: Regularization for neural nets)

Before this: Decision trees, The bias–variance trade-off, Train, validation and test sets, Law of large numbers and the Central Limit Theorem

After this lesson you can

  • Explain why the average of several noisy predictors has lower variance, derive the variance ρv + (1 − ρ)v/B for correlated predictors, and say why the correlation sets a floor
  • Draw a bootstrap sample, show that about 63.2% of the distinct examples appear in it, and say which examples are out-of-bag
  • Describe bagging and a random forest step by step, and say what the feature subset at each split (max_features) changes
  • Use the out-of-bag error as a validation estimate, read feature importances without being fooled by their bias, and name the limits of forests

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 BB predictors T1,…,TBT_1,\dots,T_B (for example, BB trees) and average their predictions at one input. Suppose each has variance vv, and each pair has correlation ρ\rho. Here ρ\rho 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 ρv\rho v.

Write Tˉ=1B∑b=1BTb\bar T=\frac1B\sum_{b=1}^B T_b for the average. Then

Var[Tˉ]=B v+B(B−1) ρvB2=ρv+(1−ρ) vB.\begin{aligned} \mathrm{Var}[\bar T] &=\frac{B\,v+B(B-1)\,\rho v}{B^2}\\ &=\rho v+\frac{(1-\rho)\,v}{B}. \end{aligned}

Two cases to remember.

  • Independent errors (ρ=0\rho=0): the variance is v/Bv/B. This is the law of large numbers at work (P1.D8): the average of BB independent draws has 1/B1/B of the variance of one draw.
  • Identical errors (ρ=1\rho=1): the variance is vv. Averaging copies of one predictor changes nothing.

In between, adding more predictors shrinks only the second term. As BB grows the variance approaches the floor ρv\rho v. With the numbers of P3.A5’s exercise (v=0.16v=0.16): for B=4B=4 the variance is 0.040.04 if ρ=0\rho=0 and 0.100.10 if ρ=0.5\rho=0.5, and with ρ=0.5\rho=0.5 no number of models can push it below 0.080.08.

What about the bias? The average of BB 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 vv is, and how small we can make ρ\rho. 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 nn examples is made by drawing nn 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 1−1n1-\tfrac1n. The nn draws are independent, so it is missed in all of them with probability

(1−1n)n→e−1≈0.368(n→∞).\Bigl(1-\frac1n\Bigr)^{n}\to e^{-1}\approx 0.368\quad(n\to\infty).

(This is a standard limit from calculus.) So about 36.8%36.8\% of the examples are out-of-bag for a given bootstrap sample, and about 63.2%63.2\% of the distinct examples appear in it. The limit is reached quickly: the exact values are 0.3490.349 for n=10n=10, 0.3660.366 for n=100n=100 and 0.3680.368 for n=1000n=1000. For n=4n=4 the exact value is (3/4)4=0.316(3/4)^4=0.316.

Two details. A bootstrap sample still has nn rows, but they are not nn different examples: about 0.632 n0.632\,n 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:

  1. For b=1,…,Bb=1,\dots,B: draw a bootstrap sample of the training set and grow a deep tree on it.
  2. To predict, ask all BB 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: ρ<1\rho<1. 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 ρv\rho v 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: ρ\rho 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 d\sqrt d of the dd features.
  • For regression the default is max_features=1.0, which means all dd 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’s randomForest, following a rule of thumb from the original forest literature. scikit-learn’s regression default has always been all the features, so you must set max_features yourself 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.

−1.5−1−0.500.511.522.5−1−0.500.511.5feature 1feature 2

● class 0 and ▲ class 1 training points; background colour is the vote of the trees (pale = close vote).

training accuracy: 96%
test accuracy: 86.25%
out-of-bag accuracy: 88.89%
examples with an out-of-bag tree: 36 of 100
first tree alone, test accuracy: 86.25%

One tree: the boundary is a jagged set of rectangles that bends around single points, noise included. Test accuracy 86.25%.

Decision regions of a forest on made-up crescent data. The colour of each cell is the class that most of the first B trees vote for; a pale cell means a close vote. Circles are class 0 and triangles are class 1 (training points). The readouts give accuracy on the 100 training points, on 400 test points, and the out-of-bag accuracy. Controls: number of trees, bagging (both features at each split) or a random forest (one random feature at each split), and a toggle for the test points.

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 B=10B=10 and 89.5% at B=100B=100. The training accuracy reaches 100% by B=30B=30: 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, (1−ρ)v/B(1-\rho)v/B, and leave the floor ρv\rho v alone. So the gain per tree shrinks quickly. The numbers below are from the widget’s data: test accuracy of the first BB trees on the 400 test points.

Trees BBBaggingRandom forest
186.25%81.5%
589%83.75%
1089%89.75%
3089.75%89.75%
10089.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 BB can dip: at B=2B=2 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 BB. 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.

  1. For each training example, collect the trees for which it is out-of-bag. With BB trees that is about 0.368 B0.368\,B trees.
  2. Let only those trees predict the example (vote or average).
  3. 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-BB effects. With B=1B=1, 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 BB trees is 0.632B0.632^B, about 1%1\% at B=10B=10. And each example is scored by only about 0.37 B0.37\,B 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 20≈4\sqrt{20}\approx4 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.832

Which 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.014

Permutation 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 y=2xy=2x for xx between 0 and 1 answers 2 at both x=1.5x=1.5 and x=3x=3. 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 BB 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.

Try it: bootstrap and the variance of an average

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
Try it: bag a tiny regression tree

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 BB: 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 σ2=0.09\sigma^2=0.09 is part of every total and cannot be removed).

Go deeper Estimating the correlation from the table

Solving V16=ρv+(1−ρ)v/16V_{16}=\rho v+(1-\rho)v/16 for ρ\rho, with v=0.1041v=0.1041 (one tree) and V16=0.0467V_{16}=0.0467, gives ρ≈0.41\rho\approx0.41. The formula then predicts a variance of 0.0580.058 for four trees, close to the measured 0.0560.056, and a floor of ρv≈0.043\rho v\approx0.043: even a thousand trees could not take the variance much below it. The formula treats all pairs as having the same correlation and ρ\rho 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 BB identically distributed predictors leaves the expected value unchanged: E[1B∑bTb]=E[T1]\mathbb{E}\bigl[\tfrac1B\sum_b T_b\bigr]=\mathbb{E}[T_1], so the bias is that of one predictor.

The probability that a given example is missing from a bootstrap sample of nn is (1−1/n)n→e−1(1-1/n)^n\to e^{-1}. Out-of-bag voting for example ii uses the set of trees {b:i∉sampleb}\{b: i\notin\text{sample}_b\}.

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_importance

Set random_state for repeatable results (P1.G3): the bootstrap draws and feature subsets are random.

Check your understanding

  1. Ten models each have prediction variance 0.200.20, and any two of them have correlation 0.30.3. What is the variance of their average, and what does it approach as more such models are added?

  2. A bootstrap sample is drawn from a training set of 1000 examples. Roughly what share of the distinct training examples is missing from it?

  3. Why does a random forest let each split look at only a random subset of the features?

  4. A student computes the out-of-bag score of a forest. What does the score measure?

  5. A random forest is trained to predict house prices, and the training prices range from 50 00050\,000 to 400 000400\,000. What will it predict for a house far larger and better than any in the training set?

Exercises

  1. A bootstrap sample of n=4n=4 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 answerThe probability is (3/4)4=0.316(3/4)^4=0.316. By linearity of expectation (P1.D4) the expected number of distinct examples is 4 (1−0.316)=2.734\,(1-0.316)=2.73.
  2. A forest has B=10B=10 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 B=1B=1?
    Show answerAn example gets no OOB prediction if it is in-bag for every tree: probability 0.634B0.634^{B} with n=100n=100 (the limit is 0.632B0.632^B). At B=10B=10 that is about 0.01050.0105, about 1 example in 100. At B=1B=1 it is 0.6340.634, so only about 36 of 100 get a prediction, as the widget shows.
  3. A regression forest in scikit-learn 1.8 is trained on a table with d=16d=16 features and default settings. How many features does each split look at? And a classification forest with default settings?
    Show answerRegression: max_features=1.0, all 16, so it is bagging of trees. Classification: max_features="sqrt", which is 16=4\sqrt{16}=4 features per split.
  4. Widget: in the bagging setting, move from B=1B=1 to B=100B=100 and note the training accuracy and the test accuracy at both ends. Which of them changes more, and why?
    Show answerThe 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.
  5. In the box on estimating the correlation, the estimate was ρ=0.41\rho=0.41 and the single-tree variance was 0.1040.104. What is the lowest variance that a bagged ensemble of these trees could reach, and what would you change to push it lower?
    Show answerThe floor is ρv=0.41⋅0.104≈0.043\rho v=0.41\cdot0.104\approx0.043. 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.)
  6. 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 answerA 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.

Key takeaways

  • A crowd helps only if its members are partly independent. For B predictors with variance v and pairwise correlation ρ, the average has variance ρv + (1 − ρ)v/B and the same bias as one predictor. More members shrink the second term but never the first.
  • A bootstrap sample draws n examples with replacement from n, so about 63.2% of the distinct examples appear in it and about 36.8% are out-of-bag. Bagging averages (or votes) one deep tree per bootstrap sample; a random forest also lets each split see only a random subset of the features, which makes the trees less alike.
  • More trees do not make a forest overfit: the error levels off, at a cost in time and memory. The feature subset size max_features is the setting that matters most, and the out-of-bag error (each example scored only by trees that never saw it) tunes it for free.
  • Impurity-based feature importance favours features with many distinct values, so check it with permutation importance on held-out data. Forests are strong on tabular data, but cannot extrapolate beyond the target values they saw and are hard to read as a whole.
Found a mistake? Tell us