Search

Search papers and lessons

Random Forest

Level 3 · 10 min read

A random forest averages many decision trees, each grown on a random resample of the data and allowed to see only a random subset of features at each split, which cancels out their individual errors.

On this page

  • Colour = topic mix
  • Discrete math
  • Probability
  • Classical models
  • Calculus
  • Learning basics
  • Sampling
  • Sign in to see your progress

TL;DR

A random forest is a crowd of decision trees. Each tree is grown on a random resample of the training data, and at every split it may consider only a random subset of the features. The forest predicts by averaging the trees (for numbers) or taking a majority vote (for categories).

Single deep trees are flexible but unstable: they chase noise. Averaging many of them (Ensemble Learning) keeps the flexibility and removes much of the instability, and the random choices keep the trees from all making the same mistake.

Where you'll see it: as a strong default for tabular data (rows of examples, columns of measured features, such as customer records and sensor logs), as a quick baseline before reaching for heavier models, and as a way to rank which input features matter most.

Intuition

Imagine a hard question, such as whether a loan will default, and a room of analysts. Each analyst has seen a different random sample of past loans, and each one is allowed to look at only a random handful of the available details before making a decision. Any single analyst is noisy. But if you average their answers, the individual quirks mostly cancel out, and what remains is the signal they all share.

A single decision tree is one such analyst. Left to grow, it keeps asking questions until every training example sits in its own leaf, so it memorises the training set, noise included (Overfitting). That makes it low in bias but high in variance (the Bias-Variance Tradeoff; variance is explained in Mean and Variance): change the training data slightly and the tree changes a lot.

Bagging (Bagging) fixes part of this by training each tree on a bootstrap resample (Bootstrap Sampling) and averaging. But there is a catch. If one feature is very strong, every tree will split on it first, and the trees become similar. Averaging similar trees removes little variance. The random forest adds a second source of randomness, the feature subset at each split, so the trees differ more from one another.

102030405000.20.40.60.81number of trees Bvariance of the average
  • trees correlated at 0.5
  • trees correlated at 0.1
Variance of the forest's average, relative to one tree's variance. More trees always help, but the curve levels off at the correlation between trees, so making trees less alike lowers the floor.

The math

The bootstrap sample

Given nn training examples, the tree bb is trained on a bootstrap sample of size nn: draw nn examples with replacement. Each example has probability 1−1/n1 - 1/n of not being drawn on a single draw, so the chance it is never drawn in all nn draws is (1−1/n)n(1 - 1/n)^n. As nn grows this approaches e−1≈0.368e^{-1} \approx 0.368. So each tree sees about 63 percent of the distinct training examples, and about 37 percent are left out. Those left-out examples are called out-of-bag for that tree.

Random feature selection

At each node of a tree, the algorithm draws mm of the pp features at random and searches only among them for the best split. A common default is m≈pm \approx \sqrt{p} for classification and m≈p/3m \approx p/3 for regression.

For classification the split quality is usually measured with Gini impurity. If a node holds a fraction pkp_k of class kk, its impurity is

G=∑kpk(1−pk),G = \sum_k p_k (1 - p_k),

which is 0 for a pure node and largest when the classes are evenly mixed. The tree chooses the split that most reduces the weighted impurity of its children. (Entropy, see Entropy, can be used instead; the idea is the same.)

Aggregation

Let Tb(x)T_b(\mathbf{x}) be the prediction of tree bb for input x\mathbf{x}. With BB trees, the forest predicts

y^(x)=1B∑b=1BTb(x)\hat{y}(\mathbf{x}) = \frac{1}{B} \sum_{b=1}^{B} T_b(\mathbf{x})

for regression, and the majority class (or the average of predicted class probabilities) for classification.

Why averaging helps: the variance formula

Suppose each tree's prediction at a fixed input has variance σ2\sigma^2, and every pair of trees has correlation ρ\rho (a number from 0, unrelated, to 1, identical). The variance of the average is

Var ⁣(1B∑b=1BTb)=1B2[∑bVar(Tb)+∑b≠cCov(Tb,Tc)].\mathrm{Var}\!\left(\frac{1}{B}\sum_{b=1}^{B} T_b\right) = \frac{1}{B^2}\left[\sum_b \mathrm{Var}(T_b) + \sum_{b \neq c} \mathrm{Cov}(T_b, T_c)\right].

