Machine Learning Slides 📂 Introduction · 18 of 25 51 min read

Gradient Boosting: Learn From Mistakes, One Tree at a Time

How does gradient boosting turn shallow, weak trees into the most accurate model on tabular data? By having each new tree fit only the residual errors left behind — the negative gradient of the loss. This tutorial walks the full loop with a worked £280k→£400k example, residual-shrinkage bars, loss functions, the learning-rate trade-off, stochastic GB, regularization, LightGBM's leaf-wise growth, and eight golden rules — all with animated diagrams.

📉

Gradient Boosting

Build one strong model from a chain of shallow trees — where every new tree learns only the leftover error of the trees before it, taking small, precise steps down the loss surface.
Fit Residuals Learning Rate Stochastic GB LightGBM

Press Next → or use ← → arrow keys

Section 01

The Idea — Learn Only From Mistakes

The student who studies only what she got wrong
A student sits an exam and scores 60/100. Instead of re-reading the whole syllabus, she studies only the questions she missed. She re-tests, finds the few she still gets wrong, and drills those. Round after round the mistakes shrink — until she's at 98/100.

Gradient Boosting is that study method as an algorithm. Each new tree ignores what the ensemble already predicts well and trains only on the residual errors left behind. Nobody re-teaches the whole problem — each round just corrects what's still wrong.
💡
The One-Sentence Definition

Gradient Boosting is a sequential ensemble of shallow trees where each tree is trained to predict the residual mistakes of all the trees before it — so the ensemble steadily reduces error, correcting bias one small step at a time.

Section 01 · Contrast

Why "Gradient"? · Bagging vs Boosting

📐
The "Gradient" Is The Direction Of Largest Error

The residual a tree fits is really the negative gradient of the loss with respect to the current prediction — the steepest downhill direction. So each tree takes one gradient-descent step, but in function space. Swap the loss and the same machinery handles regression, classification, or ranking.

PropertyBagging (Random Forest)Boosting (Gradient Boosting)
Tree orderParallel · independentSequential · dependent
Each tree trains onRandom bootstrap sampleResiduals of prior trees
Tree depthDeep (low bias, high var)Shallow (depth 3–5)
ReducesVariance onlyBias and variance
ParallelizableYes, triviallyNo, inherently sequential
Section 02 · Algorithm

The Gradient Boosting Loop

🔁 Six Steps, Repeated M Times
1Initialize with the simplest constant — the mean of y (regression) or log-odds (classification): F₀(x).
2Compute residuals for every row: rᵢ = yᵢ − F(xᵢ) — how wrong the model is right now.
3Fit a shallow tree (depth 3–5) to the residuals, not the original labels.
4Add it with shrinkage: Fₘ = Fₘ₋₁ + η·hₘ — scale by learning rate η so no tree dominates.
5Recompute residuals on the updated ensemble — they're now smaller than before.
6Repeat for M trees. Final model: F(x) = F₀ + Σ η·hₘ(x) — just a scaled sum, no voting.
⚠️
No Weighting, No Voting

Unlike AdaBoost's weighted vote, gradient boosting simply adds each scaled tree to the running prediction. The "correction" lives entirely in what each tree is trained on — the residuals.

Section 02 · Diagram

The Sequential Process, Visualized

F₀ = mean(y) £280,000 F₁ = F₀+η·h₁ £291,000 F₂ = F₁+η·h₂ £301,000 Fₘ (converged) ≈ £400,000 ✓ r₁ = +120k r₂ = +109k r₃ = +99k 🌱 Tree h₁ fit to r₁ · depth 3 🌱 Tree h₂ fit to r₂ · depth 3 🌱 Tree h₃ fit to r₃ · depth 3 +η·h₁ +η·h₂ top row = cumulative ensemble · bottom row = shallow tree fit to current residuals
🔗
Each Tree Builds On The Last

