Semester 1 · Week 09
Ensemble methods
- Ch 12 Ensemble Methods
Chapter 12: Ensemble methods
Many models, making different mistakes.
Notes · slide 2
Time: 50 minutes for one chapter. About 25 on bagging, boosting, and stacking, 15 on the worked example, and 10 on choosing and checks.
Say: A single decision tree is fragile. Change the data a little and you get a different tree. Grow it deep and it overfits. Keep it shallow and it underfits. Yet combine trees and you get the most accurate models for tabular data.
Key line: many models, making different mistakes.
Next: why crowds work.
The wisdom of crowds
- 1906: Galton collects about 800 guesses of an ox's weight at a county fair.
- The median guess lands within 1% of the truth. Closer than most individual guesses.
- Individual errors cancel out.
It only works if the models make different errors. Diversity is the whole trick.
Notes · slide 3
Say: In 1906, Francis Galton looked at about 800 guesses of an ox's weight at a county fair. The median guess was within 1% of the true weight, closer than most individuals. Errors in different directions cancelled out.
Key line: it only works if the models make different errors. If they all fail on the same examples, averaging doesn't help.
Ask: "When would a crowd get it badly wrong?" Listen for: when everyone shares the same bias or information.
Next: two ways to get diversity.
Two ways to get diversity
| Strategy | Trains | Mainly reduces |
|---|---|---|
| Bagging | Many models in parallel, on resampled data | Variance |
| Boosting | Models in sequence, each fixing the last | Bias |
Notes · slide 4
Say: Bagging trains many models side by side, each on a resampled copy of the data, and averages them. It mainly reduces variance. Boosting trains models one after another, each fixing the last one's mistakes. It mainly reduces bias.
Say: Connect this to last week's bias-variance trade-off. Bagging tames flexible models that overfit. Boosting builds strength from weak ones.
Next: bagging in detail.
Bagging
Bootstrap aggregating:
- Sample n rows with replacement. Some repeat, some are left out.
- Train a model on that sample.
- Repeat B times.
- Average the predictions, or take a majority vote.
Works best on high-variance learners, such as deep trees.
Notes · slide 5
Say: Bootstrap aggregating. Draw n rows with replacement, so some repeat and some are left out. Train a model. Repeat B times. Average, or take a vote.
Say: If the models' errors were uncorrelated, averaging B of them would divide the variance by B, with no increase in bias. In practice the errors are partly correlated, so the gain is smaller.
Key line: bagging helps most with high-variance learners, such as deep trees.
Next: the random forest.
Random forests
Bagging, plus feature randomness:
- At each split, consider only a random subset of features. About p for classification.
- Without it, every tree picks the same dominant feature at the root. Correlated trees don't cancel errors.
- Feature randomness decorrelates the trees.
Notes · slide 6
Say: A random forest is bagging plus feature randomness. At each split, a tree may only consider a random subset of features, about √p for classification.
Say: Why limit the information? Without it, every tree splits on the same strong feature at the root. The trees end up alike, and their errors don't cancel. Restricting features makes them different.
Say: sklearn's random forest regressor considers all features by default. That's plain bagging unless you set max_features.
Ask: "Why are correlated trees a problem?" Listen for: they make the same mistakes, so averaging doesn't help.
Next: boosting.
Boosting
- Train a weak learner, often a one-split "stump".
- Upweight the examples it got wrong.
- Train the next learner on the reweighted data.
- Combine them as a weighted sum.
That's AdaBoost. Mostly reduces bias.
Notes · slide 7
Say: AdaBoost, the original recipe. Train a weak learner, often a one-split stump. Increase the weight of the examples it got wrong. Train the next learner on the reweighted data, so it focuses on the hard cases. Combine them as a weighted sum.
Key line: each new model works on what the ensemble still gets wrong.
Next: the modern version.
Gradient boosting
Gradient descent, but in function space (Friedman, 2001).
- Each new tree predicts the residuals of the ensemble so far.
- Add it, scaled by a learning rate.
- For other losses, fit the negative gradient instead of the residual.
Each tree is a small step towards lower loss.
Notes · slide 8
Say: Friedman, 2001. Recall gradient descent from week 3: nudge the weights downhill. Gradient boosting nudges a whole function. Each new tree predicts the residuals, what the ensemble still gets wrong. Add it, scaled down by a learning rate.
Say: A smaller learning rate needs more trees and usually generalises better.
Ask: "First tree predicts 300k, true price is 340k. What does the second tree try to predict?" Listen for: the 40k residual.
Next: the two libraries you'll use.
XGBoost and LightGBM
- XGBoost (2016): L1/L2 regularisation on leaves, pruning, native missing values, subsampling, parallel splits. Used by 17 of 29 winning Kaggle solutions published in 2015.
- LightGBM (2017): grows leaf-wise and uses sampling and feature bundling tricks. Much faster on large data.
Notes · slide 9
Say: XGBoost, 2016, engineered gradient boosting. It adds regularisation on leaf values, pruning, built-in handling of missing values, subsampling, and parallel split finding. Its paper reports it in 17 of 29 winning Kaggle solutions published in 2015.
Say: LightGBM, 2017, from Microsoft. It grows the most useful leaf first instead of level by level, and adds sampling and feature-bundling tricks. Much faster on large data.
Key line: on tabular data, benchmark LightGBM before you reach for deep learning.
Next: combining different models.
Stacking
- Train K base models with cross-validation.
- Use their out-of-fold predictions as features.
- Train a meta-learner, often logistic or ridge regression, on those.
It learns which model to trust. It can't fix a weak set of models.
Notes · slide 10
Say: Stacking trains a meta-learner to decide how to combine base models, instead of a fixed average. Get each base model's out-of-fold predictions with cross-validation. Use those as features. Fit a simple model, often ridge or logistic regression, on top.
Say: Out-of-fold matters. Predictions on rows a model trained on are too good, and the meta-learner learns to trust them too much.
Key line: stacking learns which model to trust. It can't fix a weak set of models.
Next: explaining an ensemble.
Feature importance, three ways
| Type | Strength | Weakness |
|---|---|---|
| Impurity | Fast, built in | Biased towards high-cardinality features |
| Permutation | No cardinality bias | Slower, misleads on correlated features |
| SHAP | Per-prediction explanations | Extra library, more compute |
Notes · slide 11
Say: Impurity importance is built in and quick, but it favours features with many distinct values. Permutation importance shuffles one feature and measures the drop in score. No cardinality bias, but slower, and it misleads with correlated features. SHAP explains each prediction, feature by feature, and adds up exactly. Tree models get exact SHAP values quickly.
Key line: when impurity and permutation disagree, trust permutation, and check for correlated features.
Lab: the two methods disagree in this lab. That's worth ten minutes.
Next: the worked example.
Worked example: house prices
2,000 houses, 14 features.
| Model | RMSE | R² | Train time |
|---|---|---|---|
| Random forest | $45,502 | 0.845 | 0.15 s |
| Gradient boosting | $28,595 | 0.939 | 0.47 s |
| XGBoost | $28,873 | 0.938 | 0.68 s |
| LightGBM | $28,323 | 0.940 | 0.06 s |
Boosting beats bagging by about $17,000 here. LightGBM is fastest and best.
Notes · slide 12
Say: 2,000 synthetic houses, 14 features. Random forest RMSE is $45,502. The three boosting methods sit around $28,500. Boosting's bias reduction is worth about $17,000 here.
Say: LightGBM is the most accurate and the fastest, at 0.06 seconds.
Say: Boosting doesn't always win by this much. On many real datasets it wins by a little. Look at the timing column too: time to train is a real cost at scale.
Next: how they get there.
Worked example: how they converge
- LightGBM: $87,831 at 5 trees, $28,323 at 200.
- Random forest: within a few thousand dollars of its best by 25 trees.
Bagging's variance reduction saturates fast. Boosting needs rounds to wear down bias.
Notes · slide 13
Say: Add trees one batch at a time. LightGBM starts at $87,831 with 5 trees and reaches $28,323 at 200. Random forest is within a few thousand dollars of its best by 25 trees.
Key line: bagging's variance reduction levels off quickly. Boosting needs rounds to wear down bias.
Ask: "What does this mean for choosing the number of trees?" Listen for: forests need fewer. Boosting needs more, ideally with early stopping.
Next: does stacking help?
Worked example: stacking loses
- Random forest + LightGBM, with a ridge meta-learner: $29,535.
- Worse than LightGBM alone ($28,323).
- Ridge gives LightGBM a weight of 1.209 and random forest −0.184. It learned to subtract the weaker model.
Adding a much weaker model cost more than it gave.
Notes · slide 14
Say: Stack the random forest and LightGBM with a ridge meta-learner. RMSE is $29,535, worse than LightGBM alone. Ridge weights LightGBM at 1.209 and the forest at −0.184. It learned to subtract the weaker model.
Key line: combining a strong model with a much weaker one isn't guaranteed to beat the strong one alone.
Say: Also on importance: square footage dominates at 0.551. But rooms and school distance outrank condition, even though the price formula weights them differently. Importance shows what the model found useful in this sample, not the formula.
Next: choosing.
Choosing
- Random forest: robust baseline, little tuning, hard to break.
- Boosted trees: usually more accurate on tabular data. Need tuning: learning rate, depth, rounds.
- Start with LightGBM when data is large or time is short.
- Stack only when the last fraction of a percent matters.
Notes · slide 15
Say: Random forest is the robust baseline: little tuning, hard to break. Boosted trees are usually more accurate on tabular data but need tuning: learning rate, depth, and number of rounds. That sensitivity is also why they win once tuned.
Say: Start with LightGBM when the data is large or time is short. Stack only when the last fraction of a percent matters, as in competitions.
Next: the chapter in one idea.
Mental model
- A random forest asks what a hundred independent experts think.
- Gradient boosting asks for the smallest correction to the current best guess.
- Stacking asks which expert is right when, but it's stuck with the experts it invited.
Notes · slide 16
Say: A random forest asks what a hundred independent experts think. Gradient boosting asks for the smallest correction to the current best guess. Stacking asks which expert to trust when, but it's stuck with the experts it invited.
Next: check yourself.
Check yourself
- Why does a random forest restrict features at each split?
- Bagging or boosting for a model with high bias?
- Why train stacking's meta-learner on out-of-fold predictions?
- Your permutation importance says two features matter little, but they're highly correlated. What's going on?
Notes · slide 17
Do: pairs, three minutes, then take answers.
Answers: 1. To make the trees different, so their errors cancel. 2. Boosting. 3. Predictions on rows the base models trained on would leak and make the meta-learner overconfident. 4. Shuffle one and the other still carries the same signal, so each looks unimportant on its own.
Lab: learners expect boosting to win by a lot. It often wins by a little. Use the timing column to talk about cost.
This week
- Read Chapter 12: Ensemble Methods.
- Take the Chapter 12 quiz.
- Run the notebooks: Chapter 12 (opens in a new tab).
- Optional: the further reading for week 9.
Slide 1 of 18: Ensemble methods
Keys: → or Space next · ← back · Home/End · F full screen · N notes. Swipe on touch screens. "Save as PDF" opens the print dialog with one slide per page: choose "Save as PDF" as the printer. "Print handout" adds the speaker notes, in black on white.