Skip to content
AI.info

Advanced techniques

Bagging, Randomization, and Out-of-Bag Evaluation

Learn how bootstrap aggregation, feature randomization, and out-of-bag predictions work together in practical ensembles.

By the end you can

One dataset, many plausible training worlds

A finite training set is only one sample from the process you care about. An unstable learner can react strongly to which rows happened to appear. Bagging makes that instability visible and useful. It creates many bootstrap samples, trains one model on each sample, and aggregates their predictions. A bootstrap sample is drawn with replacement and usually has the same number of rows as the original training set. Some rows appear multiple times. Others are absent. Across many samples, each model sees a slightly different version of the evidence.

Fifty bagged CART trees lowered the average misclassification rate on all seven datasets Leo Breiman tested in 1996. Waveform fell from 29.1% to 19.3%, a 34% decrease. Heart went from 4.9% to 2.8%, a 43% decrease. Breast cancer 5.9% to 3.7% (37%). Ionosphere 11.2% to 7.9% (29%). Glass 30.4% to 23.6% (22%). Soybean 8.6% to 6.8% (21%). Then diabetes: 25.3% to 23.9%, a decrease of 6%. That last pair is the reason bagging is not a generic accuracy switch. The identical procedure that removed a third of the error on waveform removed six percent of it on diabetes.

An independent study over 23 datasets, published in 1999, reached the same qualitative conclusion. The abstract by Opitz and Maclin marks the edges of it: “First, while Bagging is almost always more accurate than a single classifier, it is sometimes much less accurate than Boosting.”

A highly stable learner may produce nearly identical models across bootstrap samples, leaving little variance to remove. The technique is especially natural for deep decision trees and other flexible, high-variance estimators.

Bagging converts sample sensitivity into a source of diversity, then averages that diversity into stability.

Steps

Bootstrap aggregation from raw rows to a prediction

The process is simple, but each step changes what you can later measure. Draw bootstrap samples by resampling rows with replacement. Fit one base learner per sample, usually with separate randomness. Predict with every member, producing a score, probability, or class from each. Aggregate by averaging numeric outputs or by combining class probabilities and votes. Then audit stability: compare aggregate performance, variance across seeds, and failure slices.

The second step is where the guarantee is most often lost. Each member has to be fitted independently on its own resample. If a preprocessing stage sees the full dataset first, the members stop being independent fits of one procedure. The aggregate then stops behaving like an average over plausible training worlds.

The fifth step is not optional bookkeeping either. Set the spread of a single member across seeds against the spread of the ensemble. That comparison is the only direct evidence that the aggregation did anything at all.

FigureProcess · 5 steps
  1. 1. Draw bootstrap samples

    Sample rows with replacement from the training set.

  2. 2. Fit independent base learners

    Train one learner per bootstrap sample, usually with separate randomness.

  3. 3. Predict with every learner

    Produce a score, probability, or class from each member.

  4. 4. Aggregate

    Average numeric outputs or combine class probabilities and votes.

  5. 5. Audit stability

    Compare aggregate performance, variance across seeds, and failure slices.

Visual

Where out-of-bag predictions come from

A row omitted from a member's bootstrap sample can be predicted by that member without direct training exposure. How many such rows there are is fixed by the arithmetic of the bootstrap, and Breiman stated it plainly in 2001: “In each bootstrap training set, about one-third of the instances are left out.” Every out-of-bag prediction is therefore assembled from roughly a third of the forest, never from all of it.

The same mechanic has a quantitative restatement. An out-of-bag prediction uses on average only exp(-1)·T of the T trees grown. So a performance curve measured on independent test data converges faster than the out-of-bag curve by a factor of 2.7, as Probst and Boulesteix put it. That gap is not a defect in the estimate. It is the price of never having spent a row on a test set. It also fixes the direction of the bias: a third of a forest is a smaller forest, and a smaller forest scores worse.

FigureProcess · 4 steps
  1. 1

    Original training rows

    The complete development dataset before bootstrapping.

  2. 2

    Bootstrap sample

    Rows drawn with replacement; some are repeated and some omitted.

  3. 3

    Out-of-bag subset

    Rows not selected for this particular member.

  4. 4

    OOB prediction pool

    For each row, aggregate predictions only from members that did not train on it.