The residual flows down to train the next shallow tree; the scaled tree flows back up to update the ensemble. Early trees set the foundation and every later tree refines it — the error-correction chain that gives boosting its power.

Section 03 · Worked Example

Watch One Prediction Climb To The Truth

true value £400k 280k 291k 301k 325k 352k 376k ≈400k boosting rounds →
🏠
A House Worth £400k, One Small Step At A Time

Start at the mean, £280k (residual +£120k). Tree 1 predicts the residual; add η×it → £291k. Tree 2 → £301k. With η = 0.1, each round nudges the prediction a fraction of the remaining error, so after ~100 rounds it lands near £400k. Small, precise steps beat one reckless leap.

Section 03 · Diagram

Residual Error Collapses Each Round

£120k £99k £79k £58k £36k £18k Round 0 + h₁ + h₂ + h₃ + h₄ + h₅
📉
Each Shallow Tree Chops Down The Error

For a single house, the residual falls from £120k → £18k in six rounds. Every tree removes a slice of what's left, so the error decays toward zero. This is the whole method in one picture: relentless, incremental correction.

Section 04 · Maths

Gradient Boosting In Four Equations

1 · Initialize
F₀(x) = argmin_γ Σ L(yᵢ, γ)
The best constant — mean for squared error, log-odds for log-loss.
2 · Pseudo-residual (negative gradient)
rᵢ = −∂L(yᵢ, F(xᵢ)) / ∂F(xᵢ)
For squared error this is exactly the raw residual yᵢ − F(xᵢ).
3 · Update with shrinkage
Fₘ(x) = Fₘ₋₁(x) + η · hₘ(x)
hₘ is the tree fit to the pseudo-residuals; η is the learning rate.
4 · Final ensemble
F(x) = F₀ + Σ η · hₘ(x)
A simple scaled sum of all trees — no weighting, no voting.
🔤
Why "Pseudo"-Residuals?

For squared-error loss the negative gradient is the raw residual y − F. But for log-loss, absolute error, or Huber, the gradient is a different expression. "Pseudo-residual" is the generic name that covers every loss — it's always the negative gradient the next tree chases.

Section 05 · Loss Functions

Swap The Loss, Change The Task

LossTaskPseudo-ResidualCharacter
Squared errorRegression (default)yᵢ − FᵢSensitive to outliers
Absolute errorRegressionsign(yᵢ − Fᵢ)Robust · targets median
HuberRegressionMSE small · MAE largeBest of both worlds
Log-lossClassificationyᵢ − p̂ᵢDefault for probabilities
ExponentialClassificationreduces to AdaBoostVery outlier-sensitive
QuantileRegression intervalsasymmetricPrediction ranges
🎯
One Framework, Many Jobs

Because the tree only ever fits the negative gradient, changing the loss is all it takes to go from house-price regression (squared error) to fraud detection (log-loss) to robust modelling on messy data (Huber) — or even confidence intervals (quantile). Match the loss to your evaluation metric.

Section 06 · Learning Rate

Learning Rate × Trees — The Golden Trade-off

One bold cut, or fifty tiny ones?
Two surgeons must correct a 5 mm misalignment. Surgeon A makes a single bold 5 mm cut — fast, but risky. Surgeon B makes fifty 0.1 mm corrections, checking after each — slower, but far more precise and safe. In complex systems, precision beats speed. A small learning rate is Surgeon B.
The Gold Rule
η × n_estimators ≈ constant
Halve η and double the trees → similar accuracy, smoother fit. η=0.05 × 1000 > η=0.1 × 500.
Friedman (2002)
η < 0.1 + large n_estimators
Consistently beats higher learning rates — the empirical backbone of every tuning guide.
Section 06 · Diagram

Low η Converges Smoothly · High η Overshoots

boosting rounds → prediction target η = 0.3 · fast but jittery η = 0.05 · smooth & stable
Lowering the learning rate…Effect
Trees neededMore (higher n_estimators)
Compute costIncreases
GeneralizationBetter
OverfittingReduced
Section 07 · Stochastic GB

