AI from scratch · Model zoo 6 of 10 · Random forests

Random forests

Page 5 ended with a problem: a deep tree fits its sample so closely that a slightly different sample gives a different tree. A random forest turns that weakness into the method. Grow hundreds of deep trees, each on a different random sample and with random columns at each split, so each is wrong in its own way, then average them. It's the model you can throw at almost any table with default settings and get a good answer, which is why it was the workhorse of tabular ML for fifteen years.

1. The idea in one picture: trees pile up, the noise cancels

Each tree here is deep and grown on its own bootstrap sample (200 dots drawn with replacement). With one tree the map is a jagged patchwork. Add trees: the map is their average, and the islands that only one tree believed in fade, while the shape most trees agree on stays.

Slide the trees from 1 to 100. Predict first: what happens to training accuracy, and to validation accuracy?

Every tree fits its own sample closely, so their average still fits the training dots. On new dots, the errors that differ from tree to tree cancel, so validation improves, quickly at first, then hardly at all. More trees never hurt the score; they only cost time and memory. On the bank calls: one tree AUC 0.74, 10 trees 0.77, 50 trees 0.785, 300 trees 0.782.

A random forest averages many deep trees, each grown on a random sample with random columns, so their separate mistakes cancel while what they agree on remains.

2. How it learns: bagging plus random columns

Bagging (bootstrap aggregating): for each tree, draw n rows with replacement from the n training rows (each tree sees about 63% of the distinct rows, some twice), grow it deep, and average the trees' predicted probabilities. The forest adds one more source of randomness: at each split, a tree may only choose among a random subset of the columns (about \(\sqrt{p}\) of \(p\) for classification). Why bother? Because averaging only cancels the part of the errors that differs between trees:

\[ \operatorname{Var}\Big(\frac{1}{B}\sum_{b=1}^{B} T_b\Big) = \rho\,\sigma^2 + \frac{1-\rho}{B}\,\sigma^2 \]

Here \(\sigma^2\) is one tree's variance and \(\rho\) the correlation between two trees. More trees (\(B\)) shrink the second term to nothing, but the first stays: if every tree starts with the same strong column, they make the same mistakes, and no number of them averages that away. Slide \(\rho\):

Why the average's variance has that floor
  1. Take \(B\) trees' predictions at one point, \(T_1, \dots, T_B\), each with variance \(\sigma^2\) (from which sample it got) and each pair with correlation \(\rho\), so covariance \(\rho\sigma^2\).
  2. The variance of a sum is the sum of all variances and covariances: \(B\sigma^2 + B(B-1)\rho\sigma^2\).
  3. Dividing the sum by \(B\) divides its variance by \(B^2\): \(\frac{\sigma^2}{B} + \frac{B-1}{B}\rho\sigma^2\).
  4. Rearranged, that's \(\rho\sigma^2 + \frac{1-\rho}{B}\sigma^2\). As \(B \to \infty\), only \(\rho\sigma^2\) is left.
  5. So two levers: more trees (cheap, kills the second term) and less correlated trees (random rows, random columns), which lowers the floor, as long as each tree doesn't get much worse. The bias, meanwhile, is one tree's bias: averaging doesn't fix a systematic error, which is why forests use deep, low-bias trees.

3. Out-of-bag: a validation score for free

Each tree never saw about 37% of the rows (the chance a row is never drawn in n tries is \((1 - 1/n)^n \approx 1/e \approx 0.37\)). Score every row with only the trees that didn't train on it, and you get an honest estimate without holding out any data: the out-of-bag (OOB) score. On the bank calls, the OOB AUC was 0.793 and the test AUC 0.782.

A tree draws 1,000 rows with replacement from 1,000. What share of the rows does it never draw? (\((1 - 1/1000)^{1000}\))

\((0.999)^{1000} \approx 0.368\), very close to \(1/e\). So about 63% of the distinct rows are in each bootstrap sample, some of them several times.

4. Build it: bagging from scratch, next to scikit-learn

5. Where it shines, where it breaks

Shines: strong with no tuning (the defaults are fine on most tables), hard to overfit by adding trees, no scaling, any mix of columns, an honest score built in (OOB), and trees train in parallel on every core. On digits it gets 96.7%, on the bank calls AUC 0.78, both within a point or two of the best model in the zoo.

Add a column of pure random numbers to the bank calls. The forest's built-in importance (how much each column's splits lowered impurity) ranks it…

Measured: 5th, with the same importance as age (0.072). A random number has a distinct value in every row, so it offers thousands of cut points, and deep trees use them to split tiny boxes by luck; each such split lowers training impurity a little, and it adds up. Permutation importance on test data (shuffle a column, see how much the AUC drops) puts it 23rd, with a drop of 0.0004, near nothing. For explaining a forest, use permutation importance on held-out data.

Forests are strong, stable and nearly tuning-free; they're big and slow to predict, can't extrapolate, and their built-in importance flatters columns with many values.

Where it breaks, and what people do

6. The knobs that matter

KnobIn scikit-learnWhat it does
Number of treesn_estimatorsMore is never worse, only slower; the score plateaus (here by 50). Use 200 to 500 and stop worrying.
Columns per splitmax_featuresThe main tuning knob: smaller decorrelates trees and regularizes each one; "sqrt" is the classification default, 1.0 means plain bagging.
Leaf size, depthmin_samples_leaf, max_depthDeep by default (low bias). Bigger leaves make smaller, faster models with smoother probabilities.
Rows per treemax_samples, bootstrapSmaller samples: faster, more diverse trees.
Free validationoob_score=TrueAn honest score without a holdout; handy when data is scarce.
Imbalanceclass_weight="balanced_subsample"Reweights the classes within each bootstrap sample.

Next in the zoo: trees again, but grown one after another, each fixing what the last ones got wrong.

All chapters: AI from scratch. Bank marketing: Moro, Cortez and Rita (2014), UCI Machine Learning Repository, CC BY 4.0.

Last updated