Out-of-bag predictions are cross-fitted development predictions, not a substitute for a final untouched test set.

Comparison

Bagging, random forests, and extra trees

All three aggregate trees, but they inject randomness at different points. Bagged trees randomise the rows and leave the ordinary split search alone. A random forest randomises the rows and, at every split, restricts which features may compete. That restriction is what pulls the trees apart from one another.

Extremely randomized trees drew the third line in 2006. The paper that introduced them states the difference in one sentence: “Its two main differences with other tree-based ensemble methods are that it splits nodes by choosing cut-points fully at random and that it uses the whole learning sample (rather than a bootstrap replica) to grow the trees.” Its defaults are K=sqrt(n) for classification and K=n for regression, and every ensemble in its experiments was grown to M=100 trees. The saving is measured rather than asserted: an average computing-time ratio of 0.36 against Random Forests over the twelve classification datasets, and about 10x faster than Tree Bagging.

scikit-learn implements exactly this split. The documentation gives bootstrap=True as the default for random forests and bootstrap=False for extra-trees. Read that line carefully before you reach for out-of-bag scores. With the documented default, the third method does not bootstrap at all, so there is no out-of-bag set to score against.

FigureComparison · 3 columns

Bagged trees

Bootstrap the rows, then grow each tree with the ordinary split search.

  • Strong variance reduction for deep trees
  • Trees can remain highly correlated
  • All features may compete at every split
  • Useful as the cleanest bagging baseline

Random forest

Bootstrap rows and restrict the feature candidates at each split.

  • Feature randomization reduces tree correlation
  • Often strong with little tuning
  • Supports out-of-bag estimates
  • Can dilute rare but dominant predictors

Extremely randomized trees

Use stronger split randomization, often with the full sample depending on implementation.

  • Injects more diversity into tree construction
  • Can reduce variance further
  • May increase bias on some tasks
  • Usually fast because split search is simplified

Example

Signals that bagging is likely to help

These are empirical clues, not guarantees, and the cleanest way to read them is against a case where every clue is absent. Bagged nearest-neighbour classifiers come back with the rate they started with. Breiman ran 100 bootstrap replicates over 100 iterations on six of the same datasets and got identical rates unbagged and bagged: waveform 26.1/26.1, heart 5.1/5.1, breast cancer 4.4/4.4, ionosphere 36.5/36.5, diabetes 29.3/29.3, glass 30.1/30.1. His explanation is that each bootstrap replicate retains about .632 of the cases, which is not enough perturbation to move a stable rule. His own summary is blunter: “Cycles did not have to be expended to find that bagging nearest neighbors does not change things.” Bühlmann and Yu later formalised why the gain is confined to unstable, hard-decision estimators, in a 2002 analysis. The same protocol that cut tree error by up to 43% left this learner unchanged to the decimal on all six datasets.

The last clue, latency, has been settled in production. Microsoft Kinect classified depth-image pixels into 31 body parts using a forest of just 3 trees of depth 20. The randomisation was pushed into the training data instead: each tree was fitted to a different set of randomly synthesised images, 300k images per tree and 2,000 sampled pixels per image. Training 3 trees to depth 20 from 1 million images took about a day on a 1,000-core cluster. The inference budget is why the ensemble stayed at three. The 2011 paper by Shotton and his co-authors says why: “An optimized implementation of our algorithm runs in under 5ms per frame (200 frames per second) on the Xbox 360 GPU, at least one order of magnitude faster than existing approaches.”

  • Deep trees change structure substantially across folds or random seeds — the instability that let 50 bagged CART trees take waveform error from 29.1% to 19.3%.
  • Validation performance is competitive on average but has a wide spread across resamples.
  • Individual predictors overreact to unusual rows or small sample perturbations. A learner that does not, like the nearest-neighbour classifiers Breiman bagged, returns the same rate to the decimal (heart 5.1/5.1, glass 30.1/30.1).
  • The problem has nonlinear interactions that a shallow, stable model underfits.
  • Prediction latency can tolerate evaluating many members — or, where it cannot, the Kinect route: 3 trees of depth 20, with the randomness moved into the training data to hold inference under 5 ms per frame.

Key idea

Do not tune indefinitely on the out-of-bag score

