Bagging and the Bootstrap

Imagine training a single decision tree on a dataset of patient records to predict disease risk. Change one data point, and the tree can flip entirely. A different root split cascades into a completely different structure. This is the hallmark of an unstable learner: small perturbations in training data cause large swings in the fitted model. Doctors relying on such a model would rightly distrust it. Its predictions depend as much on sampling noise as on real signal. Bagging — short for bootstrap aggregating — offers a remarkably simple fix. Instead of training one model, train many. Each is trained on a slightly different resampled version of the data. Then average their predictions. The averaging cancels out the idiosyncratic noise each model picked up from its particular resample. It preserves the signal they all agree on. This single idea was introduced by Leo Breiman in 1996. It converts high-variance, low-bias learners into far more reliable predictors. No change to the base learning algorithm itself is needed. The technique matters far beyond decision trees. It underlies Random Forests, and appears inside gradient boosting variants. It is a standard tool whenever a learner is powerful enough to overfit. It must not be so constrained that it can't adapt to new resamples. It also connects two ideas normally taught separately. One is the bootstrap, a resampling technique from classical statistics. It estimates the sampling distribution of an estimator. The other is the bias-variance decomposition, which explains exactly why averaging helps. This article builds bagging from first principles. It covers how the bootstrap resample is constructed, and why averaging reduces variance without inflating bias. It also covers the precise complexity of training and predicting with an ensemble. Finally, it covers specific failure modes that trip up practitioners. These range from bagging already-stable learners to misreading out-of-bag error. By the end, you should be able to derive the variance-reduction formula yourself, not just recite it.

Key takeaways
  • Bagging trains many copies of a base learner on bootstrap resamples (samples drawn with replacement) and averages their predictions.
  • It targets learners with low bias, high variance (e.g., deep decision trees); averaging reduces variance while leaving bias essentially unchanged.
  • Each bootstrap sample includes about 63.2% of unique original points, leaving roughly 36.8% "out-of-bag" for free validation.
  • If the base models' errors were fully independent, averaging BB of them would divide variance by BB; in practice positive correlation between trees limits the gain.
  • Out-of-bag (OOB) error gives an almost-free, nearly unbiased estimate of test error, no separate validation split required.
  • Bagging is the direct ancestor of Random Forests (which decorrelates trees further) and a building block for Stacking and Model Blending.
The core insight

Bagging reduces the variance of an unstable learner by averaging predictions from many models trained on independent bootstrap resamples of the same data.

The idea

A learning algorithm is unstable if small changes to the training set produce large changes in the fitted function — full decision trees, nearest-neighbor classifiers with small kk, and neural networks trained near interpolation are classic examples. Instability is exactly high variance in the The Bias–Variance Tradeoff sense: across many hypothetical training sets drawn from the same distribution, the fitted models disagree wildly with each other even though each is roughly unbiased. The bootstrap is a resampling procedure, introduced by Bradley Efron in 1979, for approximating the sampling distribution of a statistic without knowing the true underlying distribution. Given a dataset D={(x1,y1),…,(xn,yn)}D = \{(x_1, y_1), \dots, (x_n, y_n)\}, a bootstrap sample D∗D^{*} is formed by drawing nn points with replacement from DD. Because sampling is with replacement, D∗D^* typically contains duplicates of some original points and omits others entirely. Repeating this many times generates many "pseudo-datasets," each a plausible stand-in for what a fresh sample from the true distribution might look like — the empirical distribution of DD substitutes for the unknown true distribution.

Bagging applies the bootstrap to model averaging rather than to estimating a statistic's sampling variance. Draw BB bootstrap samples D1∗,…,DB∗D_1^*, \dots, D_B^*, fit the base learner (e.g., an unpruned decision tree) on each to get f^1,…,f^B\hat f_1, \dots, \hat f_B, and combine them: average the outputs for regression, or take a majority vote for classification. The combined predictor

f^bag(x)=1B∑b=1Bf^b(x)\hat f_{\text{bag}}(x) = \frac{1}{B}\sum_{b=1}^{B} \hat f_b(x)

