Bagging: average bootstrap fits, then check who was left out
Bagging
Compute exact bootstrap stump averages and OOB coverage, separating conditional resampling noise from uncertainty across training sets.
baggingA different training sample, a different answer
A regression stump makes one split. Move a few training records and its chosen split may move with them. Bagging asks whether an average of these different fits is more useful than committing to one fit.
Start with a training set of n records. Draw n record indices independently and uniformly with replacement, fit a base learner to the selected records, and repeat. One record can appear several times in a bag; another can be absent. Repeated records retain their multiplicity during training. At prediction time, regression averages the fitted outputs. Classification can take a plurality vote, with an explicit tie rule. Averaging class probabilities is another aggregation rule and can disagree with hard voting: positive-class probabilities 0.51, 0.51 and 0.01 give two positive votes but a mean below 0.5.
The name combines “bootstrap” and “aggregating.” Breiman’s September 1994 technical report describes both numerical averaging and class voting, and connects their usefulness to changes in the fitted predictor when the training data change. That is a reason to investigate an unstable learner, not a promise that every averaged learner improves. Breiman, Bagging Predictors, Technical Report 421
Our original example has just three records: (0, 0), (1, 1) and (2, 4). A stump fitted to all three predicts 1/2, 1/2 and 4 at their feature values. A bag containing only the first record predicts zero everywhere. A bag containing only the last predicts four everywhere. The ensemble has to account for both, including their probabilities.
Separate the sources of randomness
The chapters on bootstrap resampling and bias and variance supply the statistical background. Let D be the original training set, U a bootstrap index sequence, and f(x; D, U) the fitted output at a fixed query x. With B bags, the regression prediction is
For B at least two, suppose these real-valued predictions have the same finite positive variance v and every distinct pair has covariance rho times v, under a specified probability experiment. Expanding the variance of a sum gives
There are B variance terms and B(B−1) ordered covariance terms. Independent predictions make the covariance terms zero; identical random predictions have rho equal to one and receive no variance reduction. If v is zero, the variance is already zero and this correlation parameter is undefined.
“Bootstrap bags overlap, so the fitted predictions cannot be independent” misses a conditioning distinction. For a fixed D, independently drawn index sequences passed through a deterministic training procedure produce conditionally independent predictions. Shared records are fixed values in that experiment. If D itself is redrawn, however, all learners still share the same random training set. Write m(D) for the conditional mean prediction. Conditional independence and the law of total variance give
This identity assumes finite second moments and independent, identically distributed bag draws given D. If the base learner is randomized, include its random choices in U and make them independent across fits given D. More bags reduce the Monte Carlo variation around m(D). They do not remove m(D)‘s variation across original training sets. Nor does this identity compare the ensemble’s bias or test error with the learner trained once on all of D. A reduction in real-valued prediction variance alone is not a theorem about classification accuracy.
What an absent record can tell us
A record is out of bag (OOB) for a particular learner when its original index never appears in that learner’s draw. For size-n bags, its exclusion probability and, for B independent random bags, its probability of receiving no OOB prediction are
The first formula follows because each of the n independent draws must avoid the index. The second requires every bag to include it at least once. As n grows, q approaches the reciprocal of e; for n=1 it is zero. For n=3 it is exactly 8/27. These are properties of the sampling procedure, not assurances of good validation data.
Let B_i contain the learners for which record i is OOB, and C contain the records with at least one such learner. The example reports
An uncovered record gets None, not a zero prediction. When C is empty, MSE is also None. We report coverage alongside MSE so that an error calculated for a small covered subset cannot masquerade as an error for all records. Each covered record uses a different subset of learners. Its OOB prediction is neither the full ensemble prediction nor necessarily the prediction of a single leave-one-out fit. The official bagging API likewise warns that a small ensemble can leave some OOB predictions unavailable; its regression prediction averages base predictions. scikit-learn 1.7.2: BaggingRegressor
Enumerate the bags instead of relying on a lucky seed
The code uses integers and Fraction values, so ties and reported errors are exact. Each stump considers a constant and the midpoints between consecutive distinct in-bag feature values. It minimizes in-bag squared error. A constant wins a tie with a split; otherwise the smaller threshold wins. The left leaf includes the threshold. These choices make the small learner reproducible, without claiming that they are universally preferable.
fit_bagging takes explicit index sequences, each of length n. It does not randomly sample them. In the main program we supply every one of the 3³ ordered sequences, each of which has conditional bootstrap probability 1/27. Thus the average is the exact conditional bootstrap expectation for this dataset, not 27 independent random bags. In particular, the random no-coverage formula above must not be applied to this deliberately exhaustive collection. To run the usual finite random procedure, supply independent draws generated with a recorded seed.
Identical sequences are retained when supplied; a duplicate record within one sequence also retains its weight. OOB membership uses original record indices. Two records with the same feature value are still two indices.
from fractions import Fraction as F
from itertools import product
def rational(value):
if isinstance(value, bool) or not isinstance(value, (int, F)):
raise ValueError('coordinates must be integers or Fractions')
return F(value)
def data_rows(rows):
if not isinstance(rows, (list, tuple)) or not rows:
raise ValueError('rows must be a nonempty list or tuple')
result = []
for row in rows:
if not isinstance(row, (list, tuple)) or len(row) != 2:
raise ValueError('each row must contain x and y')
result.append(tuple(rational(v) for v in row))
return tuple(result)
def mean(values):
return sum(values, F(0)) / len(values)
def _fit(data):
# A constant wins an SSE tie; otherwise the first threshold wins.
level = mean(tuple(y for x, y in data))
best = {'threshold': None, 'left': level, 'right': level,
'sse': sum(((y - level) ** 2 for x, y in data), F(0))}
xs = sorted(set(x for x, y in data))
for lo, hi in zip(xs, xs[1:]):
threshold = (lo + hi) / 2
left = tuple(y for x, y in data if x <= threshold)
right = tuple(y for x, y in data if x > threshold)
a, b = mean(left), mean(right)
sse = (sum(((y - a) ** 2 for y in left), F(0))
+ sum(((y - b) ** 2 for y in right), F(0)))
if sse < best['sse']:
best = {'threshold': threshold, 'left': a,
'right': b, 'sse': sse}
return best
def fit_stump(rows):
return _fit(data_rows(rows))
def stump_value(model, x):
return (model['left'] if model['threshold'] is None
or x <= model['threshold'] else model['right'])
def fit_bagging(rows, bags):
data = data_rows(rows)
n = len(data)
if not isinstance(bags, (list, tuple)) or not bags:
raise ValueError('bags must be a nonempty list or tuple')
draws = []
for bag in bags:
if not isinstance(bag, (list, tuple)) or len(bag) != n:
raise ValueError('each bag must draw exactly n indices')
if any(type(i) is not int or not 0 <= i < n for i in bag):
raise ValueError('bag indices must be integers in range')
draws.append(tuple(bag))
models, counts, sums = [], [0] * n, [F(0)] * n
for bag in draws:
model = _fit(tuple(data[i] for i in bag))
models.append(model)
included = set(bag)
for i, (x, y) in enumerate(data):
if i not in included:
counts[i] += 1
sums[i] += stump_value(model, x)
oob = tuple(sums[i] / counts[i] if counts[i] else None
for i in range(n))
covered = tuple(i for i in range(n) if counts[i])
mse = (sum(((oob[i] - data[i][1]) ** 2 for i in covered), F(0))
/ len(covered) if covered else None)
return {'models': tuple(models), 'draws': tuple(draws),
'oob_counts': tuple(counts), 'oob': oob,
'coverage': F(len(covered), n), 'oob_mse': mse}
def predict(model, xs):
# model is an unmodified fit_bagging result; xs may be empty.
if not isinstance(xs, (list, tuple)):
raise ValueError('queries must be a list or tuple')
queries = tuple(rational(x) for x in xs)
return tuple(mean(tuple(stump_value(tree, x)
for tree in model['models'])) for x in queries)
if __name__ == '__main__':
data = ((0, 0), (1, 1), (2, 4))
bags = tuple(product(range(len(data)), repeat=len(data)))
model = fit_bagging(data, bags)
base = fit_stump(data)
print('base:', ', '.join(str(stump_value(base, F(x))) for x in (0, 1, 2)))
print('bags:', len(bags))
print('average:', ', '.join(map(str, predict(model, (0, 1, 2)))))
print('OOB counts:', model['oob_counts'])
print('OOB predictions:', ', '.join(map(str, model['oob'])))
print('coverage:', model['coverage'], 'OOB MSE:', model['oob_mse'])
constant = fit_bagging(((0, 0), (0, 1), (0, 4)), bags)
print('mean-only average:', predict(constant, (0,))[0])
none = fit_bagging(data, ((0, 1, 2),))
print('no OOB:', none['oob'], 'MSE:', none['oob_mse'])
The complete standard-library program prints:
base: 1/2, 1/2, 4
bags: 27
average: 14/27, 20/27, 83/27
OOB counts: (8, 8, 8)
OOB predictions: 11/8, 1/2, 7/8
coverage: 1 OOB MSE: 127/32
mean-only average: 5/3
no OOB: (None, None, None) MSE: None
There are eight bags excluding each index, so every record has an OOB prediction. The last record’s OOB prediction is 7/8: none of its contributing learners has seen its response of four. The OOB MSE is 127/32. This is a calculation on three constructed records, not an estimated performance result for an application.
On the training records, the single stump has MSE 1/6, whereas the bagged predictions have MSE 290/729. That difference does not establish which method generalizes better; it prevents us from quietly treating averaging as a guarantee of lower error on every dataset.
For n records and B supplied bags, the simple implementation uses O(Bn²) arithmetic/comparison operations under expected constant-time hashing, ignoring integer bit costs: each of at most n−1 cuts rescans its bag. OOB aggregation adds O(Bn). Saved draws, models and OOB arrays occupy O(Bn+n) entries. Predicting m queries takes O(1+mB) arithmetic/comparison operations and O(1+m+B) extra entries for validated queries, outputs and one temporary set of base predictions. Exact rational numerators and denominators can grow; these are operation counts, not bit-complexity or runtime guarantees. The code validates raw data, bags and query coordinates; predict expects an unmodified result from fit_bagging.
More fits cannot create missing information
A useful counterexample is the sample mean. If the base learner always predicts the mean of its bag, every bootstrap draw has the original empirical distribution. Linearity of expectation gives
The star denotes resampling conditional on the original responses. In the program, all feature values in the second dataset are zero, so every stump must be constant. Averaging all 27 bag means returns exactly 5/3, the original sample mean. A finite randomly selected collection may differ, but that difference is resampling noise, not evidence of a new source of information.
OOB evaluation also has a boundary. The original training records are reused across fits; they do not become an independent final test set. If we repeatedly choose model settings using OOB error, we are using OOB as a selection signal. A separate evaluation is still needed for an assessment protected from that selection. Any learned preprocessing used by an OOB learner must also exclude its OOB records; globally fitted target-dependent preprocessing would break the intended exclusion. This example performs no preprocessing.
Index exclusion alone is insufficient when records share an underlying unit or are related over time. An OOB learner might still see a related record. The bootstrap unit and the evaluation split must match the sampling question. For independent records, ordinary bootstrap sampling is a useful starting point; it does not make three records representative of an unseen population. More bags also cannot repair a poor response variable, systematic measurement error or a restrictive base learner.
The official guide distinguishes bootstrap resampling from sampling without replacement, and from feature subsampling. These choices lead to different ensembles. This chapter keeps all available features and changes only sampled records. A random forest chapter adds feature randomness; it should not be inferred from our one-feature stump. scikit-learn 1.7.2: Bagging meta-estimator
Check the averaging and the exclusions
- With three records and size-three bags, how often is a specified record OOB? How many of all 27 ordered bags exclude it?
Answer: Each draw has two acceptable indices, so there are 2³=8 excluding sequences. The probability is 8/27. For two independent random bags, the probability of no OOB prediction is (19/27)². This last formula does not describe a deliberately selected pair of bags.
- What does
fit_baggingreport for the main dataset with only the bag(0, 0, 1)? May its OOB MSE be reported as an error over all three records?
Answer: Only index 2 is absent. The stump predicts one at x=2, so OOB predictions are (None, None, 1), counts are (0, 0, 1), coverage is 1/3 and OOB MSE is nine. That MSE is for one covered record. The other two have no OOB estimate; assigning zero to them would invent predictions.
- At a fixed query, suppose each predictor has variance four and each pair has correlation 1/4 under the same probability experiment. What is the ensemble variance for B=10? What assumption is still missing before claiming lower test MSE than a single full-data fit?
Answer: The variance is four times [1/4+(3/4)/10], or 13/10. The full-data fit need not have the same distribution as one bootstrap fit. We still need the appropriate comparison of bias and variance, and a specified test distribution and loss. The calculation alone cannot supply them.
- Why does the mean-only example return 5/3? Does one bag containing only index 0 contradict that result?
Answer: The average over all equally probable bootstrap bags equals the conditional expectation of a bag mean, which is the original mean. One bag containing only index 0 predicts zero. An individual random realization need not equal its expectation; all bags, their probabilities and their multiplicities matter.
From the bootstrap construction to an auditable experiment
The primary source read for this chapter is Breiman’s September 1994 Technical Report 421, including its opening formulation and discussion of instability. The official guide identifies the later 1996 Machine Learning article, volume 24(2), pages 123–140; that bibliographic record is not a claim that the later article was independently read. The 1.7 documentation path displayed scikit-learn 1.7.2 when checked. The program above is original standard-library code, not an execution or translation of scikit-learn. Breiman’s technical report, official guide and bibliography
The accompanying tests extract and execute the published code. An independent reference enumerates ordered partitions of feature values and computes leaf error through pairwise response differences. For ensemble averages it groups bootstrap sequences into count compositions and weights them by multinomial multiplicity, instead of repeating the program’s sequence enumeration. Tests cover missing and partial OOB coverage, ties, repeated indices, reordered data, exact rational inputs and the mean counterexample. These are AI-authored mathematical and program checks on small cases, not human review or evidence that bagging improves an unspecified task. To compare it with a base learner in a real experiment, hold the evaluation protocol fixed, report the aggregation and sampling rules, and keep the final assessment separate from choices made using OOB results.
Make a prediction, then check
For three records and the only bag (0, 0, 1), what is OOB coverage?
Learning objectives
- Construct bootstrap fits with replacement and distinguish regression averages, hard votes and probability averages.
- Derive the conditional and unconditional variance identities without claiming universal error reduction.
- Compute index-based OOB coverage and covered-only MSE, and separate them from a final test assessment.
Prerequisites & connections
Explore related knowledge →References
- Bagging Predictors — Technical Report No. 421
Leo Breiman · 1994 - Bagging meta-estimator — scikit-learn 1.7.2 documentation
scikit-learn contributors
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Nine tests pass. Independent weighted-partition and pairwise-dispersion references verify 55 stump fits. Multinomial count compositions verify three complete ensembles containing 310 ordered bags, including all model fields, predictions, OOB counts, means, coverage and MSE.
- Verified n=1 and full-coverage bags with no OOB predictions, partial coverage, duplicate coordinates versus indices, duplicate weights, constant/split ties, relabeling, input preservation, invalid inputs, 90-digit rational responses and exact random no-coverage probabilities. Main averages are 14/27, 20/27, 83/27; OOB counts are 8 each and OOB MSE is 127/32. Mean-only exhaustive bagging remains 5/3.
- Both articles share runnable Python and eight stdout lines, six display equations, six required anchors and four answered exercises. Strict MDX, KaTeX and React HTML renders pass, including exact MathML formula correspondence and emphasis checks. Tests load articles only through article_text. Original writing was reread with the pinned Humanizer rules. Status remains written: AI author checks, no human review, production benchmark, library execution, whole-site build or browser UI acceptance.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- Bagging Predictors — Technical Report No. 421 · Actually opened the 20-page original PDF. Cover identifies Leo Breiman, Technical Report No. 421, September 1994. Printed pages 1–2 (physical PDF pages 2–3), extracted lines 12–75, define numerical averaging and class voting from size-n replacement samples and discuss instability and possible harm for stable procedures. No later journal version or empirical table independently audited. The article’s covariance identities, exact enumeration and mean counterexample are derived explicitly rather than attributed as verbatim report theorems.
- Bagging meta-estimator — scikit-learn 1.7.2 documentation · Actually read guide §1.11.3, extracted lines 642–654, distinguishing bootstrap, pasting and feature sampling; lines 670–672 give the 1996 Machine Learning 24(2), 123–140 citation. Actually read https://scikit-learn.org/1.7/modules/generated/sklearn.ensemble.BaggingRegressor.html lines 646–674 for full-size replacement bags, lines 720–734 for sampled indices and unavailable OOB predictions, and lines 845–847 for mean regression prediction. The guide also distinguishes hard votes and averaged probabilities. These pages displayed 1.7.2 on 2026-09-05. Our regression-only prototype does not implement library estimators or treat OOB as an independent test set.
- Bagging Predictors — Technical Report No. 421 · Actually read original 20-page university PDF cover (September 1994, report 421), printed pp. 1–2 / PDF pages 2–3, lines 12–75: numerical averaging, plurality voting, size-n replacement samples, instability motivation and possible harm for stable learners. No later journal copy or empirical-table reproduction claimed.
- Bagging meta-estimator — scikit-learn 1.7.2 documentation · Actually read the metadata guide URL, rendered 1.7.2, §1.11.3 lines 642–672: bagging versus pasting/feature subsampling and 1996 journal bibliography. Also opened the linked BaggingRegressor API: lines 620,646–674 for defaults/sampling, 720–734 for indices and unavailable OOB estimates, 845–847 for averaging prediction. The source identity remains the metadata guide card; the API is a supporting locator, not a renamed source.
Related topics