Unit 7, lesson 50

Bagging and Random Forests

How bagging averages trees fitted to bootstrap samples, how random forests add random feature subsets, why correlation between trees limits ensemble variance, and when out-of-bag error is honest evidence.

  • Video 50
  • Ensemble Methods

Refit a deep decision tree after changing a few training rows, and its splits and predictions can change a lot. Averaging many such trees should steady the prediction, but every one of them comes from the same training set, so how much can averaging help? This lesson builds bagged trees from bootstrap samples, adds the random choice of features that makes them a random forest, shows why the correlation between trees sets a floor under the variance of their average, and explains when the rows each tree never saw give an honest estimate of error.

Key terms

Bootstrap sample

Definition Let a training set hold nn rows. A bootstrap sample draws nn row indices I1,…,InI_1, \dots, I_n independently and uniformly from {1,…,n}\{1, \dots, n\}, that is, with replacement, and contains the rows with those indices, repeats included. The number of copies of row ii has a binomial distribution with nn trials and success probability 1/n1/n, so it averages 11, and the probability that row ii is missing from the sample is

(1−1n)n,\Bigl(1 - \frac{1}{n}\Bigr)^{n} ,

which increases with nn toward e−1≈0.368e^{-1} \approx 0.368. On average a sample therefore contains the fraction 1−(1−1/n)n1 - (1 - 1/n)^n of the distinct rows, about 0.6320.632 for large nn. These probabilities come from the index draws alone, whatever the rows contain. A bootstrap sample reuses the same data with random multiplicities and is not new data. In bagging it is part of how the model is trained, which is a different job from the bootstrap in Bootstrap Uncertainty and Model Comparisons, where resampling measures how much a statistic varies.

In plain words Draw rows from the training table one at a time, put each one back before the next draw, and stop after as many draws as the table has rows. Some rows come out twice or more, and on average about a third never come out at all.

Example The constructed data in this lesson have four rows with inputs x=1,2,3,4x = 1, 2, 3, 4 and targets y=2,4,8,10y = 2, 4, 8, 10 units. Writing each row by its input, three bootstrap samples are (1,1,2,4)(1, 1, 2, 4), (1,3,3,4)(1, 3, 3, 4) and (2,2,3,4)(2, 2, 3, 4). The first misses the row with x=3x = 3, the second misses the row with x=2x = 2 and the third misses the row with x=1x = 1, while the row with x=4x = 4 appears in all three. For n=4n = 4 a given row is missing from a sample with probability (3/4)4=81/256≈0.316(3/4)^4 = 81/256 \approx 0.316, and a sample contains on average 4(1−81/256)≈2.734(1 - 81/256) \approx 2.73 distinct rows. Each of these three samples happens to contain exactly 33.

Bagging

Definition Bagging, short for bootstrap aggregating, takes a learning procedure, a training set and a number B≥1B \ge 1 of models. It draws BB independent bootstrap samples, fits the procedure to each one, counting a repeated row as many times as it appears, and combines the fitted models f^1,…,f^B\hat{f}_1, \dots, \hat{f}_B. For regression the combination is the average

f^bag(x)=1B∑b=1Bf^b(x).\hat{f}_{\text{bag}}(\mathbf{x}) = \frac{1}{B} \sum_{b=1}^{B} \hat{f}_b(\mathbf{x}) .

For classification it is either a majority vote of the predicted classes, with a rule for ties, or an average of the estimated class probabilities followed by choosing the most probable class, and the two can disagree. In regression the BB fits have the same distribution, so their average has the same expected prediction as a single bootstrap fit and never a larger variance. Bagging works on variance, not on bias. It helps most for unstable procedures such as deep trees, whose fits change a lot when a few rows change, and it changes little for stable procedures.

In plain words Fit the same kind of model to many resampled versions of the training data and let them vote or average. Each fit overreacts to its own sample in its own way, and the average keeps the part of the pattern they share.

Example Fit a regression stump, a tree with one split chosen by squared error, to each sample above, with the rule that x≤tx \le t goes left. The first sample has targets 2,2,4,102, 2, 4, 10 and splits at 33, predicting 8/38/3 on the left and 1010 on the right. The second, with targets 2,8,8,102, 8, 8, 10, splits at 22 and predicts 22 and 26/326/3. The third, with targets 4,4,8,104, 4, 8, 10, splits at 2.52.5 and predicts 44 and 99. At the query x=2.5x = 2.5 the three stumps predict 8/38/3, 26/326/3 and 44, so

