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?
- Training stays near 100% while validation rises, then levels off
- Validation rises, then falls as the forest overfits
- Both fall: averaging blurs everything
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
- 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\).
- The variance of a sum is the sum of all variances and covariances: \(B\sigma^2 + B(B-1)\rho\sigma^2\).
- Dividing the sum by \(B\) divides its variance by \(B^2\): \(\frac{\sigma^2}{B} + \frac{B-1}{B}\rho\sigma^2\).
- Rearranged, that's \(\rho\sigma^2 + \frac{1-\rho}{B}\sigma^2\). As \(B \to \infty\), only \(\rho\sigma^2\) is left.
- 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}\))
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…
- last: it carries no information
- 5th of 63, level with age
- first
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
- Size and speed. Hundreds of deep trees with thousands of leaves each: the default forest on the bank calls is 54 MB (18 MB with leaves of at least 5 calls), against 0.4 MB for boosted trees. Predicting means walking every tree. Limit
min_samples_leafandmax_depth, or use fewer trees, if it has to run on a phone or in a millisecond. - Past the data. An average of flat trees is flat: no forest can predict ridership above anything it saw (page 1). Model the trend separately, or predict the change.
- Correlated trees. When one column dominates (a leak, or one strong signal), every tree splits on it first and the average can't cancel their shared errors (the ρσ² floor). Feature subsampling helps; so does removing a leak.
- Second place. On most tables, carefully tuned gradient boosting (page 7) edges out a forest by a point or two; forests win on robustness and effort, not peak score.
- Importance. As measured above. Correlated columns also split their importance (euribor and the employment figure share credit), so a column can look unimportant only because its twin took the splits.
6. The knobs that matter
| Knob | In scikit-learn | What it does |
|---|---|---|
| Number of trees | n_estimators | More is never worse, only slower; the score plateaus (here by 50). Use 200 to 500 and stop worrying. |
| Columns per split | max_features | The main tuning knob: smaller decorrelates trees and regularizes each one; "sqrt" is the classification default, 1.0 means plain bagging. |
| Leaf size, depth | min_samples_leaf, max_depth | Deep by default (low bias). Bigger leaves make smaller, faster models with smoother probabilities. |
| Rows per tree | max_samples, bootstrap | Smaller samples: faster, more diverse trees. |
| Free validation | oob_score=True | An honest score without a holdout; handy when data is scarce. |
| Imbalance | class_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