---
title: "Ensemble learning: bagging, boosting and stacking explained · CloudSat"
description: "How bagging, random forests, boosting, voting and stacking combine models, why averaging cuts variance, and how to compare them fairly in scikit-learn."
url: https://cloudsat.io/learn/ensemble-learning-bagging-boosting-stacking
updated: 2026-11-18T12:00:00Z
source: CloudSat (https://cloudsat.io/). Prices in USD.
---

[AI and machine learning](https://cloudsat.io/learn/topic/ai)

# Ensemble learning: bagging, boosting and stacking explained

How bagging, random forests, boosting, voting and stacking combine models, why averaging cuts variance, and how to compare them fairly in scikit-learn.

CloudSat team November 18, 2026 6 min read

An ensemble combines several models so that their errors partly cancel. Gradient-boosted trees, one family of ensembles, are a standard first choice for tabular data, and random forests are among the most forgiving baselines in machine learning. The idea works under one condition: each member must be decent on its own, and the members must make different mistakes. Every ensemble method is, at heart, a recipe for producing that difference.

## Why combining models works

Prediction error splits into bias (systematic misses because the model is too simple) and variance (sensitivity to the particular sample it was trained on). Averaging attacks variance. If you average B models whose predictions each have variance σ² and pairwise correlation ρ, the variance of the average is:

```text
Var(average) = ρ·σ² + (1 − ρ)·σ² / B
```

Adding members shrinks the second term toward zero, but the first term stays. Correlated members stop helping quickly, which is why ensemble methods work so hard to make their members disagree. Boosting goes after bias instead, by building each new model to fix what the previous ones got wrong.

## Bagging step by step

Bagging, short for bootstrap aggregating, was introduced by Leo Breiman in 1996:

1. Draw B bootstrap samples. Each one is n rows drawn with replacement from the n training rows.
2. Train one model per sample, independently and in parallel.
3. Combine them: a majority vote for classification, an average for regression.

Each bootstrap sample leaves out about 36.8% of the rows, because the chance that a given row is never drawn is `(1 - 1/n)^n`, which approaches 1/e as n grows. Those out-of-bag rows make a free validation set: score each row using only the models that never saw it.

Bagging helps unstable, high-variance learners such as deep decision trees, whose structure shifts with small changes in the data. It does little for stable models like linear regression, whose bootstrap copies all come out nearly identical.

### Random forests

A random forest (Breiman, 2001) is bagged decision trees with one more source of diversity: at each split, a tree may consider only a random subset of the features. That stops every tree from splitting on the same strong feature first, which lowers ρ in the formula above. In scikit-learn the setting is `max_features`, and for classification it defaults to the square root of the feature count.

## Boosting: models in sequence

Boosting trains models one after another, each one aimed at the errors left by those before it.

- **AdaBoost**, from Yoav Freund and Robert Schapire in the mid-1990s, reweights the training rows after each round so misclassified rows count more, then combines the models with weights based on their accuracy.
- **Gradient boosting**, formalized by Jerome Friedman in 2001, fits each new tree to the gradient of the loss (for squared error, simply the residuals) and adds it with a small learning rate.

Modern libraries such as XGBoost, LightGBM, CatBoost and scikit-learn's histogram-based estimators bin feature values, which keeps training fast on large tables. Because boosting keeps fitting the training data, it can overfit. A small learning rate, shallow trees and early stopping on validation data keep it honest.

## Voting and stacking

- **Voting** combines different kinds of models. Hard voting takes the majority class; soft voting averages predicted probabilities, which usually works better when the members are reasonably calibrated.
- **Stacking**, described by David Wolpert in 1992, trains a meta-model on the members' predictions. The meta-model must learn from out-of-fold predictions, made on rows each member did not train on. Otherwise it learns to trust whichever member memorized the training set. scikit-learn's `StackingClassifier` runs that cross-validation internally.

## The methods side by side

| Method | How members are trained | Mainly reduces | Parallel training | Settings that matter |
| --- | --- | --- | --- | --- |
| Bagging | Independently, on bootstrap samples | Variance | Yes | Number of models, sample size |
| Random forest | Independently, with random feature subsets | Variance | Yes | Number of trees, `max_features`, depth |
| AdaBoost | In sequence, reweighting rows | Bias | No | Rounds, learning rate |
| Gradient boosting | In sequence, fitting gradients | Bias | Within each tree only | Learning rate, depth, early stopping |
| Voting | Independently, different algorithms | Variance | Yes | Hard or soft, member weights |
| Stacking | Independently, plus a meta-model | Both | For the members | Meta-model, number of folds |

## Compare them on one dataset

Scoring every candidate on the same cross-validation folds gives a fair comparison. This script uses a dataset that ships with scikit-learn, so it runs anywhere:

```python
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import (BaggingClassifier, HistGradientBoostingClassifier,
                              RandomForestClassifier, StackingClassifier)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.tree import DecisionTreeClassifier

X, y = load_breast_cancer(return_X_y=True)
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=0)

models = {
    "single tree": DecisionTreeClassifier(random_state=0),
    "bagged trees": BaggingClassifier(estimator=DecisionTreeClassifier(), n_estimators=200,
                                      oob_score=True, random_state=0),
    "random forest": RandomForestClassifier(n_estimators=300, random_state=0),
    "gradient boosting": HistGradientBoostingClassifier(learning_rate=0.05, random_state=0),
    "stacking": StackingClassifier(
        estimators=[("rf", RandomForestClassifier(n_estimators=300, random_state=0)),
                    ("hgb", HistGradientBoostingClassifier(random_state=0))],
        final_estimator=LogisticRegression()),
}

for name, model in models.items():
    scores = cross_val_score(model, X, y, cv=cv, scoring="roc_auc", n_jobs=-1)
    print(f"{name:18} ROC AUC {scores.mean():.3f} +/- {scores.std():.3f}")

bagging = models["bagged trees"].fit(X, y)
print(f"bagging out-of-bag accuracy {bagging.oob_score_:.3f}")
```

Read the spread as well as the mean. On a dataset this small, gaps inside one standard deviation are noise. On your own data, also keep a holdout set that you score once, after you have chosen.

## Choosing and tuning

- **Start with gradient-boosted trees** on tabular data, with early stopping. scikit-learn's `HistGradientBoostingClassifier` switches it on by itself above 10,000 rows.
- **Keep a random forest as the baseline.** It needs little tuning and reports out-of-bag estimates for free.
- **Stack last,** for the final increment, and only when the members are both strong and different from each other.
- **Guard against leakage.** Scaling, encoding or feature selection fitted on the whole dataset before cross-validation inflates every score. Put preprocessing inside a pipeline so it is refitted on each training fold.
- **Price the predictions.** Five hundred trees are slower to serve and harder to explain than one model. Check latency and memory before you ship.

## Running ensembles on a server

Tree ensembles run on CPUs and spread well across cores: `n_jobs=-1` puts every core to work in forests, bagging and cross-validation. Memory grows with the number and depth of trees, so a large forest on wide data can take several gigabytes. XGBoost and LightGBM can also train on GPUs (in XGBoost, set `device="cuda"`), which pays off on large tables. For long tuning sweeps, a CloudSat [High Frequency VPS](https://cloudsat.io/high-frequency-vps) adds fast cores at $2.78 and up, and keeps the work running after your laptop closes.

## FAQ

### Is a random forest a kind of bagging?

Yes: bagged decision trees plus a random choice of features at each split. The extra randomness makes the trees less alike, and that is what lets averaging help.

### Does bagging help linear models?

Rarely. A linear model barely changes from one bootstrap sample to the next, so its copies agree and their average is about the same as any one of them.

### Should I try bagging or boosting first?

On tabular data, boosting often reaches higher accuracy once tuned, while forests are easier to get right with defaults. Run both through the same cross-validation; on most tables that takes minutes.

### Is a mixture-of-experts LLM an ensemble?

Not in this sense. Its experts are trained together, and a router sends each token to a few of them. An ensemble combines separately trained models and asks every one of them about every input.

**Run it on CloudSat.** Cloud VPS on AMD EPYC and NVMe from $1.98/mo in 13 regions, delivered in under 5 minutes and paid in crypto. [See plans](https://cloudsat.io/plans) or [deploy a server](https://dash.cloudsat.io/console/deploy).

## Keep reading

[All guides in AI and machine learning](https://cloudsat.io/learn/topic/ai)

- [Privacy-preserving ML: which technique stops which leak](https://cloudsat.io/learn/privacy-preserving-ml-techniques-compared): AI and machine learning Privacy-preserving ML: which technique stops which leak 7 min read
- [CUDA cores vs Tensor Cores: reading GPU specs for AI](https://cloudsat.io/learn/cuda-cores-tensor-cores-gpu-specs-for-ai): AI and machine learning CUDA cores vs Tensor Cores: reading GPU specs for AI 7 min read
- [AI agent loops in production: budgets, checkpoints, backoff](https://cloudsat.io/learn/ai-agent-loop-guardrails-for-production): AI and machine learning AI agent loops in production: budgets, checkpoints, backoff 7 min read
- [How to choose a GPU for AI: VRAM first, then bandwidth](https://cloudsat.io/learn/choose-a-gpu-for-ai-workloads): AI and machine learning How to choose a GPU for AI: VRAM first, then bandwidth 7 min read
