Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

3.9 Ensembles: three ways to combine models

🖥️ Lecture slides, Session 18 (Mon Nov 9)

On Friday a forest averaged many trees grown independently. That is one way to combine models. Boosting grows trees in sequence, each one correcting the errors left by the others. Stacking trains a final model to weigh several different models. Combinations often win, and they often win by very little: Feigl et al. (2021) compared random forests, boosted trees and neural networks on stream temperature in ten catchments and found that the choice of inputs mattered far more than the model family. This notebook lets you measure when a combination helps, and why it sometimes cannot.

Learning outcomes. By the end of this notebook you can:

  1. average the probabilities of different models and score the result;

  2. count the errors that models share, and say why those errors limit an ensemble;

  3. write boosting yourself as a loop over residuals, and read its training and held-out errors;

  4. stack models with out-of-fold predictions;

  5. read disagreement between models as a warning about a prediction.

Time: about 15 minutes in pairs. If you run short, skip Part 3.

How this notebook works

Each Your turn cell asks for a few lines of code. Read the hint, write your answer where the cell says, and run it. The cell below it holds a worked solution, hidden until you click ⋯. That hidden cell also checks your answer: it prints correct, or a hint, and if your answer is missing or different it uses the reference result so that the rest of the notebook still runs. Your own answer, if different, is kept under the same name followed by _yours.

The values below are used in several places, so they are defined once. The figure colors stay distinct for color-blind readers (the Okabe-Ito palette).

Notebook Cell

Part 1. Averaging models on the seismic source types

Data: 📍 In-situ sensor · 🪨 Solid Earth · 📈 Seismology

We return to the 4,000 Pacific Northwest events of 3.5 and Friday’s lecture: earthquakes, explosions, surface events and noise windows (Zenodo record 14025693; map in Kharita et al., 2026, Seismica). The split is the canonical one, 3,000 events to train and 1,000 to test. Always guessing one class gives macro-F1 of .10, since the classes are balanced.

Notebook Cell
3000 training events, 1000 test events, 61 waveform features

We fit three different kinds of model and keep their class probabilities on the test events. The boosted model takes about 10 seconds.

Loading...

Your turn (1): average the three models

Compute average_probability, the mean of the three probability arrays, then average_f1, the macro-F1 of the class with the highest mean probability.

Hint: (probabilities["logistic"] + probabilities["forest"] + probabilities["boosted"]) / 3, then classes[average_probability.argmax(axis=1)], then f1_score(truth, ..., average="macro").

Worked solution below (click ⋯ to open it).

Notebook Cell
average_probability: not answered yet. Hint: add the three arrays and divide by 3.
  Using the reference result below.
average_f1: not answered yet. Hint: take argmax across classes, map it to names with classes[...], then score.
  Using the reference result below.
Equal average: macro-F1 0.898. Best single model: 0.898

Your turn (2): which errors do the models share?

An ensemble can only repair errors that its members do not share. wrong below marks, for each model, the test events it gets wrong. Compute all_three_wrong, the number of events that all three misclassify.

Hint: combine the three arrays with &, then use .sum().

{'logistic': 116, 'forest': 114, 'boosted': 102}

Worked solution below (click ⋯ to open it).

Notebook Cell
all_three_wrong: not answered yet. Hint: wrong['logistic'] & wrong['forest'] & wrong['boosted'], then .sum().
  Using the reference result below.
62 events fool all three models
Models agree on 894 events: 6% of them wrong
Models disagree on 106 events: 42% of them wrong

Pause and discuss.

  • Most of the errors are shared. What might those events be, physically? Could a better model fix them?

  • When the three models disagree, the average is wrong far more often. What would you do with those events in an operational catalog?

Points to bring out

Shared errors point to the data rather than the model: events whose waveform features look like another class, or labels that an analyst might revise. No combination of these models can fix those. Disagreement is useful even when the average is not more accurate, because it ranks predictions by how far to trust them, and the low-agreement events are the ones to route to an analyst.

