🖥️ 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:
average the probabilities of different models and score the result;
count the errors that models share, and say why those errors limit an ensemble;
write boosting yourself as a loop over residuals, and read its training and held-out errors;
stack models with out-of-fold predictions;
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.
# Data handling
import hashlib
import urllib.request
from pathlib import Path
import numpy as np
import pandas as pd
import pooch
# Plotting
import matplotlib.pyplot as plt
# Models and scores (scikit-learn)
from sklearn.datasets import make_classification # synthetic stand-in if Zenodo cannot be reached
from sklearn.ensemble import HistGradientBoostingClassifier, RandomForestClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import f1_score, mean_absolute_error
from sklearn.model_selection import cross_val_predict, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeRegressorThe 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).
SEED = 42
SPLIT_SEED = 2026 # the canonical split of notebook 3.5
RATE, DEPTH = 0.3, 2 # Part 2: each boosting tree is shallow, and only part of its correction is kept
ROUNDS = 300
BLUE, RED, GRAY, MUTED = "#0072B2", "#D55E00", "#b8b1a4", "#6e675c"
plt.rcParams.update({"font.size": 12, "axes.spines.top": False, "axes.spines.right": False})Notebook Cell
# Helper: compare an answer with a reference. If the answer is missing or different, print a hint and use the
# reference so the cells below still run; a different answer is kept as <name>_yours.
def check(name, ns, reference, hint, measure=None, tol=1e-3):
measure = measure or (lambda value: np.asarray(value, dtype=float))
yours = ns.get(name)
if yours is None or (hasattr(yours, "__len__") and len(yours) == 0):
print(f"{name}: not answered yet. Hint: {hint}\n Using the reference result below.")
else:
try:
ok = np.allclose(measure(yours), measure(reference), atol=tol)
except Exception:
ok = False
if ok:
print(f"{name}: correct")
return
print(f"{name}: not the expected result. Hint: {hint}\n Your answer is kept as {name}_yours; "
"the reference is used below.")
ns[f"{name}_yours"] = yours
ns[name] = referencePart 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
SEISMIC_FILES = {
"1000_earthquakes_physical_features.csv": "md5:28129c8dd1b3e14f655d489577b841b5",
"1000_explosion_physical_features.csv": "md5:af1342d32e163e961e043364136359b0",
"1000_noise_physical_features.csv": "md5:16cdb992fed6cf6273d5624f5df905da",
"1000_surface_physical_features.csv": "md5:9a2c2643030cf058704d68e130654e9d",
}
try:
tables = [pd.read_csv(pooch.retrieve(url=f"https://zenodo.org/api/records/14025693/files/{name}/content",
known_hash=checksum, fname=name, path=pooch.os_cache("mlgeo")), index_col=0)
for name, checksum in SEISMIC_FILES.items()]
seismic = pd.concat(tables, ignore_index=True).dropna(axis=1)
X = seismic.drop(columns=["source", "serial_no"])
y = seismic["source"]
except Exception as error:
print(f"Zenodo could not be reached ({error}). Using SYNTHETIC events: the scores below will differ from the text.")
values, codes = make_classification(n_samples=4000, n_features=61, n_informative=20, n_classes=4, random_state=SEED)
X = pd.DataFrame(values, columns=[f"feature_{i}" for i in range(61)])
y = pd.Series(np.array(["earthquake", "explosion", "noise", "surface event"])[codes])
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=SPLIT_SEED, stratify=y)
truth = y_test.to_numpy()
print(f"{len(X_train)} training events, {len(X_test)} test events, {X.shape[1]} waveform features")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.
members = {"logistic": make_pipeline(StandardScaler(), LogisticRegression(max_iter=5000)),
"forest": RandomForestClassifier(n_estimators=300, random_state=SEED, n_jobs=-1),
"boosted": HistGradientBoostingClassifier(random_state=SEED)}
probabilities = {name: model.fit(X_train, y_train).predict_proba(X_test) for name, model in members.items()}
classes = members["forest"].classes_
labels = {name: classes[p.argmax(axis=1)] for name, p in probabilities.items()}
macro_f1 = {name: f1_score(truth, labels[name], average="macro") for name in members}
pd.Series(macro_f1).round(3).to_frame("macro-F1, test events")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").
average_probability = None # replace None with your expression
average_f1 = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
average_probability_sol = (probabilities["logistic"] + probabilities["forest"] + probabilities["boosted"]) / 3
average_f1_sol = f1_score(truth, classes[average_probability_sol.argmax(axis=1)], average="macro")
check("average_probability", globals(), average_probability_sol, "add the three arrays and divide by 3.")
check("average_f1", globals(), average_f1_sol, "take argmax across classes, map it to names with classes[...], then score.")
print(f"Equal average: macro-F1 {average_f1:.3f}. Best single model: {max(macro_f1.values()):.3f}")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().
wrong = {name: labels[name] != truth for name in members}
print({name: int(w.sum()) for name, w in wrong.items()})
all_three_wrong = None # replace None with your expression{'logistic': 116, 'forest': 114, 'boosted': 102}
Worked solution below (click ⋯ to open it).
Notebook Cell
all_three_wrong_sol = int((wrong["logistic"] & wrong["forest"] & wrong["boosted"]).sum())
check("all_three_wrong", globals(), all_three_wrong_sol, "wrong['logistic'] & wrong['forest'] & wrong['boosted'], then .sum().")
print(f"{all_three_wrong} events fool all three models")
agree = (labels["logistic"] == labels["forest"]) & (labels["forest"] == labels["boosted"])
average_labels = classes[average_probability.argmax(axis=1)]
print(f"Models agree on {agree.sum()} events: {(average_labels != truth)[agree].mean():.0%} of them wrong")
print(f"Models disagree on {(~agree).sum()} events: {(average_labels != truth)[~agree].mean():.0%} of them wrong")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
SNAPSHOTS = Path("../Chapter2-DataManipulation/snapshots")
BASE_URL = "https://raw.githubusercontent.com/geo-smart/mlgeo-book/main/book/Chapter2-DataManipulation/snapshots/"
FINGERPRINTS = {
"uscrn_WA_Spokane_17_SSW_2015-2024.txt": "115f60bc36f8aed6ea8d916da42b5e14bb0a5361ecbf055b6cbbedba64dc994e",
"uscrn_daily01_HEADERS.txt": "dde1b4d78d6b68b9a558d042876340c0476b73c962896ff1b152e8e49379946e",
}
def course_file(name):
path = SNAPSHOTS / name
if not path.exists():
path = Path(name)
if not path.exists():
urllib.request.urlretrieve(BASE_URL + name, path)
if hashlib.sha256(path.read_bytes()).hexdigest() != FINGERPRINTS[name]:
raise ValueError(f"{path} is not the course copy. Delete it, or restore it with git, and run this cell again.")
return path
columns = course_file("uscrn_daily01_HEADERS.txt").read_text().splitlines()[1].split()
station = pd.read_csv(course_file("uscrn_WA_Spokane_17_SSW_2015-2024.txt"), sep=r"\s+", names=columns, dtype={"LST_DATE": str},
na_values=[-9999, -99, -9999.0, -99.0, -99.000])
station["date"] = pd.to_datetime(station["LST_DATE"])
surface = station.set_index("date")[["T_DAILY_MAX", "SUR_TEMP_DAILY_MAX"]].dropna()
surface.columns = ["air", "ground"]
fit, held = surface[:"2021"], surface["2022":]
print(f"{len(fit)} training days, {len(held)} held-out days")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.
def boost(fit, held, rounds):
fit_prediction = np.full(len(fit), fit["ground"].mean())
held_prediction = np.full(len(held), fit["ground"].mean())
errors = []
for _ in range(rounds):
# your code here: three lines (fit a tree to the residuals, update fit_prediction, update held_prediction)
errors.append((mean_absolute_error(fit["ground"], fit_prediction), mean_absolute_error(held["ground"], held_prediction)))
return np.array(errors)Worked solution below (click ⋯ to open it).
Notebook Cell
def boost_sol(fit, held, rounds):
fit_prediction = np.full(len(fit), fit["ground"].mean())
held_prediction = np.full(len(held), fit["ground"].mean())
errors = []
for _ in range(rounds):
tree = DecisionTreeRegressor(max_depth=DEPTH, random_state=SEED).fit(fit[["air"]], fit["ground"] - fit_prediction)
fit_prediction += RATE * tree.predict(fit[["air"]])
held_prediction += RATE * tree.predict(held[["air"]])
errors.append((mean_absolute_error(fit["ground"], fit_prediction), mean_absolute_error(held["ground"], held_prediction)))
return np.array(errors)
check("boost", globals(), boost_sol, "the tree is fit to fit['ground'] - fit_prediction; both predictions then add RATE times the tree's output.",
measure=lambda f: f(fit, held, 10)[-1], tol=0.01)
errors = boost(fit, held, ROUNDS)
for r in (1, 3, 10, 300):
print(f"{r:3d} trees: training error {errors[r - 1, 0]:.2f} °C, held-out error {errors[r - 1, 1]:.2f} °C")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
# Helper: training and held-out error against the number of trees.
def plot_boosting():
fig, ax = plt.subplots(figsize=(7, 3.8))
rounds = np.arange(1, len(errors) + 1)
ax.plot(rounds, errors[:, 0], color=GRAY, lw=2.5, label="training years")
ax.plot(rounds, errors[:, 1], color=BLUE, lw=2.5, label="held-out years")
ax.set(xscale="log", xlabel="Trees added", ylabel="Mean absolute error (°C)", ylim=(3, 12))
ax.legend(frameon=False)
plt.tight_layout()
plt.show()
plot_boosting()
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.
out_of_fold = {name: cross_val_predict(model, X_train, y_train, cv=3, method="predict_proba") for name, model in members.items()}
stack_inputs_train = np.hstack(list(out_of_fold.values()))
stack_inputs_test = np.hstack(list(probabilities.values()))
print(stack_inputs_train.shape, stack_inputs_test.shape)(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).
stack_f1 = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
stack_f1_sol = f1_score(truth, LogisticRegression(max_iter=5000).fit(stack_inputs_train, y_train).predict(stack_inputs_test), average="macro")
check("stack_f1", globals(), stack_f1_sol, "fit on the out-of-fold inputs, predict on the test inputs, then use f1_score with average='macro'.")
summary = pd.Series({**macro_f1, "equal average": average_f1, "stack": stack_f1}).round(3)
summary.to_frame("macro-F1, test events")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.
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¶
| Method | How the members differ | How they combine | Main setting to watch | scikit-learn |
|---|---|---|---|---|
| Voting or averaging | different kinds of model | equal vote or mean probability | whether the members make different errors | VotingClassifier |
| Bagging, forests | same model on resampled data | vote or mean | tree size | BaggingClassifier, RandomForestClassifier |
| Boosting | each tree fits the remaining errors | weighted sum | number of trees, learning rate | HistGradientBoostingClassifier, AdaBoostClassifier |
| Stacking | different kinds of model | a model trained on out-of-fold predictions | leakage from in-sample predictions | StackingClassifier |
Next. 3.10 lets a search choose among such models, and asks what it is scored on.