Add Randomness — Stochastic Gradient Boosting

🎯
subsample = 1.0
standard GB
Every tree sees 100% of the rows. Deterministic, but higher overfitting risk on noisy data and slower per tree.
🎲
subsample = 0.7
stochastic GB
Each tree trains on a random 70% of rows (no replacement). Beneficial randomness → lower variance, faster training.
⚖️
The trade
bias ↑ slightly
A touch more bias for a worthwhile drop in variance — and it decorrelates trees, much like Random Forest's row sampling.
🎲
Default To 0.7–0.8

Introduced by Friedman, row subsampling is almost always a net win: it speeds up each round, adds diversity, and improves validation accuracy on real, noisy datasets. Pair it with max_features for feature subsampling too.

Section 08 · Regularization

Six Ways To Stop Overfitting, Ranked

🐢
1 · Learning Rate
Drop η to 0.01–0.05 and always pair with early stopping. The single highest-impact knob.
🌱
2 · max_depth
Keep trees shallow (3–5). Depth > 6 rarely helps and usually memorizes noise.
🎲
3 · subsample
Set 0.6–0.8 for stochastic GB — cheap diversity that lowers variance.
🗂️
4 · max_features
Sample features per split ('sqrt' or ~0.5) to decorrelate the trees further.
🍃
5 · min_samples_leaf
Raise to 5–20 on noisy data so leaves don't fit single outliers.
🛑
6 · Early Stopping
n_iter_no_change=20, validation_fraction=0.1 — halt at the optimal tree count.
⚠️
The Overfitting Trap

Unlike Random Forest — where more trees never hurt — adding trees to gradient boosting will eventually overfit if η isn't low enough. Beyond the optimal point, new trees fit noise in the residuals, not signal. That's why early stopping is non-negotiable.

Section 09 · Two Modes

Regression vs Classification

📈
Regression
GradientBoostingRegressor
Continuous targets. Loss: squared_error, huber, quantile. Pseudo-residual = raw residual yᵢ − Fᵢ. Tasks: prices, energy demand.
🏷️
Classification
GradientBoostingClassifier
Binary / multiclass. Loss: log_loss. Pseudo-residual = yᵢ − p̂ᵢ. Outputs probabilities via predict_proba(). Tasks: fraud, diagnosis.
🔧
Same Engine
only the loss changes
Both fit shallow trees to the negative gradient and add them with shrinkage. Swap the loss and you swap the task.
🧩
One Mental Model For Both

Whether you're predicting a price or a probability, the loop is identical: initialize, compute the gradient, fit a tree to it, add with η, repeat. Only the loss function — and therefore the shape of the pseudo-residual — differs.

Section 10 · Code

sklearn In Practice — Annotated

from sklearn.ensemble import GradientBoostingClassifier

gb = GradientBoostingClassifier(
    n_estimators=500,          # set high — early stopping prunes it
    learning_rate=0.05,        # small steps, better generalisation
    max_depth=4,               # shallow trees prevent overfitting
    min_samples_leaf=10,        # regularise leaf size
    subsample=0.75,            # stochastic GB: 75% rows per tree
    max_features=0.5,           # 50% of features per split
    loss='log_loss',           # classification objective
    validation_fraction=0.1,     # hold-out for early stopping
    n_iter_no_change=20,         # stop after 20 flat rounds
    random_state=42)
gb.fit(X_train, y_train)
print(gb.n_estimators_)   # e.g. 312 — stopped itself · Test AUC ≈ 0.974
🪜
Tune In The Right Order

Fix η → tune max_depth + min_samples_leaf → tune subsample + max_features → then lower η further and add trees. For regression, swap in GradientBoostingRegressor with loss='huber' for outlier-robust fits.

Section 11 · Diagram

Where Gradient Boosting Aims