Part 2. Boosting by hand: ground temperature from air temperature

Data: 📍 In-situ sensor · 💧 Land water · 💧 Hydrology & land-surface modeling

Back to the USCRN station WA Spokane 17 SSW in eastern Washington (map in 3.11). The daily maximum ground temperature follows the daily maximum air temperature, so one feature is enough to see each tree’s work. We train on 2015 to 2021 and hold out 2022 to 2024.

A boosted model starts from the mean, fits a small tree to what is still wrong, adds part of that tree’s prediction, and repeats.

Notebook Cell
2550 training days, 1088 held-out days

Your turn (3): the boosting loop

Complete the loop in boost. In each round: compute the residuals of the training days, fit a DecisionTreeRegressor(max_depth=DEPTH) to them, and add RATE times its prediction to both running predictions.

Hint: tree = DecisionTreeRegressor(max_depth=DEPTH, random_state=SEED).fit(fit[["air"]], fit["ground"] - fit_prediction), then fit_prediction += RATE * tree.predict(fit[["air"]]), and the same with held.

Worked solution below (click ⋯ to open it).

Notebook Cell
boost: not the expected result. Hint: the tree is fit to fit['ground'] - fit_prediction; both predictions then add RATE times the tree's output.
  Your answer is kept as boost_yours; the reference is used below.
  1 trees: training error 12.16 °C, held-out error 10.95 °C
  3 trees: training error 7.30 °C, held-out error 6.23 °C
 10 trees: training error 4.06 °C, held-out error 4.08 °C
300 trees: training error 3.68 °C, held-out error 4.27 °C
Notebook Cell
<Figure size 700x380 with 1 Axes>

Pause and discuss.

  • Adding trees to a forest does not hurt it. Why can adding trees to a boosted model hurt?

  • How would you choose the number of trees without looking at the held-out years?

Points to bring out

A forest averages independent trees, so more trees only steady the average. Boosting keeps fitting what remains, and once the signal is gone what remains is noise. The training error keeps falling while the held-out error turns upward after about 10 trees. So the number of trees is a setting to choose by cross-validation inside the training years, with folds that respect time, as in 3.8. In practice use HistGradientBoostingRegressor or HistGradientBoostingClassifier, the same idea with faster trees.

Part 3. Stacking: train a model on the models

Stacking replaces the equal average with a small model that learns how far to trust each member. It must learn from predictions on events the members did not train on, or it would trust the members that memorized their training data most. cross_val_predict gives those out-of-fold predictions. This cell takes about 30 seconds.

(3000, 12) (1000, 12)

Your turn (4): fit the stack

Fit a LogisticRegression(max_iter=5000) on stack_inputs_train and y_train, predict on stack_inputs_test, and compute stack_f1, the macro-F1 on the test events.

Hint: LogisticRegression(max_iter=5000).fit(stack_inputs_train, y_train).predict(stack_inputs_test).

Worked solution below (click ⋯ to open it).

Notebook Cell
stack_f1: not answered yet. Hint: fit on the out-of-fold inputs, predict on the test inputs, then use f1_score with average='macro'.
  Using the reference result below.
Loading...

On this split the boosted model, the equal average and the stack are within .002 of one another, about two events in a thousand, far too small to separate them. That is a useful result. Before reaching for a stack, compare it with its best member and an equal average, inside the training data.

Summary

MethodHow the members differHow they combineMain setting to watchscikit-learn
Voting or averagingdifferent kinds of modelequal vote or mean probabilitywhether the members make different errorsVotingClassifier
Bagging, forestssame model on resampled datavote or meantree sizeBaggingClassifier, RandomForestClassifier
Boostingeach tree fits the remaining errorsweighted sumnumber of trees, learning rateHistGradientBoostingClassifier, AdaBoostClassifier
Stackingdifferent kinds of modela model trained on out-of-fold predictionsleakage from in-sample predictionsStackingClassifier

Next. 3.10 lets a search choose among such models, and asks what it is scored on.