Random forest

A random forest grown live, one tree per step: bootstrap samples, random features at each split, out-of-bag error and the averaged vote, in 2D and as 3D terrain and tree layers.

Updated

  • Bagging
  • Random feature selection
  • Out-of-bag error
  • Why averaging reduces variance
  • Forest versus a single tree
T = 1T = 2T = 3T = 4T = 5T = 6T = 6(1/T) Σ treeₜ(x)
Preparing the lab…

Intuition

One tree is unstable; average many

A single deep tree's boundary is pieced together from axis-aligned cuts, jagged and quick to memorise the noise in the training set. If we had many independent training sets, grew a tree on each and averaged, the noise-driven jags would cancel and the true shape would remain. A random forest uses the bootstrap to "manufacture" many slightly different training sets from the same data.

The three small labs below really grow the trees one by one in your browser. The background is the average probability of all trees so far (darker means the trees agree more), and the points are the training data. All three use the same spiral data.

1 treePreparing…
60 treesPreparing…
60 identical treesPreparing…

The first has a single tree, grown on a bootstrap sample with each split looking at one random feature: its boundary is fragmented and test accuracy is 91.7%. The second averages 60 such trees; the boundary follows the spiral and test accuracy is 99.2%.

The third switches off both sources of randomness: every tree uses all the samples and every split looks at all the features, so the 60 trees are identical (12 leaves each), their average is just that one tree, and test accuracy stays at 97.5%. The randomness is not noise — it is why the forest works.

Math

The algorithm

Training data: nn samples with dd features. For tree b=1,…,Bb = 1, \dots, B:

  1. bootstrap: draw nn times with replacement from the nn samples and record how many times each sample was drawn, wiw_i (0, 1, 2…);
  2. grow a CART classification tree (Gini impurity) with wiw_i as sample weights; each split searches for the best threshold among only mm randomly chosen features;
  3. a leaf's class probability pb(c∣x)p_b(c \mid x) is the weighted proportion of each class in that leaf.

The forest predicts by "soft voting", as scikit-learn does:

pˉ(c∣x)=1B∑b=1Bpb(c∣x),y^=arg⁡max⁡cpˉ(c∣x)\bar p(c \mid x) = \frac{1}{B}\sum_{b=1}^{B} p_b(c \mid x), \qquad \hat y = \arg\max_c \bar p(c \mid x)

The lab grows one tree per step and updates the average incrementally: pˉB=((B−1) pˉB−1+pB)/B\bar p_B = \big((B-1)\,\bar p_{B-1} + p_B\big)/B.

Why averaging helps

If each tree's prediction has variance σ2\sigma^2 and any two trees have correlation ρ\rho, the average of BB trees has variance

ρ σ2+1−ρB σ2\rho\,\sigma^2 + \frac{1-\rho}{B}\,\sigma^2

The second term goes to 0 as trees are added; the first does not. So adding trees is not enough — the trees must also be less correlated, which is exactly what bootstrapping and random features achieve. In the third small lab ρ=1\rho = 1, and no number of trees helps.

Out-of-bag error

Drawing nn times with replacement, the probability that a given sample is never drawn is

(1−1n)n→1e≈36.8%\left(1 - \frac1n\right)^n \to \frac1e \approx 36.8\%

With this page's default 240 training samples, an average of 36.9% of the samples are out of bag for each of 60 trees. Letting each training sample be voted on only by the trees that never saw it gives the out-of-bag accuracy — cross-validation for free. With 60 trees on the default data the out-of-bag accuracy is 98.75% and the test accuracy 99.17%, very close.

Are more trees better?

TreesTrainTestOut of bag
195.83%91.67%89.41%
10100%99.17%95.83%
60100%99.17%98.75%
150100%99.17%98.33%

Adding trees does not overfit; past some number it just stops improving (and gets slower). What really controls overfitting is each tree's complexity: with maximum depth 3 the 60-tree forest scores only 92.5% on test (underfitting), depth 5 gives 97.5%, and the default 10 gives 99.17%.

One tree versus a forest

DataSingle CARTForest of 60 trees
Spiral97.50%99.17%
Spiral, noise 0.691.67%92.50%
Three clusters89.17%90.83%
XOR90.00%94.17%

"Single CART" is an ordinary decision tree with no sampling and all features (the same as on the decision-tree page). The forest is better on every dataset, but by how much depends on the data: where the classes genuinely overlap (three clusters, heavy noise), nobody can classify the points in the overlap.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: bootstrap, random features and voting

5 steps · each one: set up and run → look → answer

  1. 1. The first tree

    Default spiral data, one tree only. Open the "Latest tree" tab.

    Why are some points drawn hollow?
  2. 2. A few more trees

    Grow 8 trees and look at "Last 8 trees".

    Why are the 8 trees all different?
  3. 3. The averaged vote

    Grow all 60 trees, go back to "Forest vote" and look at the error curves on the right.

    Test accuracy rises from 91.7% with one tree to 99.2%, and out-of-bag accuracy is 98.75%. Why can the out-of-bag accuracy estimate the test accuracy?
  4. 4. Switch off the randomness

    Set sampling to "All samples" and features per split to 2.

    Why are 60 trees exactly as good as one (97.5%)?
  5. 5. Trees that are too shallow

    Set the maximum depth to 3.

    60 trees reach only 92.5%. Why can't the forest rescue them?

Try these settings

At noise 0.6, a minimum leaf size of 1 or 5 gives the same 92.5% test accuracy, but training accuracy drops from 100% to 96.25%: with slightly larger leaves each tree memorises less noise.

Exercises

Exercises

Exercise 1: bring the randomness back

Right now every tree is the same and test accuracy is 97.5%. Change the settings to reach at least 99% test accuracy with the forest.

Hint

Switch bootstrap sampling back on: 99.17% with 1 feature per split, 100% with 2.

  • Test accuracy ≥ 99.0%

Exercise 2: one tree is not enough

On the XOR data one tree reaches only 76.7% test accuracy. Change the settings to reach at least 94%.

Hint

Set the number of trees back to 60: 94.17%.

  • Test accuracy ≥ 94.0%

Quiz

In bootstrap sampling, roughly how likely is a sample to be left out of a given tree?
As you keep adding trees to a random forest, the test error usually…
Why look at only a random subset of features at each split?

Further reading

Frequently asked questions

What is the difference between a random forest and a decision tree?

A decision tree is one tree; a random forest is many trees grown on bootstrap samples with random features, whose probabilities are averaged at prediction time. A single deep tree has high variance and overfits easily; the forest reduces variance by averaging and is usually more accurate and more stable, at the cost of speed and interpretability.

Can a random forest overfit?

Adding trees does not make it overfit, but trees that are too deep with leaves that are too small will still memorise noise on noisy data. Control them with the maximum depth and minimum leaf size, and check with the out-of-bag error.

What is the out-of-bag (OOB) error?

About 37% of the samples take no part in training each tree. Let each sample be voted on only by the trees that never saw it and count the mistakes: that is the out-of-bag error. It approximates the cross-validation error without holding out a validation set.

How should I choose max_features?

√d is common for classification, d/3 or all features for regression. Smaller values make the trees less correlated but each tree weaker. This page has only 2 features, so each split looks at 1 (random) or 2 (all).

What is the difference between a random forest and gradient boosting?

A random forest trains many deep trees in parallel and averages them, mainly reducing variance; gradient boosting trains many shallow trees in sequence, each fitting the residuals of those before, mainly reducing bias. Gradient boosting is often more accurate but more sensitive to the learning rate, tree depth and number of stages.

Further reading