Search

Search papers and lessons

Bagging

Level 3 · 10 min read

Bagging trains many copies of a model on random resamples of the training data and averages their predictions, which cuts variance without changing the model's average behaviour.

On this page

  • Colour = topic mix
  • Probability
  • Classical models
  • Learning basics
  • Losses & regularization
  • Discrete math
  • Sampling
  • Sign in to see your progress

TL;DR

Bagging, short for bootstrap aggregating, builds an ensemble by training the same kind of model many times, each time on a different random resample of the training set. The final prediction is the average of the individual predictions (or a majority vote for classification).

Averaging does not make any single model more accurate on average. What it does is shrink the part of the error that comes from each model reacting to the particular training sample it saw. That makes bagging most useful for flexible, unstable models such as deep decision trees.

Where you'll see it: in random forests, which are bagged decision trees with an extra trick, and in any setting where a single high-variance model gives good answers on average but jumps around from one training set to the next.

Intuition

Many noisy opinions

Suppose you want to estimate the length of a coastline and you give the job to ten people, each with a different ruler and each measuring a slightly different stretch of the shore. Each estimate is unreliable, but their errors point in different directions, so the average is usually much better than a typical single guess. Bagging applies the same logic to models. Each tree is an unreliable estimator, and their mistakes are partly independent, so the average is steadier.

The catch is that the trees must not all make the same mistakes. If every tree were trained on exactly the same data, they would agree, and averaging would change nothing. Bagging creates diversity by giving each tree a different slice of reality, which is what the bootstrap provides.

Why trees benefit most

A deep decision tree fits its training data almost perfectly. Change a handful of points and the splits near the top can move, which changes the predictions a lot. This is high variance. A straight-line model changes much less when the data changes, but it may miss a curve entirely, which is bias. Bagging is designed for the first problem. It leaves the bias of the tree roughly where it is and reduces the wobble. That is why bagging is paired with low-bias, high-variance learners and rarely helps a model that is already stable.

flowchart LR
  D["Training data (n points)"] --> S1["Bootstrap sample 1"]
  D --> S2["Bootstrap sample 2"]
  D --> S3["Bootstrap sample B"]
  S1 --> M1["Tree 1"]
  S2 --> M2["Tree 2"]
  S3 --> M3["Tree B"]
  M1 --> A["Average of predictions"]
  M2 --> A
  M3 --> A

The math

Bootstrap samples

Given a training set of nn points, a bootstrap sample is a new set of nn points drawn with replacement from the original. Each draw picks one of the nn original points, each with probability 1/n1/n, and every draw is independent. So a bootstrap sample has the same size as the original, but some points appear several times and others not at all. The resampling idea is covered in Bootstrap Sampling.

How many distinct original points should we expect in one bootstrap sample? A given point is missed by one draw with probability 1−1/n1 - 1/n. It is missed by all nn draws with probability

(1−1n)n⟶1e≈0.368as n→∞.\left(1 - \frac{1}{n}\right)^n \longrightarrow \frac{1}{e} \approx 0.368 \quad \text{as } n \to \infty.

So on average about 1−1/e≈63.2%1 - 1/e \approx 63.2\% of the original points appear in each bootstrap sample. The remaining roughly 36.8%36.8\% are "out of bag" for that sample, and they can be used as a free validation set for that model.

The bagged predictor

Let f^b(x)\hat{f}_b(x) be the prediction at input xx from the model trained on bootstrap sample bb, for b=1,…,Bb = 1, \dots, B. The bagged predictor is

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

For classification, the average is replaced by a majority vote over the predicted labels, or by averaging predicted class probabilities.

What averaging does to variance

Assume each model has the same variance σ2\sigma^2, and every pair of models has the same correlation ρ\rho in their predictions at xx. The variance of the average is

Var ⁣(1B∑b=1Bf^b)=1B2(Bσ2+B(B−1)ρσ2)=ρσ2+1−ρBσ2.\mathrm{Var}\!\left(\frac{1}{B}\sum_{b=1}^{B} \hat{f}_b\right) = \frac{1}{B^2}\left(B\sigma^2 + B(B-1)\rho\sigma^2\right) = \rho\sigma^2 + \frac{1-\rho}{B}\sigma^2.