is what gets deployed. Crucially, bagging changes nothing about the base learning algorithm — it is a meta-algorithm (an ensemble method) that wraps around any base learner, and it is most useful precisely when that base learner is unstable and roughly unbiased.

How it works

The mechanism has two independent phases: generating the bootstrap ensemble, then aggregating predictions. There is no coordination between the BB training runs — each one is completely independent, which is what makes bagging trivially parallelizable.

Step 1 — Resample. For each b=1,…,Bb = 1, \dots, B, draw nn indices uniformly at random with replacement from {1,…,n}\{1, \dots, n\}, forming Db∗D_b^*.

Step 2 — Fit. Train the base learner (unchanged, no modification to its algorithm) on Db∗D_b^* to obtain f^b\hat f_b.

Step 3 — Track out-of-bag points. Record which original training points did not appear in Db∗D_b^* — these are the out-of-bag (OOB) points for tree bb, and they will later serve as a free validation set for that tree.

Step 4 — Aggregate. For a new input xx: average f^b(x)\hat f_b(x) across all bb (regression) or take the plurality vote of the BB predicted classes (classification); soft-voting by averaging predicted class probabilities is a common, often better-calibrated, alternative. ``` function BAGGING-TRAIN(D, B, BaseLearner):

# D: training set of n examples (x_i, y_i) n = size(D) models = [] oob_membership = array of size B, each an empty set # indices left out per model for b = 1 to B: sample_indices = [] for i = 1 to n: j = uniform_random_integer(1, n) # draw WITH replacement sample_indices.append(j) D_b_star = { D[j] for j in sample_indices } f_b = BaseLearner.fit(D_b_star) models.append(f_b) in_bag = set(sample_indices) oob_membership[b] = { i in 1..n : i not in in_bag } return models, oob_membership

function BAGGING-PREDICT(models, x, task): predictions = [ f_b(x) for f_b in models ] if task == "regression": return mean(predictions) else: # classification return majority_vote(predictions)

function OOB-ERROR(D, models, oob_membership):

# Estimate test error without a held-out set total_error = 0 counted = 0 for i = 1 to n: voters = [ f_b for b in 1..B if i in oob_membership[b] ] if voters is empty: continue # rare for small n or small B pred_i = aggregate(voters, D[i].x) # average or vote, using ONLY trees

# that never saw point i total_error += loss(pred_i, D[i].y) counted += 1 return total_error / counted ``` Two implementation details matter. First, the number of trees BB is not a bias-inducing hyperparameter in the way tree depth is: increasing BB never increases variance of the ensemble (it decreases it, subject to diminishing returns) and does not cause overfitting in the classical sense, so BB is typically set as large as computational budget allows, then checked for a plateau in OOB error. Second, sampling with replacement from nn items into a sample of size nn is standard, but variants exist (e.g., subsampling without replacement, "pasting") — the with-replacement choice is specifically what makes the 63.2% figure below hold and what enables the OOB estimate.

Figure
Bagging pipeline: resample, fit independently, aggregate
Training set D n examples (x₁,y₁)…(xₙ,yₙ) D₁* (resample, with replacement) D₂* (≈63.2% unique) ⋮ D_B* (resample B) f̂₁ deep tree f̂₂ deep tree ⋮ f̂_B deep tree Aggregate mean (regression) / vote (classification) f̂_bag(x) low variance Out-of-Bag (OOB) evaluation Point (xᵢ,yᵢ) is absent from D_b* for roughly 36.8% of trees b (since P(absent) → e⁻¹ ≈ 0.368). Those trees never saw xᵢ during training — averaging only their predictions on xᵢ gives an almost-unbiased estimate of test error, without holding out any data separately. OOB error ≈ error of an independent test set of comparable size.

Complexity & correctness

Time complexity. If the base learner takes T(n)T(n) time to train on nn examples (e.g., T(n)=O(nlog⁡n⋅d)T(n) = O(n \log n \cdot d) for a decision tree with dd features, using presorted feature splitting), then training the full bagging ensemble costs

O ⁣(B⋅T(n)).O\!\big(B \cdot T(n)\big).