There are BB variance terms, each σ2\sigma^2, and B(B−1)B(B-1) covariance terms, each ρσ2\rho\sigma^2. So

Var=σ2(ρ+1−ρB).\mathrm{Var} = \sigma^2\left(\rho + \frac{1 - \rho}{B}\right).

The first term, ρσ2\rho\sigma^2, does not shrink as BB grows. It is the floor. Only the second term, which is the part due to each tree's own randomness, falls with more trees. Lowering ρ\rho is therefore the lever that matters. That is exactly what the random feature selection does.

Out-of-bag error

Each example is out-of-bag for about 37 percent of the trees. Predict each training example using only the trees that did not see it, then compare with the true label. The result is an honest error estimate with no separate validation set, which is useful when data is scarce (see Train, Validation and Test Sets).

Worked examples

Example
1. Averaging three trees by hand

Suppose one tree's prediction error at a fixed input has variance σ2=4\sigma^2 = 4, and any two trees have correlation ρ=0.5\rho = 0.5. A forest with B=3B = 3 trees has variance

  1. Plug into the formula: σ2(ρ+1−ρB)=4(0.5+0.53)\sigma^2\left(\rho + \frac{1 - \rho}{B}\right) = 4\left(0.5 + \frac{0.5}{3}\right).
  2. Compute the bracket: 0.5+0.1667=0.66670.5 + 0.1667 = 0.6667.
  3. Multiply: 4×0.6667≈2.674 \times 0.6667 \approx 2.67.

Interpretation: a single tree has variance 4, and the three-tree forest has about 2.67. Two-thirds of the single-tree variance survives, because the trees' shared errors cannot be averaged away. With BB large, the variance approaches ρσ2=2\rho\sigma^2 = 2, and the rest of the reduction is limited by how correlated the trees are.

Example
2. Choosing a split with Gini impurity (the textbook case)

A node holds 10 examples: 6 spam and 4 not spam. Two candidate splits are available.

Parent: pspam=0.6p_{\text{spam}} = 0.6, so G=2(0.6)(0.4)=0.48G = 2(0.6)(0.4) = 0.48.

Split A sends 5 examples left (4 spam, 1 not) and 5 right (2 spam, 2 not).

  1. Left: p=0.8p = 0.8, so G=2(0.8)(0.2)=0.32G = 2(0.8)(0.2) = 0.32.
  2. Right: p=0.5p = 0.5, so G=0.50G = 0.50.
  3. Weighted impurity: 0.5(0.32)+0.5(0.50)=0.410.5(0.32) + 0.5(0.50) = 0.41. Gain: 0.48−0.41=0.070.48 - 0.41 = 0.07.

Split B sends 6 examples left (5 spam, 1 not) and 4 right (1 spam, 3 not).

  1. Left: p=5/6p = 5/6, so G=2(5/6)(1/6)≈0.278G = 2(5/6)(1/6) \approx 0.278.
  2. Right: p=0.25p = 0.25, so G=0.375G = 0.375.
  3. Weighted impurity: 0.6(0.278)+0.4(0.375)≈0.3170.6(0.278) + 0.4(0.375) \approx 0.317. Gain: 0.48−0.317=0.1630.48 - 0.317 = 0.163.

Interpretation: split B removes more impurity, so a tree that considers both splits picks B. If the random feature subset at that node contains only the feature for split A, the tree must use A, which is the randomness the forest relies on.

Example
3. A forest on twenty features

A forest has 500 trees on a dataset with p=20p = 20 features. Use m=20≈4.5m = \sqrt{20} \approx 4.5, rounded to 4 features per split.

  1. Chance a given feature is among the 4 candidates at a split: 4/20=0.24/20 = 0.2. So a strong feature is hidden from 80 percent of the splits, and different trees take different routes to the same answer.
  2. Out-of-bag coverage: each example is out-of-bag for about 500×0.368≈184500 \times 0.368 \approx 184 trees, which is enough to form a stable out-of-bag prediction for it.
  3. Feature importance by permutation: shuffle one feature's column in the out-of-bag data and measure how much the accuracy drops. A large drop means the forest relies on that feature.

