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.
- 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 of them would divide variance by ; 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.
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 , 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 , a bootstrap sample is formed by drawing points with replacement from . Because sampling is with replacement, 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 substitutes for the unknown true distribution.
Bagging applies the bootstrap to model averaging rather than to estimating a statistic's sampling variance. Draw bootstrap samples , fit the base learner (e.g., an unpruned decision tree) on each to get , and combine them: average the outputs for regression, or take a majority vote for classification. The combined predictor
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 training runs — each one is completely independent, which is what makes bagging trivially parallelizable.
Step 1 — Resample. For each , draw indices uniformly at random with replacement from , forming .
Step 2 — Fit. Train the base learner (unchanged, no modification to its algorithm) on to obtain .
Step 3 — Track out-of-bag points. Record which original training points did not appear in — these are the out-of-bag (OOB) points for tree , and they will later serve as a free validation set for that tree.
Step 4 — Aggregate. For a new input : average across all (regression) or take the plurality vote of the 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 is not a bias-inducing hyperparameter in the way tree depth is: increasing never increases variance of the ensemble (it decreases it, subject to diminishing returns) and does not cause overfitting in the classical sense, so is typically set as large as computational budget allows, then checked for a plateau in OOB error. Second, sampling with replacement from items into a sample of size 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.
Complexity & correctness
Time complexity. If the base learner takes time to train on examples (e.g., for a decision tree with features, using presorted feature splitting), then training the full bagging ensemble costs
This is embarrassingly parallel: the fits share no state, so with processors the wall-clock time is . Prediction for a single query costs , where is the base learner's per-query cost (e.g., for a tree) — again trivially parallelizable, and in practice a constant-factor overhead compared to a single model.
Space complexity. Storing the ensemble requires where is one model's size; for trees this is proportional to the number of leaves, typically in the worst case for fully grown trees, so 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 be i.i.d. (approximately, since bootstrap samples overlap but let's first idealize as independent) predictors, each with variance at a fixed point , and pairwise correlation between any two of them (induced by sharing the same original dataset ). The variance of their average is
With each term and for , and such cross terms:
As , this converges to — not zero. This is the central honest fact about bagging: variance reduction saturates. If the base models were perfectly independent (), variance would shrink like , vanishing as grows. But bootstrap samples are drawn from the same underlying dataset , so inevitably — the models are correlated because they share overlapping data. Bagging's benefit is exactly of the naive reduction; the residual floor 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 further.)
Bias is (almost) unchanged. Since and expectation is linear,
for any single (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 -sized dataset, since each resample is itself a sample of size 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 unique points. The probability a specific point is never chosen in draws with replacement from items is
So each bootstrap sample contains, in expectation, about of the distinct original points (with repeats making up the rest to size ), and about 36.8% of points are held out — exactly the pool used for the OOB estimate. This convergence is fast: even at , , 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: 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 with , and training points. We fit single-split regression stumps (extremely shallow, unstable trees) at and bag of them, tracking bootstrap composition explicitly. Original indices: with -values .
| Bootstrap sample | Indices drawn (with replacement) | Unique indices used | OOB indices (never drawn) |
|---|---|---|---|
| 1 | 1,1,3,4,6,6,7,8 | {1,3,4,6,7,8} | {2,5} |
| 2 | 2,2,2,4,5,7,7,8 | {2,4,5,7,8} | {1,3,6} |
| 3 | 1,3,3,5,5,6,7,8 | {1,3,5,6,7,8} | {2,4} |
| 4 | 2,3,4,4,5,6,8,8 | {2,3,4,5,6,8} | {1,7} |
| 5 | 1,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 out of unique points — , higher than the asymptotic because is small (finite-sample effect: , so expected unique fraction is , 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 , none of which were trained using point 2. Now suppose each stump's predicted value at query (near the middle of the range) comes out as:
| Model | Trained on sample | Prediction at |
|---|---|---|
| 0.42 | ||
| 0.61 | ||
| 0.35 | ||
| 0.58 | ||
| 0.49 |
A single stump (say alone) would report — but a fresh bootstrap draw could easily have produced 's or 's : that spread (roughly to ) is the variance we are trying to tame. The bagged prediction is the mean:
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 ( rather than ). With only correlated trees the reduction is modest; growing into the hundreds (as done in practice) pushes this down toward the correlation floor .
Common pitfalls & traps
| Pitfall | Why it happens | Fix |
|---|---|---|
| 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 noise | Reserve bagging for high-variance, low-bias learners (deep trees, unpruned models) |
| Treating like a tunable hyperparameter that can overfit | Confusing with model complexity like tree depth; more bootstrap replicates never increases variance | Set large (limited by compute); monitor OOB error for a plateau, not a U-shape |
| Ignoring correlation between trees | Assuming bootstrap samples are independent draws from the true distribution, when they in fact all derive from the same fixed | Understand the variance floor ; use Random Forest-style feature randomization to lower if more reduction is needed |
| Using OOB error and a separate validation set redundantly | Not realizing OOB error already approximates held-out performance at near-zero extra cost | Use 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 classification | Hard-voting discards confidence information each tree carries | Prefer soft voting (average predicted probabilities) when the base learner outputs calibrated scores |
| Forgetting duplicate points inflate leaf purity / effective sample size illusions | With-replacement sampling means "n examples" are really fewer unique points, hidden in metrics computed naively on | Be explicit that bootstrap sample size does not mean independent observations |
Pioneers & history
Origins · 1 minLeo Breiman and how this was discovered
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.
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 in the variance formula), pushing the variance floor 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, is not really a bias-variance dial — increasing 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 as large as your compute budget allows, then check the OOB error curve as a function of : 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 ) 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 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 , 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.