This is embarrassingly parallel: the BB fits share no state, so with PP processors the wall-clock time is O(B⋅T(n)/P)O(B \cdot T(n) / P). Prediction for a single query costs O(B⋅Tpredict)O(B \cdot T_{\text{predict}}), where TpredictT_{\text{predict}} is the base learner's per-query cost (e.g., O(depth)O(\text{depth}) for a tree) — again trivially parallelizable, and in practice a constant-factor overhead compared to a single model.

Space complexity. Storing the ensemble requires O(B⋅S(n))O(B \cdot S(n)) where S(n)S(n) is one model's size; for trees this is proportional to the number of leaves, typically O(n)O(n) in the worst case for fully grown trees, so O(Bn)O(Bn) total. This is the real cost of bagging: you trade memory and inference-time compute for variance reduction.

Why averaging reduces variance — the derivation. Let f^1,…,f^B\hat f_1, \dots, \hat f_B be i.i.d. (approximately, since bootstrap samples overlap but let's first idealize as independent) predictors, each with variance σ2\sigma^2 at a fixed point xx, and pairwise correlation ρ\rho between any two of them (induced by sharing the same original dataset DD). The variance of their average is

Var ⁣(1B∑b=1Bf^b(x))=1B2(∑bVar(f^b(x))+∑b≠b′Cov(f^b(x),f^b′(x))).\text{Var}\!\left(\frac{1}{B}\sum_{b=1}^{B} \hat f_b(x)\right) = \frac{1}{B^2}\left(\sum_b \text{Var}(\hat f_b(x)) + \sum_{b \neq b'} \text{Cov}(\hat f_b(x), \hat f_{b'}(x))\right).