f^bag(2.5)=13(83+263+4)=469≈5.11.\begin{aligned} \hat{f}_{\text{bag}}(2.5) &= \frac{1}{3}\Bigl(\frac{8}{3} + \frac{26}{3} + 4\Bigr) \\[0.4em] &= \frac{46}{9} \approx 5.11 . \end{aligned}

One stump fitted to all four rows splits at 2.52.5 and predicts 33 there. On three constructed validation rows, x=1.5,2.5,3.5x = 1.5, 2.5, 3.5 with targets 3,6,93, 6, 9, the bagged predictions are 26/926/9, 46/946/9 and 83/983/9, a mean absolute error of 11/27≈0.4111/27 \approx 0.41, while the single stump predicts 3,3,93, 3, 9 with mean absolute error 11. The average has steps at 22, 2.52.5 and 33 instead of one large jump. Three validation rows show how averaging works here, not that an ensemble always beats one tree, and once they are used to choose between the two models they are no longer an untouched test. For classification, three trees that give a case the probabilities 0.90.9, 0.40.4 and 0.40.4 for class 11 vote 1,0,01, 0, 0, so the majority says class 00, while their average probability 17/30≈0.5717/30 \approx 0.57 says class 11.

Random forest

Definition A random forest is bagging applied to decision trees with one more source of randomness, random feature subsets. Each tree is fitted to its own bootstrap sample, and at every node, before the split search, a random subset of mtrym_{\text{try}} of the pp features is drawn without replacement, independently of all other nodes and trees. The best split is searched only among the features in that subset. The size mtrym_{\text{try}} is a hyperparameter with 1≤mtry≤p1 \le m_{\text{try}} \le p, and mtry=pm_{\text{try}} = p gives plain bagged trees. Common defaults are about p\sqrt{p} for classification, while libraries differ for regression, some using about p/3p/3 and some all pp features, so it is worth tuning on validation data. The trees are usually grown deep and left unpruned, and their predictions are combined as in bagging.

In plain words Bootstrap samples make the trees see different rows, and random feature subsets make them ask different questions. When one feature is much stronger than the rest, plain bagging tends to put it at the top of every tree, while a forest makes many trees look for structure in the other features too.

Example With p=4p = 4 features and mtry=2m_{\text{try}} = 2, each node draws one of (42)=6\binom{4}{2} = 6 possible subsets, and a given feature is available with probability 2/4=1/22/4 = 1/2. So at the root, on average half the trees cannot use even the strongest feature and must split on another one. In the four-row example there is only one feature, so every subset is that feature, and a random forest on those rows is the same as bagging. Feature randomization changes something only when mtry<pm_{\text{try}} < p.

Ensemble variance

Definition Fix an input x\mathbf{x}, and let T1,…,TBT_1, \dots, T_B be the predictions of BB trees at x\mathbf{x}, random through the training sample and through the random draws of the algorithm. Assume each TbT_b has variance σ2\sigma^2 and every pair of distinct trees has correlation ρ\rho. The variance of the average Tˉ\bar{T} is the sum of the BB variances σ2\sigma^2 and the B(B−1)B(B - 1) covariances ρσ2\rho\sigma^2, divided by B2B^2, which gives

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

These variances and covariances are possible only when ρ≥−1/(B−1)\rho \ge -1/(B - 1). If ρ>0\rho > 0, the variance falls as BB grows but never below the floor ρσ2\rho\sigma^2. If ρ=1\rho = 1, averaging does not help at all, and if ρ=0\rho = 0, the variance is σ2/B\sigma^2/B. This is a model with equal variances and equal correlations, a way to see what correlation does, and not a measured property of a fitted forest. Averaging identically distributed predictions does not change their mean, so whatever bias the trees have, the average keeps.

In plain words Averaging cancels the part of the trees’ errors that differs from tree to tree and keeps the part they share. Adding trees shrinks only the first part. Once there are many trees, the shared part is nearly all that is left, so making the trees less alike matters more than adding more of them.

Example With σ2=9\sigma^2 = 9 and ρ=0.2\rho = 0.2, one tree has variance 99. Ten trees give 9(0.2+0.8/10)=2.529(0.2 + 0.8/10) = 2.52, a hundred trees give 9(0.2+0.8/100)=1.8729(0.2 + 0.8/100) = 1.872, and no number of trees goes below 9⋅0.2=1.89 \cdot 0.2 = 1.8. Going from 1010 to 100100 trees removes only 0.6480.648, while lowering ρ\rho to 0.10.1 with the same σ2\sigma^2 and 100100 trees would give 9(0.1+0.9/100)=0.9819(0.1 + 0.9/100) = 0.981.

