Machine Learning Slides 📂 Introduction · 16 of 17 50 min read

Ensemble Learning: Bagging, Boosting & Stacking Explained

Why do random forests and XGBoost dominate Kaggle? Because a crowd of "okay" models beats one brilliant one. This tutorial breaks down ensemble learning from the ground up — the wisdom-of-crowd math that makes it work, bagging (parallel, cuts variance), boosting (sequential, cuts bias), and stacking (a meta-model that learns how to blend). With animated diagrams, hard vs soft voting, sklearn code, and the pitfalls that quietly wreck ensembles.

🎭

Ensemble Learning

Why a committee of mediocre models beats one brilliant one — the three great families Bagging, Boosting and Stacking, and the wisdom-of-the-crowd maths that makes them work.
Bagging Boosting Stacking Voting

Press Next → or use ← → arrow keys

Section 01

Why Combine Models At All?

Guess the weight of the ox — the crowd beats the expert
At a county fair, hundreds of people guess an ox's weight. Individually most are badly wrong — some far too high, some far too low. But average all their guesses and the number lands within a pound of the truth. The individual errors, pointing in every direction, cancel out.

Ensemble learning is that fair, formalised. Train many models that each make different mistakes, then combine them. As long as their errors are uncorrelated, the ensemble is far more accurate — and more stable — than any single member.
💡
Weak Learners → Strong Ensemble

A weak learner only needs to be slightly better than a coin flip. Combine enough of them, with uncorrelated errors, and the ensemble converges toward near-perfect accuracy. Diversity is the whole game.

3Great families
↓VarBagging cuts variance
↓BiasBoosting cuts bias
ρ→0Low correlation = win
Section 02

The Maths — Uncorrelated Errors Cancel

individual model predictions (scattered around truth) → TRUTH ENSEMBLE AVERAGE Var(ensemble) = ρσ² + (1−ρ)/N · σ²
🧮
The Formula That Explains Everything

Ensemble variance = ρσ² + (1−ρ)/N · σ², where ρ is the correlation between models, σ² their individual variance, and N the count. As N grows, the second term vanishes — but the first term, ρσ², only shrinks if models are uncorrelated. That's the mathematical proof that diversity beats individual accuracy.

Section 03

The Three Families At A Glance

Ensemble Learning BAGGING parallel · independent cuts VARIANCE Random Forest Extra Trees bootstrap + vote BOOSTING sequential · corrective cuts BIAS AdaBoost · GBM XGBoost · LightGBM fix previous errors STACKING meta-learner combines cuts BOTH RF + SVM + KNN… + meta-model out-of-fold preds
🧭
One Sentence Each

Bagging trains many models in parallel and averages them — killing variance. Boosting trains models in sequence, each fixing the last one's mistakes — killing bias. Stacking trains a meta-model to blend diverse base learners — attacking both.

Section 04

Bagging — Parallel Independence

Training Data 🌳 Tree 1 bootstrap A 🌳 Tree 2 bootstrap B 🌳 Tree N bootstrap N VOTE / AVERAGE all trees at once · parallel ↓ variance
🌲
Independence Is The Point

Each tree trains on a different bootstrap sample (rows drawn with replacement — ~63% unique). Random Forest adds a random feature subset at every split for extra diversity. Because the trees are independent, training is trivially parallel (n_jobs=-1), and averaging their uncorrelated errors crushes variance. The ~37% left-out rows give free OOB validation.

Section 05

Boosting — Sequential Error Correction

Round 1 2 errors (enlarged) Round 2 up-weight the errors 1 error left Round 3 focus on last error all correct ✓ Σ αₖ hₖ weighted sum each model fixes what the previous one got wrong · ↓ bias
⚠️
Sequential, Powerful — And Prone To Overfit

Each learner up-weights (AdaBoost) or fits the residuals (Gradient Boosting) of the previous one, so the ensemble relentlessly reduces bias. But it cannot be parallelised, and it will overfit given enough rounds. Always keep a validation set and use early_stopping_rounds. The key knob is learning_rate × n_estimators.

Section 05 · Variants

The Boosting Family — AdaBoost to CatBoost

