45.08.05 · mathematical-statistics / 08-learning-methods

Bagging and Random Forests

shipped3 tiersLean: none

Anchor (Master): Hastie, Tibshirani & Friedman 2009 The Elements of Statistical Learning 2e §15.3-15.4 (variance of an average of correlated trees, variable importance, the random-forest kernel and proximities); Breiman 2001 Machine Learning 45 (the generalisation-error bound via strength and correlation); Scornet, Biau & Vert 2015 Annals of Statistics 43 (consistency of Breiman's random forests in the additive-regression model)

Intuition Beginner

A single decision tree is sharp but jumpy. Change a handful of training cases and the tree can redraw itself from the top down, giving quite different predictions. That jumpiness is the price trees pay for being so flexible. The idea behind bagging is simple: if one tree is noisy, grow many trees on slightly different versions of the data and average their answers. The average of many noisy guesses is steadier than any single guess, the same way the average of many thermometer readings is closer to the true temperature than one reading.

Where do the slightly different versions of the data come from? You make them by resampling. Take your training set and draw a new set of the same size by picking cases at random, with replacement, so some cases appear twice and some not at all. Each resample grows its own tree. This trick is called the bootstrap, and aggregating the trees grown on bootstrap samples is "bootstrap aggregating", shortened to bagging.

Random forests add one more twist. Plain bagged trees still look alike, because they are grown on almost the same data and tend to pick the same strong feature for the top split. Trees that agree do not help much when you average them. So a random forest hides most of the features from each split: at every split it lets the tree choose only from a small random handful of features. This forces different trees to use different features, makes them disagree more, and that disagreement is exactly what makes the average better.

The payoff is a method you can hand almost any table of data and get a strong prediction with little tuning. Forests rarely embarrass themselves, which is why they are a favourite first thing to try.

Visual Beginner

Picture the same training table copied many times, each copy reshuffled by drawing rows with replacement. Each copy grows one tree. To predict, you run a new case down every tree and average the answers.

Method What changes between trees How much trees agree What averaging buys
One tree nothing — there is one not applicable nothing; you live with its jumpiness
Bagging the bootstrap resample a lot (trees look alike) removes some jumpiness
Random forest resample plus random features per split less (trees disagree more) removes more jumpiness

Reading the table top to bottom: each step makes the trees more different from one another, and more different trees give a steadier average.

Worked example Beginner

We average three trees on a single new house and watch the variance shrink. Suppose the true price is 300 (thousand dollars). Each individual tree, over the randomness of its resample, predicts a value that scatters around 300 with a spread we summarise by a variance of 90.

First, the unhelpful case: three identical trees. If every tree always gives the same number, averaging three of them gives that same number, so the variance stays 90. Identical predictors teach us nothing new by averaging.

Now three trees that move together only partly. Say any two of them have a correlation of 0.5. The variance of the average of three such trees works out from the rule "variance of an average equals the correlated part plus the leftover part divided by how many you average". The correlated part is . The leftover part is , and dividing by 3 gives 15. So the average has variance .

Finally, three trees that barely move together, correlation 0.1. Correlated part ; leftover , divided by 3 is 27; total .

Lining them up: variance 90 for one tree (or many identical trees), 60 when trees correlate at 0.5, and 36 when they correlate at 0.1. What this tells us: averaging helps, and it helps far more when the trees disagree. Lowering the correlation from 0.5 to 0.1 cut the variance almost in half. That is the whole reason random forests scramble the features.

Check your understanding Beginner

Formal definition Intermediate+

Let have a joint law on with , and let be a training sample drawn i.i.d. from it. A base learner is a procedure returning a predictor; here the base learner is a CART regression or classification tree 45.08.04.

Bootstrap sample. A bootstrap sample is obtained by drawing indices uniformly with replacement from and collecting the corresponding cases. Equivalently, is governed by a multinomial count vector with and each . The probability that case is omitted from a single bootstrap sample is ; the omitted cases are the out-of-bag (OOB) cases for that sample.

Bagging. Draw bootstrap samples , fit a base tree to each, and aggregate. For regression the bagged predictor is the average

and for classification the aggregate is the plurality vote (or, when class-probability estimates are averaged, the of the averaged class proportions).

Random forest. A random forest replaces each bootstrap-fitted tree by a tree fitted with an extra source of randomness , an i.i.d. random vector independent across trees that, at every node, restricts the search for the best split to a random subset of of the predictors (the mtry parameter). Writing for the -th randomised tree (the resample is folded into ), the forest predictor is

Plain bagging is the special case . The default is commonly (regression) or (classification); controls a trade between individual tree strength (larger , more accurate single trees) and inter-tree correlation (smaller , more de-correlation).

Out-of-bag prediction and error. For each case , let be the bootstrap samples that omit it. The OOB prediction averages only those trees, , and the OOB error is the empirical risk of these predictions, , a nearly unbiased estimate of test error obtained without a separate validation set.

Variable importance. Two measures are standard. The Gini (split-improvement) importance of predictor sums, over all nodes that split on across all trees, the impurity reduction achieved there 45.08.04. The permutation importance of is the increase in OOB error when the values of are randomly permuted among the OOB cases, breaking the association between and while preserving its marginal distribution.

The notation here — for a base learner, for a bootstrap sample, for the tree-randomising vector, for the split-subset size, for inter-tree correlation — is recorded in _meta/NOTATION.md.

Counterexamples to common slips Intermediate+

  • "Bagging reduces bias as well as variance." The bagged predictor is an average of identically distributed trees, so its expectation equals the expectation of one tree: bagging leaves the bias of the base learner essentially unchanged and acts almost purely on the variance. (Random forests can slightly raise bias, because restricting splits to features makes each tree a little worse; the net effect is favourable because the correlation drops faster.) The method is therefore wasted on a low-variance, high-bias learner such as a linear model.

  • "More trees can overfit, so must be tuned like a complexity parameter." The forest predictor converges almost surely as (the trees are i.i.d. given the data), so adding trees only reduces Monte-Carlo noise in the average and never increases generalisation error; is a budget, not a regularisation knob. Complexity is controlled by tree depth and by , not by .

  • "OOB error needs a held-out set to be honest." Each OOB prediction for case uses only trees that never saw , so the OOB error is already an out-of-sample estimate; no separate validation split is required, and OOB error closely tracks -fold cross-validation error in practice.

Key theorem with proof Intermediate+

The central quantitative fact is the variance of an average of correlated trees. It explains in one line why bagging helps unstable learners, why a correlation floor caps the gain, and why random forests target that floor.

Theorem (variance of an average of correlated predictors). Let be identically distributed real predictions at a fixed point, each with variance and pairwise correlation for . Then the average has

In particular as , a floor set by the correlation alone. [Hastie 2009]

Proof. By bilinearity of covariance,

Each variance is , contributing . Each of the ordered off-diagonal covariances equals by the definition of correlation for identically distributed variables. Hence

where the last equality regroups . As the second term vanishes and .

Bridge. This identity is the foundational reason ensembling works and the precise design brief for random forests. The second term, , is the part averaging removes for free as grows — this is exactly what plain bagging exploits, since independent-looking resamples shrink it toward zero. The first term, , is a floor that no number of trees can lower; the only way past it is to lower , and that is the central insight behind random feature subsampling, which de-correlates the trees by forbidding them to all key on the same dominant predictor. The formula generalises the elementary variance of an average of independent draws — set and the floor disappears. It builds toward the strength-and-correlation generalisation bound of the Advanced results, where Breiman recasts and as a competition between keeping trees accurate and keeping them different, and it appears again in the consistency theory, where the same averaging that controls variance is what lets the forest's adaptive neighbourhoods concentrate on the regression function. Putting these together, the whole chapter's distinction between variance-reduction methods here and the bias-reduction method of boosting 45.08.06 is read straight off which term of an error decomposition each one moves.

Exercises Intermediate+

Advanced results Master

The variance identity sets the design target; the remaining theory makes the target operational, bounds the error in terms of it, and asks whether the forest estimate is consistent.

Theorem 1 (Breiman's strength-and-correlation bound). Model a random forest classifier as an ensemble with i.i.d. Define the margin , the strength , and the mean correlation of the raw margin functions between two independent trees. As the forest's generalisation error converges almost surely (so forests do not overfit in ), and, when ,

[Breiman 2001]. The bound is the classification analogue of the regression variance floor : error is small when trees are strong ( large) and weakly correlated ( small), and the random split-feature selection is precisely the mechanism that shrinks at a modest cost in .

Theorem 2 (almost-sure convergence in the number of trees). Because the trees are i.i.d. given the training data, for fixed the regression forest average converges almost surely to as by the strong law of large numbers, and the generalisation error converges to that of the infinite forest [Breiman 2001]. Consequently is not a complexity parameter: increasing it removes Monte-Carlo noise in the aggregate and cannot increase test error. Model complexity is carried by tree depth and by .

Theorem 3 (out-of-bag error is an internal validation estimate). Fix the loss . For each case the OOB prediction averages only the trees that omitted , each of which is fitted without , so estimates the risk of a forest trained on cases. As each almost surely (a fraction of trees), so the OOB prediction approaches the full infinite-subforest prediction restricted to omitting , and the OOB error tracks -fold cross-validation error without a separate split or refitting [Hastie 2009]. The same OOB machinery, with one feature permuted, yields the permutation importance.

Theorem 4 (the random-forest kernel and proximities). Define the forest proximity between two points as the fraction of trees in which they fall in the same leaf, . This is a positive-definite kernel, and the regression forest prediction is the kernel-weighted average with weights , the potential-nearest-neighbour weighting [Hastie 2009]. A random forest is thus an adaptive kernel method whose neighbourhoods are the data-driven leaf cells, the same local-averaging reading that casts a single tree as an adaptive nearest-neighbour rule 45.08.04; the proximity matrix doubles as a similarity measure for clustering, outlier detection, and missing-value imputation.

Theorem 5 (consistency of CART-split random forests). In the additive regression model with each continuous, uniform on , and centred with finite variance, Breiman's random forest — using genuine data-dependent CART splits and bootstrap resampling — is -consistent: with the number of terminal nodes and , the forest estimate satisfies [Scornet 2015]. This is the first consistency proof for the original algorithm rather than a stylised purely-random surrogate; earlier results (Biau 2012; Biau, Devroye and Lugosi 2008) established consistency for centred or purely-random forests whose splits ignore the response.

Synthesis. The foundational reason random forests cohere as a method is that one error decomposition is being driven in a single direction: the variance floor of the Key theorem is exactly the regression face of Breiman's strength-and-correlation bound , and the design of the algorithm — bootstrap resampling plus random split-feature selection — is the engineering that lowers (or ) while spending as little tree strength as possible. This is exactly why is a budget and not a regularisation knob: averaging i.i.d. trees can only remove the term, never the floor, and the strong law guarantees convergence rather than overfitting in . The central insight that unifies the diagnostics is local averaging: the proximity kernel reading shows a forest is an adaptive nearest-neighbour estimator whose weights are read off leaf co-occurrence, which is dual to the CART nearest-neighbour picture and generalises it by averaging over many randomised partitions; this is the bridge from the variance algebra to the consistency theory, since the Scornet-Biau-Vert theorem states that these adaptive neighbourhoods shrink while retaining enough points for the leaf-averages to converge to . Putting these together, the family is organised by which term of the bias-variance split 45.06.02 each method moves: forests spend their effort on variance, leaving bias near the base tree's, whereas boosting 45.08.06 grows stunted, high-bias trees and reduces bias sequentially — variance-reduction and bias-reduction as the two routes off one decomposition.

Full proof set Master

Proposition 1 (variance of an average of correlated predictors). For identically distributed with variance and pairwise correlation , .

Proof. As established in the Key theorem, since there are diagonal variance terms and ordered off-diagonal covariance terms each equal to . Dividing, .

Proposition 2 (idealised bagging never increases squared error; gain equals base variance). Let be a base prediction over the resampling distribution with mean , and let be a fixed target. Then , so the aggregate has squared error with gap .

Proof. Expand and substitute : . Non-negativity of variance gives , with equality iff , that is, iff the base learner is deterministic.

Proposition 3 (out-of-bag fraction). The probability that a fixed case is omitted from a single size- bootstrap sample is , which increases to as ; the expected number of distinct cases appearing is .

Proof. Each of the independent draws misses a fixed case with probability , so all draws miss it with probability . Writing as (the bracketed series is the expansion of , decreasing to in magnitude). The indicator that case appears has expectation ; summing over and using linearity gives the expected count .

Proposition 4 (almost-sure limit of the forest in ). For fixed and training data, with i.i.d. and , the forest average converges almost surely: as .

Proof. Conditionally on the training data, the summands are i.i.d. (functions of the i.i.d. ) with finite mean. Kolmogorov's strong law of large numbers gives almost surely over the sequence . The limit is the infinite-forest predictor at ; the generalisation error, a fixed functional of the predictor, converges to that of the infinite forest, so test error is non-increasing in up to Monte-Carlo fluctuation.

The strength-and-correlation bound (Theorem 1), the kernel/proximity structure (Theorem 4), and the additive-model consistency theorem (Theorem 5) are stated without reproduced proof — Theorem 1 is Theorem 2.3 of [Breiman 2001], Theorem 5 is the main theorem of [Scornet 2015], whose proof runs through empirical-process control of the CART splits and the additive-model approximation and exceeds the scope set here.

Connections Master

CART 45.08.04 is the base learner these methods average: the instability proved there — a fully grown tree is low-bias and high-variance because its partition is a discontinuous function of the data — is the exact regime in which the variance identity of this unit predicts a large payoff from averaging, so this unit consumes the object the tree unit builds, and the nearest-neighbour reading of a single tree extends here to the forest proximity kernel.

The bias-variance decomposition 45.06.02 is the ledger that organises the whole family: bagging and random forests are deliberate moves on the variance term, leaving the bias near that of the base tree, which is why they are wasted on a low-variance learner and why the floor — not — caps their benefit; the foundational reason the formula is a clean sum of a floor plus a shrinking term is the same bilinearity of covariance that underlies that unit's orthogonal split.

Boosting 45.08.06 is the complementary method on the same decomposition: where forests reduce variance by averaging strong, de-correlated trees, boosting reduces bias by sequentially reweighting deliberately shallow, high-bias trees, so the two units together exhibit variance-reduction versus bias-reduction as the two routes off the bias-variance split, and the contrast is the cleanest illustration in the chapter of why the decomposition is the organising principle.

The bootstrap and resampling methods of 26.08.01 supply the engine: the with-replacement resample that defines a bootstrap sample, the out-of-bag complement, and the omission fraction are the resampling theory of that unit applied to ensembling rather than to standard-error estimation, and the OOB error is the resampling estimate of risk specialised to the forest.

Historical & philosophical context Master

Bagging was introduced by Leo Breiman (1996) in Bagging Predictors [Breiman 1996], which framed bootstrap aggregation as a variance-reduction device and proved by a Jensen-type inequality that aggregation cannot increase squared error, with the gain governed by the instability of the base learner — making explicit that the method pays off for high-variance procedures such as CART and does little for stable ones. The bootstrap itself is due to Bradley Efron (1979), and Breiman's contribution was to repurpose it from inference about a statistic to the construction of a predictor. The random-subspace idea of restricting features was developed in parallel by Tin Kam Ho (1998) (the random subspace method) and by Yali Amit and Donald Geman (1997) (randomised trees for shape recognition).

The synthesis is Breiman (2001), Random Forests [Breiman 2001], which combined bootstrap resampling with random split-feature selection, proved the strong-law convergence in the number of trees and the strength-and-correlation generalisation bound, and introduced out-of-bag error, permutation importance, and proximities. The statistical-learning recasting in Hastie, Tibshirani and Friedman's Elements of Statistical Learning (2009) [Hastie 2009] placed the variance-of-correlated-average identity at the centre and presented the forest as an adaptive kernel method. Rigorous consistency long lagged the empirical success: results for stylised purely-random and centred forests (Biau, Devroye and Lugosi 2008; Biau 2012) preceded the consistency proof for Breiman's actual CART-split algorithm by Erwan Scornet, Gérard Biau and Jean-Philippe Vert (2015) [Scornet 2015] in the additive-regression model, closing part of the long gap between the method's practical dominance and its theoretical understanding.

Bibliography Master

@article{breiman1996bagging,
  author  = {Breiman, Leo},
  title   = {Bagging Predictors},
  journal = {Machine Learning},
  volume  = {24},
  number  = {2},
  pages   = {123--140},
  year    = {1996}
}

@article{breiman2001randomforests,
  author  = {Breiman, Leo},
  title   = {Random Forests},
  journal = {Machine Learning},
  volume  = {45},
  number  = {1},
  pages   = {5--32},
  year    = {2001}
}

@book{hastie2009esl,
  author    = {Hastie, Trevor and Tibshirani, Robert and Friedman, Jerome},
  title     = {The Elements of Statistical Learning: Data Mining, Inference, and Prediction},
  edition   = {2},
  publisher = {Springer},
  year      = {2009}
}

@article{scornet2015consistency,
  author  = {Scornet, Erwan and Biau, G\'erard and Vert, Jean-Philippe},
  title   = {Consistency of Random Forests},
  journal = {The Annals of Statistics},
  volume  = {43},
  number  = {4},
  pages   = {1716--1741},
  year    = {2015}
}

@article{efron1979bootstrap,
  author  = {Efron, Bradley},
  title   = {Bootstrap Methods: Another Look at the Jackknife},
  journal = {The Annals of Statistics},
  volume  = {7},
  number  = {1},
  pages   = {1--26},
  year    = {1979}
}

@inproceedings{ho1998randomsubspace,
  author    = {Ho, Tin Kam},
  title     = {The Random Subspace Method for Constructing Decision Forests},
  journal   = {IEEE Transactions on Pattern Analysis and Machine Intelligence},
  volume    = {20},
  number    = {8},
  pages     = {832--844},
  year      = {1998}
}

@article{amitgeman1997,
  author  = {Amit, Yali and Geman, Donald},
  title   = {Shape Quantization and Recognition with Randomized Trees},
  journal = {Neural Computation},
  volume  = {9},
  number  = {7},
  pages   = {1545--1588},
  year    = {1997}
}

@article{biau2012,
  author  = {Biau, G\'erard},
  title   = {Analysis of a Random Forests Model},
  journal = {Journal of Machine Learning Research},
  volume  = {13},
  pages   = {1063--1095},
  year    = {2012}
}