Skip to content
Lambdian

Bagging and random forests

Average many deep, decorrelated trees to keep their low bias and cancel their high variance.

Animated explanation

The idea

One deep decision tree is a nervous expert: brilliant on what it has seen, erratic on anything new. Ask a crowd of such experts, each trained on a slightly different version of the data, and average their answers. Their individual mistakes point in different directions and cancel; what they agree on is the real signal.

Bagging (bootstrap aggregating) creates the different versions by resampling rows with replacement. Random forests add one more twist: at each split a tree may only consider a random subset of features, so that one dominant feature does not make every tree look the same. Less correlated trees average out better.

Out-of-bag evaluation

Each bootstrap sample leaves out about 37% of the rows. For every row, average the predictions of only those trees that did not see it: the out-of-bag prediction. Its error is a nearly free estimate of test error, without a separate validation set.

Settings that matter

  • n_estimators: more trees never overfit; they only cost time. A few hundred is typical.
  • max_features: d\sqrt d for classification, d/3d/3 for regression; lower values decorrelate trees more.
  • min_samples_leaf / max_depth: usually left loose; deep trees are the point.

Random forests are famously robust "out of the box" and are often the strongest model on small and medium tabular datasets without any tuning.

Importance and limitations

Impurity-based importance is quick but favours high-cardinality features; permutation importance (shuffle one feature, measure the score drop) is more trustworthy. Forests cannot extrapolate beyond the target range seen in training, and they are larger and slower than a single tree or a linear model.

The algorithm, step by step

  1. 1
    For b=1,…,Bb = 1, \dots, B: draw a bootstrap sample of nn rows with replacement.
  2. 2
    Grow a deep tree on it; at each split consider only mm randomly chosen features.
  3. 3
    Predict by averaging the trees' class probabilities (or regression outputs).
  4. 4
    Estimate generalisation error from out-of-bag predictions.

The maths

Variance of an average of correlated trees

Var⁡(Tˉ)=ρσ2+1−ρBσ2\operatorname{Var}(\bar T) = \rho\sigma^2 + \frac{1-\rho}{B}\sigma^2

Out-of-bag fraction

(1−1n)n→e−1≈0.368\left(1-\tfrac1n\right)^n \to e^{-1} \approx 0.368

Forest prediction

p^(c∣x)=1B∑b=1Bp^b(c∣x)\hat p(c\mid\mathbf{x}) = \frac1B\sum_{b=1}^B \hat p_b(c\mid\mathbf{x})

Strengths and weaknesses

Strengths

  • Excellent accuracy with almost no tuning
  • Robust to noise, outliers and irrelevant features
  • Built-in OOB error and feature importance
  • Trivially parallel

Weaknesses

  • Less interpretable than one tree
  • Large models; slower prediction
  • Cannot extrapolate outside the training range

Reach for it when…

A strong default for tabular classification and regression, especially before investing in boosting.

Check your understanding

Question 1

Q1Why do random forests restrict the features considered at each split?

Question 2

Q2Adding more trees to a random forest…

Question 3

Q3What is out-of-bag error?

Lambdian Lab

Bagging trees by hand

Build a forest from scikit-learn's DecisionTreeClassifier, doing the bagging yourself.

  • bootstrap(n, rng) → (in_bag indices, out_of_bag boolean mask).
  • fit_forest(X, y, B, max_features, seed): B trees, each on a bootstrap sample with DecisionTreeClassifier(max_features=max_features, random_state=…); return (trees, oob_masks).
  • predict_forest(trees, X): majority vote (average of predict_proba, then argmax).
  • oob_accuracy(trees, oob_masks, X, y): accuracy of out-of-bag votes (rows never out of bag are skipped).
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.