Ensembles: bagging, random forests and gradient boosting
Many weak opinions, combined carefully, beat one strong one
Gradient-boosted trees are the default winner on tabular data in 2026 and random forests are the most forgiving model you can reach for. The math here — variance of an average of correlated predictors, boosting as gradient descent in function space — reappears in deep-learning optimizers (4.5 Optimizers and learning-rate schedules), in self-consistency voting for LLM outputs (8.5 Decoding and sampling) and in agent voting/ensembling patterns (10.5 Agentic workflow patterns).
You'll be able to
- Derive the variance of an average of B correlated predictors and explain why decorrelation is the goal of bagging and random forests
- Explain gradient boosting as functional gradient descent and show that fitting residuals is the squared-loss special case
- Describe what XGBoost, LightGBM and CatBoost each added to plain gradient boosting
- Choose and tune a GBDT sensibly and know when tree ensembles beat deep learning
Key ideas
- Var(average of B models) = ρσ² + (1−ρ)σ²/B: averaging removes the independent part of the variance, correlation ρ sets the floor.
- Bagging trains on bootstrap samples (≈63.2% unique rows; the rest are out-of-bag and give free validation); random forests also sample features per split to decorrelate trees.
- Forests use deep trees and reduce variance; boosting uses shallow trees added sequentially and reduces bias.
Show 4 more key ideas
- Gradient boosting = gradient descent in function space: fit each new tree to pseudo-residuals −∂L/∂F; for squared loss these are plain residuals.
- XGBoost scores trees with a second-order expansion: leaf weight −G/(H+λ) and an explicit split gain; LightGBM adds histogram/leaf-wise speed; CatBoost adds ordered target statistics.
- Tune learning rate + early-stopped number of trees first, then depth/leaves, min child weight, subsampling and regularization.
- GBDTs still beat deep learning on typical tabular data; deep learning wins on perceptual data and with transfer learning.
Suggested path through this lesson
Wisdom of crowds, with a formula
Suppose you have models whose predictions each have variance and pairwise correlation . The variance of their average is
Two lessons fall out immediately. The second term vanishes as , so averaging is free variance reduction. The first term does not vanish: if your models make correlated mistakes, no amount of averaging removes them. Ensembling is therefore a game of decorrelation. Numbers: with , and , the ensemble variance is — a 3× reduction, capped by . This is the bias–variance decomposition of 3.5 Evaluating models: metrics, validation and the bias–variance trade-off put to work: trees have low bias and huge variance, so they are the perfect raw material.
Bagging and random forests
Bagging (bootstrap aggregating) trains each model on a bootstrap sample: draws with replacement from the training points. Each bootstrap sample contains about of the unique points; the other 36.8% are out-of-bag (OOB) and act as a free validation set for that tree. Averaging the predictions (or voting) reduces variance without touching bias.
Random forests add a second source of randomness to push down: at every split, only a random subset of features is considered — typically for classification and for regression. Without this, every tree would grab the same dominant feature at the root and the trees would be highly correlated. Forests use deep, unpruned trees (low bias), hundreds of them (large ), and are remarkably hard to overfit by adding trees: more trees only lowers the term. The main knobs are (max_features) and min_samples_leaf.
Forests also give two kinds of feature importance: mean decrease in impurity (fast, biased) and permutation importance (shuffle a feature on OOB data, measure the drop) — prefer the latter (3.13 Feature engineering, data quality and data-centric ML).
Boosting: fit what is still wrong
Boosting builds an additive model sequentially,
where each is a small tree ("weak learner", depth 3–8) and is the learning rate. At step we would like to minimize . Friedman's insight: treat the vector of training predictions as the parameter and do gradient descent in function space. The negative gradient at the current model is the pseudo-residual
and we fit the tree to the targets (a regression tree, whatever the original task) and take a step .
Math check. For squared loss the pseudo-residual is : the ordinary residual. "Fit a tree to the residuals" is literally a gradient step. For binary log loss with the pseudo-residual is — the same form as the logistic-regression gradient in 3.3 Logistic regression and softmax classification.
Because every tree corrects the previous ensemble, boosting reduces bias (unlike bagging). It can overfit if you add too many trees, so the number of trees is chosen by early stopping on a validation set, and shrinkage (0.01–0.3) trades more trees for better generalization. Stochastic gradient boosting subsamples rows (and columns) per tree, which both speeds things up and decorrelates. AdaBoost, the original boosting algorithm, is the special case of exponential loss, where fitting the gradient becomes re-weighting misclassified points.
XGBoost, LightGBM and CatBoost
XGBoost (2016) replaced the first-order gradient step with a second-order Taylor expansion of the loss, giving every tree a closed-form objective. With and at the current prediction, a tree with leaf weights is scored by
where is the number of leaves. Minimizing over the weights of leaf (with , ) gives
The gain formula replaces Gini/entropy: splits are chosen by how much they reduce the regularized second-order loss, and , are explicit regularizers. XGBoost also learns default directions for missing values and parallelizes split finding.
LightGBM (2017) made boosting fast on big data: histogram-based splits (bin each feature into ≈255 buckets), leaf-wise (best-first) growth instead of level-wise, gradient-based one-side sampling (keep large-gradient rows), and exclusive feature bundling for sparse features. CatBoost (2017) attacked target leakage in categorical encoding with ordered target statistics (each row's encoding uses only "earlier" rows) and ordered boosting, uses symmetric (oblivious) trees that are fast at inference, and has excellent defaults.
When tree ensembles beat deep learning
For typical tabular data — heterogeneous columns, tens to hundreds of thousands of rows, irregular target functions, uninformative features — gradient-boosted trees still beat neural networks on average (Grinsztajn et al., 2022): trees are robust to irrelevant features, naturally model sharp, axis-aligned interactions, and need no scaling or architecture search. Deep learning wins on raw perceptual data (images, audio, text) and whenever pretrained representations can be transferred (5.4 Transfer learning and training CNNs in practice, 7.5 Encoder-only: BERT and friends (and sentence embeddings)). The best of both: feed neural embeddings (of text columns, say) into a GBDT as features.
A practical tuning recipe: start with LightGBM or XGBoost defaults; set a small learning rate (0.03–0.1) and let early stopping choose the number of trees; then tune depth/number of leaves, min_child_weight (leaf size), row and column subsampling (0.7–0.9), and / regularization with a quick random search. Always evaluate with the same cross-validation protocol as your baseline (3.5 Evaluating models: metrics, validation and the bias–variance trade-off).
Where this shows up later
- Cross-validated evaluation and leakage-safe pipelines — 3.5 Evaluating models: metrics, validation and the bias–variance trade-off, 3.13 Feature engineering, data quality and data-centric ML; the full tabular project — 3.14 Project: end-to-end tabular ML with scikit-learn.
- Boosting is gradient descent in function space; the parameter-space version with momentum and Adam is 4.5 Optimizers and learning-rate schedules.
- Averaging predictions returns as self-consistency voting in LLM decoding — 8.5 Decoding and sampling, model ensembling in evaluation — 8.7 Evaluating LLMs, and voting/parallelization patterns in agents — 10.5 Agentic workflow patterns; mixture-of-experts layers combine specialized sub-networks — 7.11 Mixture of Experts.
Common pitfalls (4)
- Using the same rows to train and to estimate forest error instead of OOB or CV data.
- Adding more boosting rounds without early stopping — unlike forests, boosting does overfit with M.
- Target-encoding categoricals on the full training set before boosting: a leakage that CatBoost's ordered statistics exist to prevent.
- Believing random forests cannot overfit at all: adding trees cannot hurt, but tiny leaves and no feature subsampling still can.
Recap: all 7 key points
- Var(average of B models) = ρσ² + (1−ρ)σ²/B: averaging removes the independent part of the variance, correlation ρ sets the floor.
- Bagging trains on bootstrap samples (≈63.2% unique rows; the rest are out-of-bag and give free validation); random forests also sample features per split to decorrelate trees.
- Forests use deep trees and reduce variance; boosting uses shallow trees added sequentially and reduces bias.
- Gradient boosting = gradient descent in function space: fit each new tree to pseudo-residuals −∂L/∂F; for squared loss these are plain residuals.
- XGBoost scores trees with a second-order expansion: leaf weight −G/(H+λ) and an explicit split gain; LightGBM adds histogram/leaf-wise speed; CatBoost adds ordered target statistics.
- Tune learning rate + early-stopped number of trees first, then depth/leaves, min child weight, subsampling and regularization.
- GBDTs still beat deep learning on typical tabular data; deep learning wins on perceptual data and with transfer learning.
Watch
Bootstrapping, feature subsampling and out-of-bag error, visually.
Read
Exercises
- Variance of an average, empirically
Simulate B = 1…200 predictors with σ² = 1 and pairwise correlation ρ ∈ {0, 0.3, 0.7} (use a shared component plus independent noise). Plot the variance of their average against B alongside the formula ρσ² + (1−ρ)σ²/B. Expected: curves flatten at ρ.
- Forest vs boosting on one dataset
On a tabular dataset (e.g. the California housing data in scikit-learn), compare
RandomForestRegressor,HistGradientBoostingRegressorand a ridge baseline with 5-fold CV RMSE. For the boosted model, plot validation error vs number of iterations at learning rates 0.3 and 0.03. Expected: boosting wins with early stopping; the small learning rate needs more trees but ends lower. - Boosting from scratch
Implement gradient boosting for squared loss in 30 lines: start with F₀ = mean(y), loop M times fitting a depth-3
DecisionTreeRegressorto residuals and adding ν·h. Match scikit-learn'sGradientBoostingRegressorwith the same settings. Expected: identical predictions up to floating-point noise.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →