SafeZone AI Learn
Learn/ Machine Learning/ Supervised Learning · lesson 5 of 8

Decision trees and random forests

CART's greedy axis-aligned splits and why single trees are high-variance memorizers — then the two ideas, bagging and feature decorrelation, that turn a crowd of them into the most reliable default in tabular ML.

Everything so far drew smooth boundaries from global models. Trees are the opposite end of the design space: local, hierarchical, axis-aligned, zero smoothness — and the raw material of the two ensemble methods (forests here, boosting next lesson) that dominate tabular machine learning. The intellectual arc of this lesson is a bias–variance story with a twist: a single tree’s problem is variance, and the fix is not shrinkage but averaging.

CART: recursive greedy partitioning

A binary decision tree splits the input space with questions of the form xjtx_j \le t, recursively, until leaves are pure enough; a leaf predicts its majority class (or class frequencies). Growing the optimal tree is NP-hard, so CART is greedy: at each node, try every feature jj and every threshold tt (only midpoints between sorted data values matter — finitely many), and keep the split minimizing the children’s weighted impurity. For class proportions pkp_k:

Gini: G=1kpk2Entropy: H=kpklogpk\text{Gini: } G = 1 - \sum_k p_k^2 \qquad \text{Entropy: } H = -\sum_k p_k \log p_k

Both are maximal at 50/50 and zero when pure; they disagree rarely enough that the choice is a footnote. The split criterion for parent PP with children L,RL, R:

Δ=G(P)    nLnPG(L)    nRnPG(R)  >  0.\Delta = G(P) \;-\; \frac{n_L}{n_P} G(L) \;-\; \frac{n_R}{n_P} G(R) \;>\; 0 .

(Why not split directly on accuracy? Misclassification rate is piecewise-linear in pp — whole families of genuinely-progressing splits leave it unchanged, so the greedy search stalls. Gini/entropy are strictly concave, rewarding any purification. That detail is the difference between a criterion that works and one that plateaus.)

What this buys and costs, structurally:

  • Axis-aligned boxes. The boundary is a union of rectangles — staircases along diagonals (visible in the widget), but naturally expressive for rule-like, interaction-heavy tabular structure (the XOR that defeated every linear model is two splits for a tree).
  • Invariance to monotone feature transforms. Only the order of values matters: no standardization, logs, or scaling ever needed — a real reason trees are the low-friction tabular default.
  • Native handling of mixed types and (in serious implementations) missing values via surrogate splits.
  • Interpretability while small — a depth-3 tree is a readable flowchart; a depth-10 tree is not, and the forest that fixes the tree destroys the flowchart entirely. Interpretability was a property of the weak model.

The variance problem

An unpruned tree drives training error toward zero — with nn leaves available it can isolate every point. The bias–variance ledger reads: low bias, enormous variance. The hierarchy is the multiplier: change a handful of samples and the root split can flip, and every decision below inherits the change — the whole partition reorganizes. In the widget, refitting on a bootstrap resample redraws visibly different boxes at depth 8; that instability is the variance term from the regularization lesson, made visual. Classical pruning (grow, then cut back by cost-complexity α#leaves\alpha \cdot \#\text{leaves} — capacity control in the ridge spirit) trades some variance back for bias. The modern answer is better.

Bagging, and the correlation ceiling

Bootstrap aggregating (Breiman, 1996): draw BB bootstrap resamples, grow a deep tree on each, average their predictions (vote, or average probabilities). The arithmetic of averaging is the whole theory. For BB estimators of variance σ2\sigma^2 with pairwise correlation ρ\rho:

Var ⁣(1Bbf^b)=ρσ2+1ρBσ2.\operatorname{Var}\!\Big(\tfrac{1}{B}\textstyle\sum_b \hat f_b\Big) = \rho\,\sigma^2 + \frac{1-\rho}{B}\,\sigma^2 .

The second term dies as BB grows (more trees never hurt — no overfitting in BB, only diminishing returns), but the first does not: correlation between the trees is the floor. Bagged trees are correlated for an obvious reason — every resample still contains the same dominant features, so every tree opens with similar root splits and the “committee” is really one opinion echoed BB times.

Random forests attack ρ\rho directly: at every split, only a random subset of mm features (typically d\sqrt{d}) is even considered. Strong features are periodically benched, forcing trees to discover different structure; individual trees get slightly worse (σ2\sigma^2 up a little), but decorrelation (ρ\rho down a lot) wins the product. That is the entire trick — one line of code, aimed squarely at the first term of a variance formula. Two free by-products: out-of-bag evaluation (each tree never saw ~36.8% of the data — recall (11/n)ne1(1 - 1/n)^n \to e^{-1} — so honest validation comes without a held-out set) and permutation feature importance (shuffle a feature, watch OOB error move).

Single tree on moons: at depth 2–3, clean boxes (high bias — the staircase approximates the curve); at depth 8–10, shards that trace individual training points, train accuracy ~100%, test accuracy sagging — variance you can see. Switch to the forest at the same depth: the shards melt into a smooth-ish boundary and the probability shading gains soft gradations (averaged votes), with test accuracy typically beating any single depth setting. Sweep B from 1 → 60 and watch returns diminish exactly as the (1ρ)σ2/B(1-\rho)\sigma^2/B term predicts. On XOR, note depth 2 alone nails what defeated every linear model in this module.

Practical grammar of forests

KnobEffectDefault wisdom
BB (trees)variance ↓ toward the ρσ2\rho\sigma^2 floorhundreds; stop when OOB flattens
max depth / min leafper-tree bias–variancedeep for forests (bagging absorbs variance)
mm (features per split)the ρ\rho diald\sqrt d classification, d/3d/3 regression; tune if anything
class weightsimbalance handlingpairs with the evaluation lesson’s threshold story

Honest failure modes, because defaults breed complacency: forests cannot extrapolate (predictions are averages of training targets — beyond the data’s range they go flat, a real trap on trending time series); axis-alignment makes rotated boundaries expensive; very high-cardinality categoricals and impurity-based importances mislead (prefer permutation importance); and the smooth-probability look does not mean calibrated — forests are typically under-confident at the extremes (lesson 3’s isotonic fix applies).

from sklearn.ensemble import RandomForestClassifier

rf = RandomForestClassifier(
    n_estimators=400, max_features="sqrt", oob_score=True, n_jobs=-1
).fit(X_tr, y_tr)
print(rf.oob_score_)          # honest accuracy, no validation split spent

Exercises

Work these before the next lesson

  1. Show Gini and entropy are strictly concave in pp and misclassification rate min(p,1p)\min(p, 1-p) is not. Construct a concrete two-way split whose children are purer than the parent yet leave misclassification unchanged — the stalling example.
    Solution

    Worked solutions are part of Premiumunlock all of them for £5/month →

  2. 4 more exercises — each with a worked solution — are part of Premium. Unlock everything for £5/month →

References

  • L. Breiman, J. Friedman, R. Olshen, C. Stone, Classification and Regression Trees, 1984 — CART.
  • L. Breiman, “Bagging Predictors”, Machine Learning 1996.
  • L. Breiman, “Random Forests”, Machine Learning 2001 — the correlation analysis this lesson leans on.
  • ESL ch. 9 (trees) and ch. 15 (forests).
  • C. Strobl et al., “Bias in random forest variable importance measures”, BMC Bioinformatics 2007 — why permutation importance.