Two things follow. First, the second term shrinks as 1/B1/B, so more models always help, with diminishing returns. Second, the first term ρσ2\rho\sigma^2 does not shrink with BB. It is the floor set by how correlated the models are. Bagging reduces variance only as far as the bootstrap samples decorrelate the models, and this is why random forests add an extra step to lower ρ\rho.

The expected error decomposes in the usual way, as in the Bias-Variance Tradeoff:

E[(y−f^bag(x))2]=noise+bias2+variancebag.\mathbb{E}[(y - \hat{f}_{\text{bag}}(x))^2] = \text{noise} + \text{bias}^2 + \text{variance}_{\text{bag}}.

Bagging leaves the bias term essentially unchanged, because the average of the models has about the same mean as each model. It shrinks the variance term.

102030405001234number of models Bvariance of the average
  • rho = 0.5, sigma^2 = 4
  • rho = 0.2, sigma^2 = 4
Variance of the bagged prediction as B grows. Both curves start at sigma^2 = 4 for a single model, then level off at rho sigma^2. Less correlated models reach a lower floor.

Worked examples

Example
How many points does a bootstrap sample keep?

Take a dataset of n=5n = 5 points, labelled 1 to 5.

  1. Draw five indices with replacement: 3,3,1,5,23, 3, 1, 5, 2.
  2. The distinct points are {1,2,3,5}\{1, 2, 3, 5\}. Point 4 is missing, so it is out of bag for this sample.
  3. Four of five points are present, which is 80%80\%. For n=5n = 5 the expected fraction is 67.2%67.2\% (see step 4), so this draw is a little above average by chance; with so few points the fraction is noisy.
  4. The chance a fixed point is missing is (1−1/5)5=0.328(1 - 1/5)^5 = 0.328 for n=5n = 5, so the expected fraction present is 0.6720.672. For n=1000n = 1000 the chance is (0.999)1000≈0.368(0.999)^{1000} \approx 0.368, and as nn grows the fraction present converges to 1−1/e≈0.6321 - 1/e \approx 0.632.
  5. Interpretation: each tree sees about two thirds of the data, and the rest can score it without a separate validation split.
Example
Variance reduction with ten trees

Each tree has variance σ2=4\sigma^2 = 4 at some input. Take B=10B = 10 trees.

  1. Case A, correlation ρ=0.5\rho = 0.5: ρσ2=0.5×4=2\rho\sigma^2 = 0.5 \times 4 = 2, and 1−ρBσ2=0.510×4=0.2\frac{1-\rho}{B}\sigma^2 = \frac{0.5}{10} \times 4 = 0.2. Total variance =2.2= 2.2.
  2. Case B, correlation ρ=0.2\rho = 0.2: ρσ2=0.8\rho\sigma^2 = 0.8, and 0.810×4=0.32\frac{0.8}{10} \times 4 = 0.32. Total variance =1.12= 1.12.
  3. A single tree has variance 44, so bagging cut the variance by almost half in case A and by almost three quarters in case B.
  4. Even with B=1000B = 1000 trees, case A cannot go below ρσ2=2\rho\sigma^2 = 2. Only lower correlation helps further.
  5. Interpretation: the number of trees is not the only lever. Decorrelating the trees matters as much.
Example
Five trees voting on one house price

Five bagged regression trees each predict the price of one house, in hundreds of thousands of dollars: 2.1, 3.4, 2.8, 2.5, 3.02.1,\ 3.4,\ 2.8,\ 2.5,\ 3.0.

  1. The bagged prediction is the mean: (2.1+3.4+2.8+2.5+3.0)/5=13.8/5=2.76(2.1 + 3.4 + 2.8 + 2.5 + 3.0)/5 = 13.8/5 = 2.76.
  2. Deviations from the mean: −0.66, 0.64, 0.04, −0.26, 0.24-0.66,\ 0.64,\ 0.04,\ -0.26,\ 0.24.
  3. Their average square is (0.4356+0.4096+0.0016+0.0676+0.0576)/5=0.9720/5=0.1944(0.4356 + 0.4096 + 0.0016 + 0.0676 + 0.0576)/5 = 0.9720/5 = 0.1944. This is the spread the average is averaging over, and the bagged prediction sits in the middle of it.
  4. Suppose the true price is 3.03.0. The bagged error is 0.240.24. The individual errors are 0.9, 0.4, 0.2, 0.5, 0.00.9,\ 0.4,\ 0.2,\ 0.5,\ 0.0, which average 2.0/5=0.42.0/5 = 0.4, so the bagged error is smaller than the typical single tree's, though one tree (the last) happened to be exact.
  5. Interpretation: the average smooths out individual trees, but if all five trees had been trained on data that systematically underpriced houses, the average would also be low. Bagging fixes instability, not a bad model.

Tradeoffs and failure modes

Bagging is a strong default for high-variance learners, and it is simple to parallelise because the models do not depend on each other. Its costs are a larger model and slower prediction, since each query runs BB models. It also loses some interpretability: one tree is readable, a hundred averaged trees are not.

SituationWhat goes wrongBetter choice
Stable, low-variance model such as linear regressionLittle variance to remove, so the gain is smallUse the model directly, or add L2 Regularization
Strongly correlated trees, for example one dominant featureThe variance floor ρσ2\rho\sigma^2 stays highRandom forests, which subsample features at each split
Very few training pointsBootstrap samples repeat points heavily and miss manyCross-validation with a careful split
Model with high bias, such as a shallow treeAveraging does not reduce the biasBoosting, which reduces bias step by step
Strong outliersEach sample that includes an outlier produces a distorted modelRobust losses or outlier removal before bagging

A common mistake is to bag a model that is already regularised heavily. Each copy is then nearly identical, the correlation ρ\rho is close to one, and the ensemble costs many times more compute for almost no gain.

History

The bootstrap itself was introduced by Bradley Efron in 1979 as a way to estimate the uncertainty of a statistic by resampling the data. Leo Breiman proposed bagging in a technical report in 1994 and published it in the journal Machine Learning in 1996. His argument was simple: averaging predictors built on bootstrap replicates lowers error for unstable methods, and the method needs no change to the underlying learner.

Breiman later combined bagging with random feature selection at each split and called the result a random forest, published in 2001. That combination became one of the most widely used general-purpose learners, and it remains the reference point for bagging today. Bagging also showed a broader pattern that later ensemble methods built on, which is that many modest models can beat one carefully tuned model when their errors are not too alike.

Check yourself

QuestionRecall: what does bagging average over, and why is it called bootstrap aggregating?Show answer

Bagging averages the predictions of many models, each trained on a bootstrap sample. The bootstrap is the random resampling with replacement that creates each training set, and aggregating means combining the predictions by averaging or voting.

QuestionComputation: with n=10000n = 10000 training points, about what fraction of the original points appear in a bootstrap sample, and what fraction are out of bag?Show answer

The chance a fixed point is missed by all draws is (1−1/10000)10000(1 - 1/10000)^{10000}, which is very close to 1/e≈0.36791/e \approx 0.3679. So about 63.2%63.2\% of the original points appear in each bootstrap sample, and about 36.8%36.8\% are out of bag. The out-of-bag points give a validation estimate for each tree without a separate held-out set.

QuestionWhy: why does bagging reduce variance but not bias, and why does it help a deep decision tree more than a linear regression?Show answer

Each model's prediction is an average over the same kind of learner, so the average has roughly the same mean as the individual models. That leaves bias unchanged. A deep tree's predictions swing a lot when the training sample changes, so averaging many of them removes much of that swing. A linear regression already changes little between samples, so there is little variance to remove.

QuestionApplied: you bag 200 trees and find the ensemble barely beats one tree. The trees are almost identical. What would you change, and why?Show answer

Identical trees mean the correlation ρ\rho is near one, so the variance floor ρσ2\rho\sigma^2 stays high no matter how many trees you add. Reduce the correlation: subsample features at each split as random forests do, or draw smaller samples (a smaller fraction of the rows) for each tree. Then recheck the out-of-bag error, since the extra trees will only help once they disagree with each other.

Sources