The counts here are simple arithmetic for this setup, not measurements. They show how each design choice touches the result: fewer candidate features mean more diverse trees, and out-of-bag predictions cost nothing extra.

Tradeoffs and failure modes

SituationWhat goes wrongBetter choice
Data is images, audio or text with rich structureTrees split on raw pixels or words poorly, and forests lose to learned features.Use a Feedforward Neural Network or a model suited to the structure.
You need calibrated probabilitiesCalibrated means a predicted 0.8 really comes true about 80 percent of the time. Averaged votes from many trees rarely come out near 0 or 1, so the probabilities tend to be pulled toward the middle.Apply a calibration step, or use a model trained to output probabilities directly.
The model must extrapolate beyond the training rangeTrees predict a constant in each leaf, so they cannot go past the largest value seen.Use a linear model, or a method that extrapolates.
Prediction must be very fast with a tight memory budgetHundreds of deep trees take time and memory.Limit tree depth, reduce the number of trees, or train one small model to imitate the forest's outputs.
Features are very many and mostly noiseRandom feature subsets often contain only noise, so each tree is weak.Remove irrelevant features first, or increase mm.

Random forests are rarely the best model on a dataset they were not designed for, but they are hard to beat as a reliable first try: they need little tuning and seldom overfit badly.

History

Tin Kam Ho introduced random decision forests in 1995, using random subspaces of the features to grow each tree. Yali Amit and Donald Geman had used a related randomised-tree idea for shape recognition in 1997. Leo Breiman brought the pieces together in 2001 in the paper "Random Forests", building on his earlier bagging method from 1996. Breiman's version combined bootstrap resampling with random feature selection at each split, and added out-of-bag error and variable importance. It caught on because it was accurate, needed almost no tuning, and was easy to parallelise, since trees are independent of one another.

Recap

A single deep Decision Tree has low bias but high variance. Bagging averages trees trained on bootstrap resamples, but strong features make those trees alike. A random forest also limits each split to a random feature subset, which lowers the correlation ρ\rho between trees and so the floor ρσ2\rho\sigma^2 on the forest's variance. Out-of-bag predictions give a free error estimate. From here, boosting builds trees one after another to reduce bias instead of variance.

Check yourself

QuestionWhat two sources of randomness does a random forest use, and what does each one add?Show answer

The first is the bootstrap resample: each tree trains on a sample drawn with replacement, so the trees see different data. The second is the random feature subset at each split: each split searches only a few features, so the trees differ in structure. Together they decorrelate the trees, which is what lets averaging reduce variance further than bagging alone.

QuestionA node has 8 examples: 4 of class A and 4 of class B. What is its Gini impurity, and what is the impurity of a pure node?Show answer

For the node, pA=pB=0.5p_A = p_B = 0.5, so G=0.5(0.5)+0.5(0.5)=0.5G = 0.5(0.5) + 0.5(0.5) = 0.5. A pure node has one class with p=1p = 1 and the other with p=0p = 0, so G=0G = 0. The impurity is largest when the classes are evenly mixed.

QuestionWhy does the variance of a forest of BB trees stop falling as BB grows, and what controls where it levels off?Show answer

The variance is σ2(ρ+(1−ρ)/B)\sigma^2(\rho + (1 - \rho)/B). As BB grows, the (1−ρ)/B(1 - \rho)/B term goes to zero, but ρσ2\rho\sigma^2 remains. The level it approaches is set by the correlation ρ\rho between trees. Making trees less correlated, for example by using a smaller feature subset at each split, lowers that floor.

QuestionA forest of 300 trees is trained. Roughly how many trees leave a given training example out, and how can that count be used?Show answer

About 300×0.368≈110300 \times 0.368 \approx 110 trees leave the example out of their bootstrap sample. Those trees form its out-of-bag prediction, which is an honest estimate of error. Averaging the out-of-bag errors over all examples gives a validation-style score without holding out a separate test set.

Sources

Random Forest — explained simply | ungoon.me