Notes
All notes

Deriving Random Forests (ML #7)

Your single decision tree scores 79% on the test set. The identical algorithm scores 81% on the same test set with a different random seed, and 77% with another. Nobody changed a line of code — the instability was always there, hidden behind one number that happened to look fine.

A random forest does not fix that by making each tree better. It makes each tree different, then averages. Those are completely different fixes, and the entire derivation of why forests work is about how much “different” is enough.

This chapter derives the variance of an ensemble’s average, shows that decorrelation — not tree count — is the whole game, and explains why forests inherit none of k-NN’s curse of dimensionality.

The setup: M predictors and their errors

Suppose you have \(M\) predictors \(f_1, \dots, f_M\) for the same target, each with individual error variance \(\sigma^2\) and pairwise correlation \(\rho\) (the average correlation of their errors across the dataset). The forest predicts the average:

\[ F_M(x) = \frac{1}{M}\sum_{m=1}^{M} f_m(x) \]

All of the ensemble’s magic is in \(\text{Var}[F_M]\), so compute it. Variance of a sum includes cross terms — this is the step everyone skips:

\[ \text{Var}\!\left[\sum_{m} f_m\right] = \sum_{m}\text{Var}[f_m] + \sum_{m \neq m'} \text{Cov}[f_m, f_{m'}] \]

Divide by \(M^2\). The first sum is \(M\sigma^2\); the second has \(M(M-1)\) ordered pairs, each with covariance \(\rho\sigma^2\):

\[ \text{Var}[F_M] = \frac{M\sigma^2 + M(M-1)\rho\sigma^2}{M^2} = \frac{\sigma^2}{M}\left(1 + (M-1)\rho\right) \]

This one equation is the whole theory. Read both limits.

\(\rho = 0\) (independent errors): the bracket is \(1\), giving \(\text{Var}[F_M] = \sigma^2/M\). Variance falls as \(1/M\) — 25 trees give a 25× reduction. This is the dream case.

\(\rho = 1\) (identical errors): the bracket is \(1 + (M-1) = M\), giving \(\text{Var}[F_M] = \sigma^2\). No reduction at all. A thousand perfectly correlated trees have exactly the variance of one.

So the achievable range for \(M = 25\) and unit individual variance is a 25× spread in noise:

correlation \(\rho\) \(\text{Var}[F_M]\) with \(M=25\) vs. single tree
0.0 0.040 25× better
0.1 0.136 7.4× better
0.3 0.328 3.0× better
0.5 0.520 1.9× better
1.0 1.000 no gain

This is why “more trees is always better” is wrong, and why the correlations in real forests are not small. Every tree in a forest sees the same underlying population, so their errors are structurally similar. Bagging attacks \(\rho\) by resampling rows; random feature subsets attack it again by resampling columns. Getting \(\rho\) from ~0.5 down to ~0.2 is what buys the real gain — which is exactly why max_features exists as a second decorrelation lever and why it is tuned at all.

Bias: what averaging does not fix

Compute the ensemble’s bias the same way:

\[ \mathbb{E}[F_M] = \frac{1}{M}\sum_m \mathbb{E}[f_m] = \mathbb{E}[f_1] \]

if the trees are exchangeable, which they are under bootstrap resampling. The bias of the average equals the bias of a single member. Averaging cannot fix bias, because it averages in the same wrong direction. This is the dividing line between the two ensemble families:

import numpy as np

def bootstrap_trees(X, y, n_trees=25, max_depth=None, seed=0):
    """Plain bagging: identical split rule, resampled rows only."""
    rng = np.random.default_rng(seed)
    trees = []
    for _ in range(n_trees):
        idx = rng.integers(0, len(X), len(X))      # with replacement
        trees.append(fit_tree(X[idx], y[idx], max_depth))
    return trees

def predict_mean(trees, X):
    """Ensemble prediction: the average of member predictions."""
    return np.mean([t.predict(X) for t in trees], axis=0)

Bagging lowers variance around a fixed bias. If your trees are systematically wrong — the signal is non-linear and the tree is too shallow to represent it — averaging cannot fix it, and the ensemble converges to the same error as its members. That is the diagnosis for “my forest didn’t help”: the members share a bias, so the mean does too.

OOB: free validation from the bootstrap

A bootstrap sample of \(n\) points drawn with replacement contains each point with probability \(1/n\) per draw. The expected number of omitted points is \(n\left(1 - \frac{1}{n}\right)^n\), and the limit as \(n \to \infty\) gives:

\[ \Pr[\text{a given point is omitted}] = \left(1 - \frac{1}{n}\right)^n \;\longrightarrow\; e^{-1} \approx 0.368 \]

So roughly 36.8% of your training data is not in each bootstrap sample — and which 36.8% is essentially random per tree. Each tree therefore has a natural held-out set. Assemble the out-of-bag prediction for each observation from the ~36.8% of trees that never saw it:

\[ \widehat{\text{err}}_{\text{OOB}} = \frac{1}{n}\sum_{i=1}^{n} \mathbb{1}\left[ F_{-i}(x_i) \neq y_i \right] \]

where \(F_{-i}\) averages only the trees for which \(x_i\) was out-of-bag. This is a genuine validation estimate at zero extra compute and zero extra data, and it is why forests can be tuned and monitored without a validation split. It is not a full substitute for a test set — it is optimistic when the model is tuned repeatedly against it — but it is the fastest honest signal available during development.

def oob_error(trees, X, y, seed=0):
    """Each point is predicted by only the trees that never saw it."""
    rng = np.random.default_rng(seed)
    n = len(X)
    in_bag = np.zeros((len(trees), n), dtype=bool)
    for t, tree in enumerate(trees):
        idx = tree.bootstrap_idx
        in_bag[t, np.unique(idx)] = True

    correct, counted = 0, 0
    for i in range(n):
        oob = ~in_bag[:, i]                      # trees that missed point i
        if oob.sum() == 0:                       # point was in every bag
            continue
        pred = np.mean([trees[j].predict(X[i:i+1]) for j in np.where(oob)[0]])
        correct += int((pred > 0.5) == y[i]); counted += 1
    return 1 - correct / counted                  # skips the ~e^-1 in-all-bags points

The curse of dimensionality does not apply

Chapter 5 showed k-NN collapsing toward chance as dimensions grew, because distance sums over all features so noise dimensions dilute the signal. A forest sidesteps this completely, and the reason is structural: a split looks at one feature at a time.

A node’s candidate splits are of the form \(x_j \le t\) for a single \(j\). Choosing among them requires comparing only the \(d\) 1-D projections, not a \(d\)-dimensional distance. If feature \(d\) is pure noise, its best possible split contributes an information gain of worse than random, and it simply never wins the \(\arg\max\). There is no mechanism by which noise features dilute the useful ones, because they are never summed together.

This is why forests handle thousands of features — including one-hot encoded categoricals — without complaint, and why they need no standardization (a threshold on a variable is invariant to any monotone rescaling of it; a Euclidean distance is not). It is the single most practically useful structural difference between the two algorithms.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.3cm, minimum height=0.7cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (d) at (0,1.9) {high-$d$ data};
  \draw[a] (d) -- node[above, font=\rmfamily\scriptsize] {sum over all dims} (-2.9,0.3);
  \draw[a] (d) -- node[above, font=\rmfamily\scriptsize] {compare 1-D splits} (2.9,0.3);
  \node[b, fill=orange!16] (knn) at (-2.9,-0.9) {k-NN\\noise dilutes\\accuracy $\to$ chance};
  \node[b, fill=green!12] (tree) at (2.9,-0.9) {tree\\noise features never win\\an $\arg\max$};
  \node[font=\rmfamily\scriptsize, text=black!60] at (0,-2.3) {same data, opposite vulnerability: it is the aggregation that differs};
\end{tikzpicture}

How many features per split

max_features is the second decorrelation dial, and its common default has a derivation-flavored justification. Consider the extremes. Looking at all \(p\) features at each node finds the globally best split at every node — minimum bias, but every tree becomes nearly identical, so \(\rho \to 1\) and the ensemble degenerates to a single tree. Looking at one feature per node makes each tree wildly different (\(\rho\) low) but each split is poor, so bias climbs.

The variance-optimal balance sits between them, and \(\sqrt{p}\) is the standard choice: enough features that the best of the sample is usually the genuinely good one, few enough that the trees diverge. It is a heuristic, not a theorem, which is why the practical advice is still to tune it. Classification defaults to \(\sqrt{p}\); regression to \(p/3\) or \(p\), since regression splits have more room to be informative.

Feature importance and its trap

Two standard measures, both flawed in instructive ways. Mean decrease in impurity (MDI) sums the weighted impurity drops across all splits using a feature. It is biased toward features with many distinct values — a continuous feature offers hundreds of candidate thresholds, so it collects more chances to show a gain. The fix: mean decrease in accuracy (MDA) permutes one feature at a time and measures the accuracy loss, which is scale-free but noisy and depends on the training set.

The honest summary is that both are diagnostics, neither is causal, and neither should be reported without noting the bias. Permutation importance computed on held-out data is the least bad option. If you need actual attributions, say so and use a different tool.

Pitfalls

QQuestionSelf-check

Derive \(\text{Var}[F_M] = \frac{\sigma^2}{M}(1+(M-1)\rho)\) from the variance-of-a-sum identity. Your forest gained almost nothing going from 10 to 200 trees while training accuracy stayed at 100% — what does the variance formula predict about \(\rho\), and what would you change? Why is standardization unnecessary for a tree but essential for k-NN?

ASolution

Applying \(\text{Var}[\sum f_m] = \sum\text{Var}[f_m] + \sum_{m\neq m'}\text{Cov}[f_m, f_{m'}]\) to \(F_M = \frac1M\sum f_m\) gives \(\frac{M\sigma^2 + M(M-1)\rho\sigma^2}{M^2} = \frac{\sigma^2}{M}(1+(M-1)\rho)\): \(M\) variance terms plus \(M(M-1)\) ordered covariance pairs, each \(\rho\sigma^2\). The near-zero gain from 10 to 200 trees means \(\rho\) is close to 1 — the trees are nearly identical, so the bracket \(\approx M\) cancels the \(1/M\) and variance stays at \(\sigma^2\). The cause is that every tree sees the same data and every split is driven by the same strong feature; the fix is to decorrelate harder — smaller max_features, more aggressive bootstrap diversity, or more data per node so trees stop memorizing row IDs. Standardization is irrelevant to trees because a split is the predicate \(x_j \le t\), which a monotone rescaling of \(x_j\) leaves unchanged; it is essential for k-NN because the squared Euclidean distance sums raw per-feature contributions, so a feature in dollars dominates one in years by orders of magnitude.

Next: Deriving Gradient Boosting (ML #8) — fitting residuals stage by stage, and why the leaf value falls out of a second-order Taylor expansion.