MethodCore MechanismBest For
AdaBoostRe-weights misclassified samples each roundClean, balanced binary classification
Gradient BoostingFits the residual errors of previous treesFlexible; subsampling tames noise
XGBoostGBM + histogram splits, sparsity handling, regularisationProduction & competitions
LightGBMLeaf-wise growth, histogram binningVery large datasets · speed
CatBoostOrdered boosting, native categorical handlingCategorical-heavy data · little tuning
The Weighted Ensemble
F(x) = α₁h₁(x) + α₂h₂(x) + … + αₖhₖ(x)
Each weak learner hₖ gets a weight αₖ — better learners speak louder in the final sum.
The Critical Trade-off
learning_rate × n_estimators
Lower learning rate → more robust but needs more trees. Tune these two together, always with early stopping.
🏆
The Kaggle King Of Tabular Data

Gradient-boosted trees — especially XGBoost and LightGBM — win the majority of tabular ML competitions. When you need the last 2–3% of accuracy that Random Forest can't reach, this is where you go. Pair with RandomizedSearchCV and early stopping.

Section 06

Stacking — A Meta-Learner On Top

Training Data 🌳 Random Forest base learner 🛡️ SVM base learner 📍 KNN base learner Meta-Learner Logistic Regression · blends OOF preds FINAL PREDICTION Level 0 Level 1
🔒
Out-Of-Fold Predictions Prevent Leakage

The meta-learner must train on predictions the base models made on data they didn't see. Use K-fold: each base learner trains on K−1 folds and predicts the held-out fold — these out-of-fold predictions become the meta-features. Skip this and the meta-learner sees artificially perfect predictions, overfits, and collapses in production.

Section 07

Voting — The Quick Ensemble

Hard Voting
one model, one vote
Each model predicts a class; the majority wins. Simple, but throws away how confident each model was.
📊
Soft Voting
average probabilities
Average the predicted probabilities across models, pick the highest. Uses more information → almost always better.
When To Use
you already have models
Got a few diverse, well-tuned models already? Voting is the fastest ensemble — no meta-learner, no K-fold plumbing.
🗳️
Soft Voting Beats Hard Voting Almost Always

A model that says "90% spam" should count for more than one that barely says "51% spam". Soft voting respects that confidence; hard voting flattens both to a single tick. Reach for soft voting whenever your base models expose predict_proba.

Section 08

Which Error Does Each Family Fix?

Single deep model low bias · HIGH variance → BAGGING averages the scatter Single shallow model HIGH bias · low variance → BOOSTING corrects toward centre Ensemble (stacking) low bias · LOW variance → tight AND on target ✅
ProblemCauseEnsemble Fix
High varianceDeep model memorises noiseBagging / Random Forest — average uncorrelated trees
High biasShallow model underfitsBoosting — sequentially correct residuals
BothNo single architecture is bestStacking — learn the optimal blend
Section 09

Which Ensemble When?

🌲
Random Forest
The default first baseline for any tabular task. Works out of the box, no scaling, free OOB validation.
🚀
XGBoost / LightGBM
When you need maximum accuracy on tabular data. Tune with RandomizedSearchCV + early stopping.
AdaBoost
Clean, balanced, small datasets. Fast and simple — but avoid it on noisy data (outliers get over-weighted).
🗳️
Voting
You already have a few tuned, diverse models. Quick soft-voting ensemble with no extra plumbing.
🏗️
Stacking
When the last 1–2% of accuracy justifies real complexity. Diverse base learners + a simple meta-model.
🚫
A Single Model
When you need interpretability (legal), <1ms latency, or the dataset is tiny (< 200 rows). Ensembles won't help.
🎯
The Standard Progression

Start with Random Forest to establish a solid baseline. If you need more, move to gradient boosting. Only if the last couple of percent genuinely matters do you reach for stacking — it's the most work for the smallest gain.

Section 10

Implementation — All Four In Sklearn

from sklearn.ensemble import (
    RandomForestClassifier, GradientBoostingClassifier,
    AdaBoostClassifier, VotingClassifier, StackingClassifier)
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier

# ── BAGGING · the default baseline ───────────────
rf = RandomForestClassifier(n_estimators=300, n_jobs=-1, oob_score=True)

# ── BOOSTING · higher ceiling · needs early stopping ──
import xgboost as xgb
gbm = xgb.XGBClassifier(
    n_estimators=1000, learning_rate=0.05, max_depth=4,
    subsample=0.8, early_stopping_rounds=30, eval_metric='auc')
gbm.fit(X_tr, y_tr, eval_set=[(X_val, y_val)])