Random Forest starts here low bias · HIGH variance averaging pulls the scatter inward → Gradient Boosting targets here low bias · LOW variance tight AND on target ✅
🎯
Two Roads To The Bullseye

Random Forest starts accurate but scattered and averages the scatter away (kills variance). Gradient Boosting starts simple but off-centre and iteratively corrects toward the target (kills bias) while shrinkage and shallow trees hold variance down — landing tight and on the bull.

Section 12 · Comparison

Gradient Boosting vs Random Forest

PropertyGradient BoostingRandom Forest
Core ideaSequential error correctionParallel variance averaging
ReducesBias + varianceVariance only
Tree depthShallow (3–5) · weakDeep · complex
ParallelizableNo — sequentialYes — trivially
Overfitting riskHigh — tune carefullyLow — self-regularizing
Tuning sensitivityHigh — many knobsLow — good defaults
Peak tabular accuracyHighest in practiceVery good, rarely highest
Best use caseMax accuracy · competitionsFast, robust baseline
🧭
The Practitioner's Decision Tree

Start with Random Forest. If it misses your accuracy target after basic tuning, move to Gradient Boosting. And if your dataset tops ~100,000 rows, skip straight to LightGBM — sklearn's GB is too slow at that scale.

Section 13 · LightGBM

LightGBM — Same Logic, Built For Scale

Standard GB · level-wise grows every node at each depth · balanced LightGBM · leaf-wise splits the max-gain leaf → deeper, faster
PropertyStandard GBLightGBM
Tree growthLevel-wise (balanced)Leaf-wise (max-gain first)
Split findingExact — every valueHistogram — 256 bins
Speed on 1M rowsSlow10–100× faster
CategoricalsManual encodingNative support
Section 14 · Explainability

Reading Feature Importance

📈
Gain
impurity reduction
Total loss improvement a feature delivers across all its splits. Most informative — but can favour high-cardinality features.
🔢
Split Count
usage frequency
How often the feature is used to split. Fast, but biased toward continuous / high-cardinality features.
🎯
SHAP
gold standard
Game-theory Shapley values — shows exactly how much each feature pushes a specific prediction up or down. Local + global.
🔍
Use SHAP For Anything That Matters

Built-in gain and split-count are fine for a quick look, but they can mislead with correlated features. For stakeholder reports, audits, or production monitoring, SHAP (TreeExplainer) is the trustworthy, direction-aware choice.

Section 15 · Golden Rules

Eight Non-Negotiable Rules

🏅 Gradient Boosting, Distilled
1Always use early stopping. Set n_iter_no_change=20 — never hand-pick n_estimators.
2Start with a low learning rate (0.05 or less). η=0.01 × 3000 trees beats η=0.1 × 300.
3Keep trees shallow. max_depth=3 is a robust default; rarely exceed 6.
4Enable stochastic GB. subsample=0.7–0.8 adds diversity and reduces variance.
5Use LightGBM above ~50k rows. Same accuracy, 10–100× the speed.
6Tune in order: η → depth & leaf → subsample & features → lower η again.
7Match loss to metric. Optimizing MSE but judging MAE means optimizing the wrong thing.
8Never scale features. Tree splits are scale-invariant — StandardScaler just wastes time.
Wrap-Up

You Now Own Gradient Boosting

r=y−FFit the residual
−∇L= negative gradient
η↓+ trees + early stop
3–5Shallow tree depth
0.7Stochastic subsample
SHAPTrustworthy importance
🎯
The Through-Line

Gradient boosting turns a chain of weak, shallow trees into a champion by having each one descend the loss gradient — fitting the residual mistakes of the trees before it. Shrinkage keeps the steps small, shallow trees and subsampling keep variance down, and early stopping calls it at the right moment.

📚
Where To Go Next

Compare XGBoost (regularized, second-order), LightGBM (leaf-wise, fast) and CatBoost (native categoricals). Tune with Optuna, explain with SHAP, and practise on Kaggle's tabular competitions — this family rules them.

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