With each term Var(f^b(x))=σ2\text{Var}(\hat f_b(x)) = \sigma^2 and Cov(f^b,f^b′)=ρσ2\text{Cov}(\hat f_b, \hat f_{b'}) = \rho \sigma^2 for b≠b′b \ne b', and B(B−1)B(B-1) such cross terms:

Var(f^bag(x))=Bσ2+B(B−1)ρσ2B2=ρσ2+1−ρBσ2.\text{Var}(\hat f_{\text{bag}}(x)) = \frac{B\sigma^2 + B(B-1)\rho\sigma^2}{B^2} = \rho \sigma^2 + \frac{1-\rho}{B}\sigma^2.

As B→∞B \to \infty, this converges to ρσ2\rho \sigma^2 — not zero. This is the central honest fact about bagging: variance reduction saturates. If the base models were perfectly independent (ρ=0\rho = 0), variance would shrink like σ2/B\sigma^2/B, vanishing as BB grows. But bootstrap samples are drawn from the same underlying dataset DD, so ρ>0\rho > 0 inevitably — the models are correlated because they share overlapping data. Bagging's benefit is exactly (1−ρ)(1-\rho) of the naive 1/B1/B reduction; the residual floor ρσ2\rho\sigma^2 is the irreducible cost of shared training data. (This is precisely the gap that Random Forests attack directly, by injecting extra randomness — random feature subsets at each split — specifically to lower ρ\rho further.)

Bias is (almost) unchanged. Since f^bag(x)=1B∑bf^b(x)\hat f_{\text{bag}}(x) = \frac{1}{B}\sum_b \hat f_b(x) and expectation is linear,

E[f^bag(x)]=E[f^b(x)]\mathbb{E}[\hat f_{\text{bag}}(x)] = \mathbb{E}[\hat f_b(x)]

for any single bb (by the identical-distribution assumption over bootstrap draws). So the bias of the ensemble equals the bias of a single base model trained on a bootstrap resample, which is close to (though not exactly) the bias of a model trained on the original nn-sized dataset, since each resample is itself a sample of size nn from the empirical distribution. Bagging therefore leaves bias essentially untouched while attacking variance — it helps most when the base learner already has low bias (is flexible enough to fit the true signal) but high variance (is unstable). Applying bagging to a high-bias, low-variance learner (e.g., linear regression with few features) yields little benefit, since there is little variance left to remove and the averaging cannot fix systematic bias.

Why ≈63.2%\approx 63.2\% unique points. The probability a specific point ii is never chosen in nn draws with replacement from nn items is

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

So each bootstrap sample contains, in expectation, about 1−e−1≈63.2%1 - e^{-1} \approx 63.2\% of the distinct original points (with repeats making up the rest to size nn), and about 36.8% of points are held out — exactly the pool used for the OOB estimate. This convergence is fast: even at n=20n=20, (1−1/20)20≈0.358(1-1/20)^{20} \approx 0.358, already close to the limit.

Honest tradeoffs.

  • Bagging trades interpretability for stability: a single decision tree can be visualized and explained; an ensemble of hundreds cannot.
  • It trades compute and memory for accuracy: B×B\times the training time and storage.
  • It does not help stable, high-bias learners; it can occasionally hurt them slightly due to added noise from resampling.
  • It does not remove bias, so if the base learner underfits, bagging will not fix that — only variance shrinks.

Worked example

Consider a toy 1-D regression problem: true function y=sin⁡(x)+εy = \sin(x) + \varepsilon with ε∼N(0,0.32)\varepsilon \sim \mathcal{N}(0, 0.3^2), and n=8n = 8 training points. We fit single-split regression stumps (extremely shallow, unstable trees) at x=2x = 2 and bag B=5B = 5 of them, tracking bootstrap composition explicitly. Original indices: 1,2,3,4,5,6,7,81,2,3,4,5,6,7,8 with xx-values 0.5,1.0,1.8,2.3,3.1,4.0,4.8,5.50.5, 1.0, 1.8, 2.3, 3.1, 4.0, 4.8, 5.5.

Bootstrap sample bbIndices drawn (with replacement)Unique indices usedOOB indices (never drawn)
11,1,3,4,6,6,7,8{1,3,4,6,7,8}{2,5}
22,2,2,4,5,7,7,8{2,4,5,7,8}{1,3,6}
31,3,3,5,5,6,7,8{1,3,5,6,7,8}{2,4}
42,3,4,4,5,6,8,8{2,3,4,5,6,8}{1,7}
51,2,4,5,6,6,7,7{1,2,4,5,6,7}{3,8}

Two things to notice immediately, both consequences of the math above. First, each sample retains 66 out of 88 unique points — 75%75\%, higher than the asymptotic 63.2%63.2\% because n=8n=8 is small (finite-sample effect: (1−1/8)8≈0.343(1-1/8)^8 \approx 0.343, so expected unique fraction is 1−0.343≈65.7%1-0.343 \approx 65.7\%, and our small sample of 5 draws shows natural variation around that). Second, every index is OOB for at least one of the five models — for instance, point 2 is OOB in samples 1, 3, and 4, so its OOB prediction averages exactly those three trees' outputs on x=1.0x=1.0, none of which were trained using point 2. Now suppose each stump's predicted value at query x=2.5x=2.5 (near the middle of the range) comes out as:

ModelTrained on samplePrediction at x=2.5x=2.5
f^1\hat f_1D1∗D_1^*0.42
f^2\hat f_2D2∗D_2^*0.61
f^3\hat f_3D3∗D_3^*0.35
f^4\hat f_4D4∗D_4^*0.58
f^5\hat f_5D5∗D_5^*0.49

A single stump (say f^1\hat f_1 alone) would report 0.420.42 — but a fresh bootstrap draw could easily have produced f^3\hat f_3's 0.350.35 or f^2\hat f_2's 0.610.61: that spread (roughly 0.350.35 to 0.610.61) is the variance we are trying to tame. The bagged prediction is the mean:

f^bag(2.5)=0.42+0.61+0.35+0.58+0.495=2.455=0.49.\hat f_{\text{bag}}(2.5) = \frac{0.42+0.61+0.35+0.58+0.49}{5} = \frac{2.45}{5} = 0.49.

This value sits centrally among the five stumps' predictions, and — critically — the variance of this averaged estimate across hypothetical resamples of the whole procedure is smaller than the variance of any single stump's prediction, precisely by the factor derived above (ρ+(1−ρ)/B\rho + (1-\rho)/B rather than 11). With only B=5B=5 correlated trees the reduction is modest; growing BB into the hundreds (as done in practice) pushes this down toward the correlation floor ρσ2\rho\sigma^2.

Common pitfalls & traps

PitfallWhy it happensFix
Bagging a stable, low-variance learner (e.g., plain linear regression)Little variance exists to reduce; gains are negligible, sometimes slightly negative due to resampling noiseReserve bagging for high-variance, low-bias learners (deep trees, unpruned models)
Treating BB like a tunable hyperparameter that can overfitConfusing BB with model complexity like tree depth; more bootstrap replicates never increases varianceSet BB large (limited by compute); monitor OOB error for a plateau, not a U-shape
Ignoring correlation ρ\rho between treesAssuming bootstrap samples are independent draws from the true distribution, when they in fact all derive from the same fixed DDUnderstand the variance floor ρσ2\rho\sigma^2; use Random Forest-style feature randomization to lower ρ\rho if more reduction is needed
Using OOB error and a separate validation set redundantlyNot realizing OOB error already approximates held-out performance at near-zero extra costUse OOB error as the primary internal estimate when data is scarce; reserve a true test set only for final reporting
Averaging class labels instead of class probabilities in classificationHard-voting discards confidence information each tree carriesPrefer soft voting (average predicted probabilities) when the base learner outputs calibrated scores
Forgetting duplicate points inflate leaf purity / effective sample size illusionsWith-replacement sampling means "n examples" are really fewer unique points, hidden in metrics computed naively on Db∗D_b^*Be explicit that bootstrap sample size nn does not mean nn independent observations

Pioneers & history

Origins · 1 minLeo Breiman and how this was discovered
LB
Leo Breiman
1928–2005 · Berkeley statistician who founded bagging, random forests, and CART

Leo Breiman spent an unusual career split between industry consulting and academia before returning to statistics full-time at Berkeley, where he became one of the field's most consequential applied theorists. He co-authored the CART (Classification and Regression Trees) methodology in 1984, which gave the field its modern decision-tree formalism, and then spent the 1990s asking a sharper question: if trees are so unstable, can instability itself be turned into an asset through resampling and averaging? His 1996 paper "Bagging Predictors" answered yes, and his 2001 "Random Forests" paper pushed the idea further by decorrelating the trees deliberately. Breiman's empirical, algorithm-first style — test on real data, prove what you can, be honest about what you can't — shaped how the ML community thinks about ensembles to this day.

History
1979
— Bradley Efron introduces the bootstrap for estimating sampling distributions of statistics.
1984
— Breiman, Friedman, Olshen, and Stone publish CART, formalizing recursive partitioning trees.
1994
— Efron and Tibshirani publish "An Introduction to the Bootstrap," cementing the method's statistical foundations.
1996
— Breiman publishes "Bagging Predictors," introducing bootstrap aggregating for variance reduction.
2001
— Breiman publishes "Random Forests," extending bagging with feature-subsampling to decorrelate trees further.

Where this matters

Bagging is rarely used in its pure textbook form as "bag many unpruned trees" in production today — it has largely been superseded by Random Forests, which is bagging plus deliberate decorrelation via random feature subsets at each split, giving a strictly better variance-reduction floor. But the bagging principle itself — resample, refit, average — is embedded throughout modern machine learning infrastructure:

  • Random Forests (scikit-learn's `RandomForestClassifier`/`Regressor`, R's `randomForest`, Spark MLlib) directly generalize bagging and remain a default baseline for tabular data in industry, from credit scoring to genomics.
  • Bagged ensembles for uncertainty estimation: the spread of bootstrap models' predictions is used as a practical (if imperfect) proxy for predictive uncertainty, in fields from ecology to epidemiology.
  • Statistical inference via the bootstrap (the resampling half of this article, without the aggregation) underlies confidence interval estimation across nearly every applied statistics package, independent of machine learning.
  • Bagging as a building block for <a class="wiki-link" href="/wiki/cs-ml-stacking" data-track="wiki_article.body.wiki_link">Stacking and Model Blending</a>: many stacked ensembles use bagged base learners as one "family" of predictors feeding into a meta-learner, since bagging supplies diverse, low-correlation predictions cheaply.
  • Distributed computing frameworks exploit bagging's embarrassingly-parallel structure directly — each bootstrap fit is an independent map task, with aggregation as a cheap reduce, making it a natural fit for Spark, Dask, and multi-GPU training pipelines.
  • Kaggle-style competition pipelines routinely bag identical model architectures with different random seeds/resamples purely to squeeze out variance reduction on the leaderboard, even outside formal Random Forest implementations.

Ask the tutor: How does adding random feature selection at each split (as in Random Forests) provably lower the correlation ρ between bagged trees, and how much further does variance actually drop in practice?

Is bagging the same thing as a Random Forest?

No. Bagging is the general recipe: resample with replacement, fit a base learner on each resample, average. A Random Forest applies bagging specifically to decision trees, with one extra ingredient — at each split, only a random subset of features is considered, rather than all features. That extra randomization further decorrelates the trees (lowers ρ\rho in the variance formula), pushing the variance floor ρσ2\rho\sigma^2 even lower than plain bagging achieves. Random Forests are bagging plus feature-level decorrelation; bagging is the more general, learner-agnostic ensemble technique that Random Forests specialize.

Does bagging ever make predictions worse than a single model?

It can, though usually only mildly, and mainly for already-stable base learners. If the base learner has very low variance to begin with (e.g., a simple linear model on a small, well-conditioned feature set), bootstrap resampling introduces sampling noise (duplicated/omitted points) without a variance benefit to offset it, so ensemble performance can be marginally worse or simply flat. Bagging also cannot fix underfitting: if the base learner's bias is the dominant error source, no amount of averaging removes that systematic component, so an underpowered base learner stays underpowered.

How many bootstrap models B should I use?

Unlike tree depth or regularization strength, BB is not really a bias-variance dial — increasing BB monotonically (weakly) decreases the ensemble's variance and never increases overfitting risk in the classical sense, because averaging more i.i.d.-ish estimators cannot make the average worse in expectation. Practically, choose BB as large as your compute budget allows, then check the OOB error curve as a function of BB: it decreases and then plateaus, and once it plateaus, additional trees mostly cost compute without meaningfully improving accuracy. Values of a few hundred are common defaults in practice.

Why does sampling "with replacement" matter — why not just split the data into B disjoint chunks?

Splitting into disjoint chunks (each of size n/Bn/B) would shrink each base learner's effective training set, increasing its individual bias and variance, and would also destroy the specific 63.2%/36.8% structure that makes the out-of-bag estimate work. Sampling with replacement lets every bootstrap sample have the same size nn as the original dataset, so each base learner is trained on "as much data as the original" (statistically), while still differing enough between resamples to be decorrelated. The replacement mechanism is precisely what creates a natural, automatically-tracked held-out subset (the never-drawn points) for each model.

Can bagging be applied to models other than decision trees?

Yes — bagging is a wrapper around any base learner, though its benefit scales with how unstable that learner is. It has been applied to neural networks (bagged ensembles of networks trained with different bootstrap samples and/or random initializations), k-nearest-neighbor classifiers with small kk, and even to feature-selection procedures (bagging the selection step to stabilize which features get chosen). It offers little benefit for learners that are already low-variance, such as heavily regularized linear models or naive Bayes classifiers with strong priors.

How does bagging relate to boosting?

They sit at opposite ends of the bias-variance spectrum of ensemble strategies. Bagging trains base learners independently and in parallel on resampled data specifically to reduce variance, and works best with already-low-bias, high-variance base learners (deep trees). Boosting trains base learners sequentially, each one focused on the previous ensemble's errors, specifically to reduce bias, and typically uses high-bias, low-variance base learners (shallow stumps) as building blocks. Bagging cannot easily correct underfitting; boosting is designed to attack it directly, at some risk of increased variance if run too long.

What's the connection between bagging and the classical statistical bootstrap?

The classical bootstrap (Efron, 1979) was designed to estimate the sampling distribution, standard error, or confidence interval of a statistic — e.g., "how much would the sample mean vary across repeated experiments?" — by resampling the observed data instead of relying on parametric assumptions. Bagging repurposes exactly this resampling mechanism, but instead of estimating a statistic's variability, it uses the resamples to train an ensemble of predictive models and average their outputs. The underlying justification is identical: the empirical distribution of the observed data is treated as a proxy for the true, unknown data-generating distribution, and drawing "new datasets" from it approximates drawing new datasets from reality.

Before this

Where this leads