# ── VOTING · soft = average probabilities ────────
vote = VotingClassifier(estimators=[
    ('rf', rf), ('svc', SVC(probability=True)), ('knn', KNeighborsClassifier())
], voting='soft', n_jobs=-1)

# ── STACKING · out-of-fold preds via cv, simple meta ──
stack = StackingClassifier(
    estimators=[('rf', rf), ('svc', SVC(probability=True)), ('knn', KNeighborsClassifier())],
    final_estimator=LogisticRegression(),
    cv=5, n_jobs=-1)          # cv=5 handles OOF automatically
Two Habits That Save You

Always pass n_jobs=-1 to parallelise (bagging, voting, stacking). Always give boosting an eval_set and early_stopping_rounds — it will overfit otherwise. sklearn's StackingClassifier(cv=5) generates the out-of-fold predictions for you, so leakage is handled correctly.

Section 11

Common Pitfalls — What Silently Breaks Ensembles

👯
Correlated Base Learners
no real diversity
RF + ExtraTrees + Bagging all make the same mistakes. Mix fundamentally different algorithms (tree + linear + distance).
💧
Stacking Leakage
in-sample meta-features
Training base learners and the meta-model on the same rows gives the meta-model fake-perfect inputs. Always use out-of-fold predictions.
📈
Over-Boosting
no early stopping
Low learning rate + thousands of rounds → memorised noise. Monitor a validation set with early_stopping_rounds=30.
📊
Accuracy On Imbalance
99% and useless
"Always predict no-fraud" scores 99% on 99%-negative data. Use F1, AUC-ROC or average precision instead.
📏
Missing Per-Model Scaling
mixed ensembles
RF needs no scaling but SVM/KNN do. In a voting/stacking mix, wrap each scale-sensitive model in its own Pipeline.
🎭
MDI Feature Importance
high-cardinality bias
Mean-decrease-impurity over-values many-valued features. Trust permutation_importance or SHAP for attribution.
Section 12 · Part 1

Golden Rules — 1 to 4

🎭 ENSEMBLE LEARNING DISCIPLINE · RULES 1–4
1
Start with Random Forest for any new tabular task. It's the correct default baseline — no scaling, minimal tuning, free OOB validation. Beat it before reaching for anything fancier.
2
Diversity beats individual accuracy. Five mediocre uncorrelated models outperform five excellent identical ones. The variance formula proves it: only low correlation ρ makes the ensemble term vanish.
3
Boosting always needs early stopping. Given enough rounds it will overfit. Hold out a validation set and set early_stopping_rounds — non-negotiable for GBM / XGBoost / LightGBM.
4
Never use training-set predictions for stacking meta-features. Always generate out-of-fold predictions (sklearn's cv=5 does this) or the meta-learner overfits to leaked, artificially-perfect inputs.
Section 12 · Part 2

Golden Rules — 5 to 7

🎭 ENSEMBLE LEARNING DISCIPLINE · RULES 5–7
5
More trees never hurt Bagging / Random Forest. Error decreases monotonically then plateaus — the only cost of more estimators is compute. Contrast with boosting, where more rounds eventually overfit.
6
Always use n_jobs=-1. Bagging, voting and stacking parallelise trivially across cores. There's no reason to train on a single core when the whole machine is available.
7
Choose metrics that match your problem. Accuracy misleads on imbalanced data. Use F1, AUC-ROC, average precision, or a business-relevant loss — and evaluate every ensemble on the metric that actually matters.
The Ensemble Deployment Checklist

✅ RF baseline established · ✅ base learners genuinely diverse · ✅ boosting has early stopping · ✅ stacking uses out-of-fold preds · ✅ n_jobs=-1 set · ✅ metric matches the problem, not just accuracy.

FINAL

Ensembles — Many Models, One Better Answer

BagParallel · ↓ variance
BoostSequential · ↓ bias
StackMeta-learner · ↓ both
VoteSoft > hard
ρ→0Diversity is everything
7Golden rules
🎯
The Foundation Is Set

You now understand why combining models beats any single one, how bagging kills variance, how boosting kills bias, how stacking learns the best blend, and why diversity is the whole game. These techniques power the majority of winning tabular-ML systems in production today.

📚
Where To Go Next

Deep-dive Random Forest and XGBoost / LightGBM / CatBoost individually, then study SHAP for ensemble interpretability and Optuna for hyperparameter search. Practise on Kaggle's Titanic, House Prices and any tabular competition — ensembles dominate the leaderboards.

🎭 End of tutorial · Press to review, or click Restart