Out-of-bag estimates are efficient because they reuse the training set. But repeated decisions based on the same OOB signal can overfit the process you are developing with. If you compare hundreds of feature sets, hyperparameters, and thresholds against one OOB estimate, it stops behaving like untouched evidence.

Keep an external validation or test protocol for final decisions. Time-dependent, grouped, or spatial data may also require custom resampling, because an ordinary row bootstrap can destroy the dependence structure.

The estimate has both a known accuracy and a known direction. Breiman cited evidence in 2001 that it is “as accurate as using a test set of the same size as the training set”, and noted in the same section that it “will tend to overestimate the current error rate”. How far that overestimate can run was measured in 2018 by Janitza and Hornung. In a balanced null-case simulation where the true error rate is 0.5, the gap between OOB error and test error was 10% to 30% at n=20 with p=1000 predictors, depending on mtry. On six real high-dimensional genomic datasets, both OOB and cross-validation overestimated the true error by about 5%. Their abstract names the regime where the problem bites: “the overestimation is largest in balanced settings and in settings with few observations, a large number of predictor variables, small correlations between predictors and weak effects”. Their recommendation is stratified subsampling with sampling fractions proportional to class sizes, used for both tuning and error estimation.

OOB evaluation is convenient development evidence, not immunity from selection bias or dependency leakage.

Analogy

Many drafts, one set of research notes

Several slightly different drafts, all built from the same research notes, reach an editor. Each draft emphasizes different examples and may contain a few local mistakes. A careful synthesis can be more stable than trusting a single draft.

That safeguard disappears when every draft copies the same false source. Bagging changes which observations influence each learner. It does not repair systematic label errors or missing populations.

How many drafts is enough has been measured. Random forests of 2,000 trees were grown 1,000 times per dataset, over 306 datasets from OpenML. For binary classification, going from 10 to 250 trees lowered the OOB error rate by 0.0306 on average and raised AUC by 0.0521. Going from 250 to 2,000 trees bought only 0.0018 more error and 0.0032 more AUC. Nor is the curve reliably downhill. In 16 datasets, about 10% of them, the error at 2,000 trees was at least 0.005 worse than the minimum reached somewhere in T between 10 and 250. Probst and Boulesteix put the finding against the folklore in their abstract: “While the principle underlying bagging is that more trees are better, in practice the classification error rate sometimes reaches a minimum before increasing again for increasing number of trees.” Oshiro and colleagues had found the compatible result independently in 2012, on 29 datasets: beyond about 128 trees, the AUC gain from adding trees is minimal.

Resampling diversifies exposure to the data; aggregation reduces the influence of any one unstable fit.

Example

An out-of-bag audit for small and dependent datasets

Out-of-bag predictions are convenient, but what they mean depends on how rows relate to one another. The cost of getting that wrong has been measured on one model and one dataset. A random forest was trained on a forest inventory of 11.8 million trees in central Africa. Under standard random 10-fold cross-validation it scored R2 = 0.53 with RMSPE 56.5 Mg/ha. Under a spatial 44-fold cross-validation it scored R2 = 0.14 with RMSPE 77.5 Mg/ha. Same model, same data. Only the resampling changed. Ploton and colleagues published the comparison in Nature Communications in 2020, and their abstract states it flatly: “A standard nonspatial validation method suggests that the model predicts more than half of the forest biomass variation, while spatial validation methods accounting for SAC reveal quasi-null predictive power.” Meyer and colleagues reached the same conclusion independently in 2019, with Random Forest case studies. An ordinary row bootstrap makes exactly the assumption the random 10-fold split made.

  • Independent rows: Compare OOB estimates with a held-out test to detect optimistic tuning through repeated OOB use.
  • Grouped observations: Bootstrap groups rather than rows when several records come from the same person, device, or account.
  • Time-ordered or spatial data: Do not treat neighbouring observations as interchangeable — the same forest scored R2 = 0.53 under random 10-fold and R2 = 0.14 under 44-fold spatial validation.
  • Rare classes: Record how many OOB predictions each rare example receives and whether class coverage varies across trees.
  • Pipeline leakage: Fit imputers, encoders, and feature selectors inside each bootstrap training sample rather than once on the full dataset.

Key takeaways