Correlation between trees

Definition For a fixed input x\mathbf{x} and two distinct trees b≠b′b \ne b' of an ensemble, with predictions TbT_b and Tb′T_{b'} at x\mathbf{x}, the correlation between trees is

ρ(x)=Corr⁡(Tb,Tb′),\rho(\mathbf{x}) = \operatorname{Corr}(T_b, T_{b'}) ,

taken over the randomness of the training sample and of the bootstrap and feature draws. It concerns the predictions of different trees at the same input, not the correlation between features. It is usually positive, because every tree is fitted to the same training set and strong features tend to win the same splits. A smaller mtrym_{\text{try}} usually lowers ρ(x)\rho(\mathbf{x}), but it can raise the variance σ2(x)\sigma^2(\mathbf{x}) and the bias of each tree, because the trees must often split on weaker features. Lower correlation therefore lowers the ensemble variance only when it is not outweighed by worse trees, and when most features are noise a small mtrym_{\text{try}} can hurt. Within one fitted forest the trees share the training set, so the spread of their predictions at one input shows only the variation that comes from the random draws, and it cannot reveal ρ(x)\rho(\mathbf{x}) by itself.

In plain words Trees that make the same mistakes cannot correct each other. Random feature subsets make the trees disagree more, and that helps the average only as long as each tree stays reasonably accurate.

Example Suppose, as an assumption for illustration, that forest A with mtry=pm_{\text{try}} = p has trees with σ2=4\sigma^2 = 4 and ρ=0.6\rho = 0.6, and forest B with a smaller mtrym_{\text{try}} has noisier trees with σ2=5\sigma^2 = 5 and ρ=0.3\rho = 0.3. With 500500 trees the formula gives 4(0.6+0.4/500)≈2.4034(0.6 + 0.4/500) \approx 2.403 for A and 5(0.3+0.7/500)=1.5075(0.3 + 0.7/500) = 1.507 for B, close to their floors 2.42.4 and 1.51.5. Forest B has the lower ensemble variance despite its worse trees. Whether it also has the lower prediction error depends on bias as well, which is why mtrym_{\text{try}} is chosen on validation data.

Out-of-bag error

Definition In a bagged ensemble or random forest with BB trees, row ii of the training set is out of bag for tree bb when it is missing from that tree’s bootstrap sample. Let OiO_i be the set of such trees. When OiO_i is not empty, the out-of-bag prediction for row ii combines only the trees in OiO_i, and the out-of-bag error is the average loss of these predictions over the rows that have one, reported together with how many rows that is. Because the samples are independent, a row has no out-of-bag prediction with probability (1−(1−1/n)n)B\bigl(1 - (1 - 1/n)^n\bigr)^B, which shrinks quickly as BB grows, and with many trees each out-of-bag prediction uses about 3737 percent of them. When the rows are independent draws from the population the model will serve, and no preprocessing step such as imputation or feature selection was fitted using all the rows, the out-of-bag error estimates the error on new rows without a separate validation set. It is not valid when rows come in related groups, such as several rows from one customer, since trees that saw the customer’s other rows predict the omitted one too easily, or when the rows are ordered in time and the model must predict the future. Once the out-of-bag error has been used to choose settings such as depth or mtrym_{\text{try}}, it is selection evidence and no longer an independent final test.

In plain words Each tree skips about a third of the rows, so every row can be predicted by the trees that never saw it, which works like a validation set built into the forest. It is honest only when skipping a row really hides that row’s information, and only until the score has been used to make choices.

Example In the four-row example the row with x=1x = 1 and y=2y = 2 is missing only from the third sample, whose stump predicts 44, an absolute error of 22. The row with x=2x = 2 and y=4y = 4 is predicted by the second stump as 22, an error of 22, and the row with x=3x = 3 and y=8y = 8 by the first stump as 8/38/3, an error of 16/316/3. The row with x=4x = 4 is in every sample and has no out-of-bag prediction, which happens to a given row with probability (175/256)3≈0.32(175/256)^3 \approx 0.32 when n=4n = 4 and B=3B = 3. The out-of-bag mean absolute error over the three covered rows is (2+2+16/3)/3=28/9≈3.11(2 + 2 + 16/3)/3 = 28/9 \approx 3.11. Each of these predictions comes from a single stump, so the figure describes something much weaker than the three-tree average.

Check yourself

  1. A forest of three trees is fitted to five training rows. Written by row number, the bootstrap samples are (1,1,2,4,5)(1, 1, 2, 4, 5), (2,3,3,4,5)(2, 3, 3, 4, 5) and (1,2,2,3,5)(1, 2, 2, 3, 5). Which trees can give each row an out-of-bag prediction? For samples of size 55, what is the probability that a given row is missing from one sample, and that it has no out-of-bag prediction with 33 trees and with 100100 trees?
Show the answer

Row 11 is missing only from the second sample, so only tree 22 can predict it out of bag. Row 33 is missing only from the first sample, so tree 11 predicts it, and row 44 is missing only from the third sample, so tree 33 predicts it. Rows 22 and 55 appear in all three samples and have no out-of-bag prediction. An out-of-bag error for this forest covers three of the five rows and should say so, rather than quietly filling in predictions from trees that trained on rows 22 and 55.

A given row is missing from one sample with probability (4/5)5=1024/3125≈0.328(4/5)^5 = 1024/3125 \approx 0.328. It is in a sample with probability about 0.6720.672, and the three samples are independent, so it has no out-of-bag prediction with probability about 0.6723≈0.3040.672^3 \approx 0.304. With 100100 trees that probability is about 0.672100≈6×10−180.672^{100} \approx 6 \times 10^{-18}, so in practice every row is covered.

  1. A regression data set has p=10p = 10 features, one strong and nine weak, and a random forest uses mtry=3m_{\text{try}} = 3. How likely is the strong feature to be available at a given node, and what does that change compared with mtry=10m_{\text{try}} = 10? Suppose that with mtry=10m_{\text{try}} = 10 the trees at some input have σ2=4\sigma^2 = 4 and ρ=0.8\rho = 0.8, and with mtry=3m_{\text{try}} = 3 they have σ2=5\sigma^2 = 5 and ρ=0.3\rho = 0.3. Compare the ensemble variances for 200200 trees. Does this prove that mtry=3m_{\text{try}} = 3 is better?
Show the answer

Each of the 1010 features is equally likely to be in the subset of 33, so the strong feature is available with probability 3/103/10. Counting subsets gives the same value, (92)/(103)=36/120\binom{9}{2}/\binom{10}{3} = 36/120. With mtry=10m_{\text{try}} = 10 every tree can split on the strong feature at the root and most will, so the trees look alike. With mtry=3m_{\text{try}} = 3 about 7070 percent of the trees must start with a weak feature, so the trees differ more, and each is somewhat worse.

Under the assumed values, the ensemble variances are

4(0.8+0.2200)=3.204,5(0.3+0.7200)=1.5175,\begin{aligned} 4\Bigl(0.8 + \frac{0.2}{200}\Bigr) &= 3.204 , \\[0.4em] 5\Bigl(0.3 + \frac{0.7}{200}\Bigr) &= 1.5175 , \end{aligned}

close to the floors 3.23.2 and 1.51.5. Adding trees cannot bring the first forest below 3.23.2, while lower correlation brings the second well under it.

This does not prove that mtry=3m_{\text{try}} = 3 is better. The values of σ2\sigma^2 and ρ\rho are assumptions, they describe one input, and prediction error also depends on bias, which can grow when the trees are forced onto weak features. The choice of mtrym_{\text{try}} is made with validation data, or with the out-of-bag error when the rows are independent, and the chosen forest is then assessed once on a test set.

  1. A hospital fits a random forest to 5,0005{,}000 visits from 800800 patients, with several visits per patient, to predict a lab value for new patients. The team tries 3030 combinations of depth and mtrym_{\text{try}}, keeps the one with the lowest out-of-bag error, and reports that error as the error to expect on new patients. What is wrong, and what is an honest plan?
Show the answer

There are two problems. First, the visits of one patient are related. When a visit is out of bag for a tree, that tree has usually trained on other visits of the same patient, so the out-of-bag prediction is easier than a prediction for a patient the forest has never seen, and the out-of-bag error is likely to be too optimistic. Second, the reported value is the smallest of 3030 out-of-bag errors and it made the choice of settings, so it tends to understate the chosen forest’s error even with independent rows. After tuning it is selection evidence, not a final test.

An honest plan splits by patient. Put all visits of a set of test patients aside. On the remaining patients, tune depth and mtrym_{\text{try}} with cross-validation in which every patient’s visits fall in a single fold, and fit any preprocessing inside each fold. Refit the chosen settings on all training patients and evaluate once on the test patients. If the model will be used later in time on new patients, the test patients should also come from a later period than the training data.

How this lesson connects