🖥️ Lecture slides, Session 18 (Mon Nov 9)
A validation score only means something once we know what the validation data have in common with the training data. Earth data share a lot: tomorrow resembles today, neighboring grid cells share a climate, and every station records the same earthquake. Shuffle such samples into folds and each validation sample keeps close relatives in training, so the score reports recall of those relatives. This notebook measures that effect three times, on a time series, on a map and on a table of earthquake recordings.
Lab. Start in class on Monday November 9 and finish at home. Individual submission on Canvas, due Monday November 16, 11:59 pm (see the end of this notebook).
Learning outcomes. By the end of this notebook you can:
compare a shuffled split with a split that trains on the past and validates on the future;
put a score next to a baseline that needs no learning;
tell a training choice that improves generalization from one that only fine tunes a score;
build spatial blocks and read how a score changes with block size;
keep all recordings of an event on one side of the split;
choose the split that matches where your model will be used.
Time: about 25 minutes in pairs. Parts 3 and 5 are optional.
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 xarray as xr
# Plotting
import matplotlib.pyplot as plt
# Models, splits and scores (scikit-learn)
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
from sklearn.model_selection import GroupKFold, KFold, TimeSeriesSplit, cross_val_predict, cross_val_scoreThe 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
BLOCK_SIZES = [2, 4, 6] # Part 2: edge of a spatial block, in degrees
BLUE, ORANGE, GREEN, RED, GRAY, MUTED = "#0072B2", "#E69F00", "#009E73", "#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] = referenceNotebook Cell
# Helper: find a course file beside the book, or fetch it from GitHub, and verify it.
BASE_URL = "https://raw.githubusercontent.com/geo-smart/mlgeo-book/main/book/"
FINGERPRINTS = {
"Chapter1-GettingStarted/data/gps_P395_relative_position.csv": "eb22473bbc5565caafbfe1b3b539c65cf88ba3cb23dec07106d81738957a4ff6",
"Chapter2-DataManipulation/snapshots/naturalearth_pnw_map.csv": "7ed9da2e9ac642e9bc39c9d966df9b63bf169d3819ea9c588c56211b59601791",
"Chapter2-DataManipulation/snapshots/cpc_soilw_precl_westUS_1991-2020.nc": "7c8fda8209cfb8cc5fc4c3181382c64b56c2a8ff7971302b689bc4ec8fcf9d7b",
"Chapter2-DataManipulation/snapshots/cpc_westUS_static_1991-2020.nc": "a9108d71d264a3767fe6642f2af69afc332c8fe56743ab4598c216b10775671a",
}
def course_file(relative):
path = Path("..") / relative
if not path.exists():
path = Path(Path(relative).name)
if not path.exists():
urllib.request.urlretrieve(BASE_URL + relative, path)
if hashlib.sha256(path.read_bytes()).hexdigest() != FINGERPRINTS[relative]:
raise ValueError(f"{path} is not the course copy. Delete it, or restore it with git, and run this cell again.")
return pathPart 1. Time: where will a GNSS station be next month?¶
Data: 📍 In-situ sensor · 🪨 Solid Earth · 📐 Geodesy
P395 stands in the Oregon Coast Range above the Cascadia subduction zone, at 45.0223°N, 123.8575°W (NGL station list, as in 1.7). Its daily east position moves at −6.4 mm/yr in the IGS20 frame (NGL MIDAS, also in 1.7): plate motion and plate-boundary deformation, with seasonal wiggles on top. The record runs from 2006 to 2026.
Notebook Cell
gnss = pd.read_csv(course_file("Chapter1-GettingStarted/data/gps_P395_relative_position.csv"))
east = gnss["east_m"].to_numpy() * 1000 # mm, relative to the first day
year = gnss["decimal_year"].to_numpy()Notebook Cell
# Helper: where the station is, and its record.
def plot_station():
coast = pd.read_csv(course_file("Chapter2-DataManipulation/snapshots/naturalearth_pnw_map.csv"))
fig, (left, right) = plt.subplots(1, 2, figsize=(11, 3.4), width_ratios=[1, 2.4])
for _, part in coast[coast["part"] >= 0].groupby(["kind", "part"]):
left.plot(part["lon"], part["lat"], color=MUTED, lw=0.7)
left.plot(-123.8575, 45.0223, "*", ms=16, color=RED)
left.set(xlim=(-126, -116), ylim=(44, 49.5), xlabel="Longitude", ylabel="Latitude", title="P395")
right.plot(year, east, color="0.25", lw=0.7)
right.set(xlabel="Year", ylabel="East position (mm)", title="Daily east position, NGL")
plt.tight_layout()
plt.show()
plot_station()
The task. From the last 60 days, predict the mean position over the next 30 days. We build one sample every 5 days. Neighboring samples share 55 of their 60 history days and 25 of their 30 target days, which makes them strongly correlated by construction, as any windowed series is.
history, horizon, stride = 60, 30, 5
rows = []
for i in range(history, len(east) - horizon, stride):
past = east[i - history:i]
rows.append({"mean_60d": past.mean(), "mean_10d": east[i - 10:i].mean(), "last": east[i - 1],
"slope_60d": np.polyfit(np.arange(history), past, 1)[0],
"season_sin": np.sin(2 * np.pi * year[i]), "season_cos": np.cos(2 * np.pi * year[i]),
"target": east[i:i + horizon].mean(), "year": year[i]})
samples = pd.DataFrame(rows)
FEATURES = ["mean_60d", "mean_10d", "last", "slope_60d", "season_sin", "season_cos"]
X_time, y_time = samples[FEATURES].to_numpy(), samples["target"].to_numpy()
last_value = samples["last"].to_numpy()
GAP = horizon // stride # samples left out between training and validation, so target windows do not overlap
print(f"{len(samples)} samples, {X_time.shape[1]} features")
samples.head(3)1482 samples, 6 features
The same random forest is used in every test below, so any change in the score comes from how we split the samples.
Your turn (1): a shuffled split¶
Question: does the forest forecast the 30-day mean position correctly for samples it was not trained on?
We hold some samples back, train on the rest, and compare the forest’s forecasts with the true 30-day means of the held-back samples. cross_val_score runs this test as a sequence of steps, repeated five times so that every sample is held back exactly once:
shuffle the samples and cut them into 5 folds;
train on 4 folds and forecast the 5th, the validation fold;
average the size of the misses, |forecast − true value|, over the validation samples: the mean absolute error (MAE), in mm;
move on to the next fold and repeat steps 2 and 3.
Store the mean of the five MAEs in shuffled_mae. It reads as the typical forecast miss, so smaller is better.
Hint: -cross_val_score(forest, X_time, y_time, cv=shuffled, scoring="neg_mean_absolute_error").mean(). The minus sign is there because scikit-learn returns minus the error, so that larger is always better.
forest = RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1)
shuffled = KFold(n_splits=5, shuffle=True, random_state=SEED)
shuffled_mae = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
shuffled_mae_sol = -cross_val_score(forest, X_time, y_time, cv=shuffled, scoring="neg_mean_absolute_error").mean()
check("shuffled_mae", globals(), shuffled_mae_sol, "use cv=shuffled in cross_val_score, with the minus sign in front.", tol=0.01)
print(f"Forest, shuffled folds: {shuffled_mae:.2f} mm")shuffled_mae: not answered yet. Hint: use cv=shuffled in cross_val_score, with the minus sign in front.
Using the reference result below.
Forest, shuffled folds: 0.45 mm
# What cross_val_score does, written out: the same five folds, each forest fit and scored by hand.
shuffled_mae_by_hand = np.mean([
mean_absolute_error(
y_time[val],
RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1)
.fit(X_time[train], y_time[train])
.predict(X_time[val])
)
for train, val in shuffled.split(X_time)
])print(f"By hand: {shuffled_mae_by_hand:.2f} mm. cross_val_score: {shuffled_mae:.2f} mm. Same folds, same forests.")By hand: 0.45 mm. cross_val_score: 0.45 mm. Same folds, same forests.
Your turn (2): train on the past, validate on the future¶
Question: how well does the forest forecast days that come after everything it was trained on? That is how a forecast is used.
future runs the same sequence of steps, but each validation fold comes later in time than all its training samples, and gap drops the samples in between whose 30-day windows would overlap. Compute the mean MAE over these folds and store it in future_mae.
Hint: only the cv argument changes.
future = TimeSeriesSplit(n_splits=5, gap=GAP)
future_mae = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
future_mae_sol = -cross_val_score(forest, X_time, y_time, cv=future, scoring="neg_mean_absolute_error").mean()
check("future_mae", globals(), future_mae_sol, "same call as before, with cv=future.", tol=0.01)
print(f"Forest, future folds: {future_mae:.1f} mm")future_mae: not answered yet. Hint: same call as before, with cv=future.
Using the reference result below.
Forest, future folds: 12.4 mm
Your turn (3): a baseline that needs no learning¶
Question: does the forest beat a rule that learns nothing?
Persistence forecasts that the next 30 days will sit where the station was on the last observed day, last_value. On the same future validation folds, compute the MAE of this forecast against the true 30-day means, then average over the folds. Store the result in persistence_mae.
Hint: np.mean([mean_absolute_error(y_time[v], last_value[v]) for _, v in future.split(X_time)]).
persistence_mae = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
persistence_mae_sol = np.mean([mean_absolute_error(y_time[v], last_value[v]) for _, v in future.split(X_time)])
check("persistence_mae", globals(), persistence_mae_sol, "loop over future.split(X_time) and keep only the validation indices.", tol=0.01)
line_mae = -cross_val_score(LinearRegression(), X_time, y_time, cv=future, scoring="neg_mean_absolute_error").mean()
print(pd.Series({"forest, shuffled folds": shuffled_mae, "forest, future folds": future_mae,
"persistence, future folds": persistence_mae, "linear regression, future folds": line_mae}).round(2).to_string())persistence_mae: not answered yet. Hint: loop over future.split(X_time) and keep only the validation indices.
Using the reference result below.
forest, shuffled folds 0.45
forest, future folds 12.37
persistence, future folds 1.17
linear regression, future folds 0.82
Notebook Cell
# Helper: one fold of each split, with the forest's predictions.
def plot_two_splits():
fig, axes = plt.subplots(2, 1, figsize=(10, 5.2), sharex=True, sharey=True)
for ax, split, title in [(axes[0], shuffled, "Shuffled"), (axes[1], future, "Train on the past, validate on the future")]:
fit, val = list(split.split(X_time))[-1]
predicted = RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1).fit(X_time[fit], y_time[fit]).predict(X_time[val])
ax.scatter(samples["year"].iloc[fit], y_time[fit], s=4, color=GRAY, label="training samples")
ax.scatter(samples["year"].iloc[val], y_time[val], s=7, color=BLUE, label="validation samples")
ax.scatter(samples["year"].iloc[val], predicted, s=7, color=ORANGE, marker="x", label="forest")
ax.set(ylabel="East (mm)")
ax.set_title(title, loc="left")
axes[0].legend(frameon=False, loc="lower left")
axes[1].set_xlabel("Year")
plt.tight_layout()
plt.show()
plot_two_splits()
Pause and discuss.
Why does the forest flatten in the lower panel? (Friday’s slide on hot days is the same effect.)
The shuffled score is below 1 mm. What did the forest do to earn it?
Linear regression and persistence need no tuning at all. What physical property of this record do they use?
Points to bring out
A forest can only return averages of training values, so it cannot predict positions beyond the range it has seen, and this station keeps moving. In the shuffled split each validation sample has neighbors in training that share most of its 60 days, so the forest copies them. Persistence and the linear model both use the fact that the position changes slowly and steadily. A flexible model loses here to a one-line rule, which you would never learn from the shuffled score.
Which training choices matter?¶
So far only the split changed. Now we change the training itself, and judge each choice by two scores: shuffled folds, what an unchecked report would show, and future folds, how this station’s forecast is used. A lower error on future folds is better generalization. A small gain from adjusting settings (hyperparameters), with the same model and features, is fine tuning; this is not the fine-tuning of a pretrained network in Chapter 4.
Your turn (4): tune the forest¶
Question: can better settings fix the forest’s forecast?
SETTINGS lists six forests: maximum depth 3, 12 or unlimited, and at least 1 or 20 samples per leaf. For each one, compute the MAE on shuffled folds and on future folds, as in Your turns (1) and (2). Collect them in tuning, a table with one row per setting and the columns shuffled and future.
Hint: pd.DataFrame([{**setting, "shuffled": ..., "future": ...} for setting in SETTINGS]), where each ... is the call from Your turn (1) with RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1, **setting) and the matching cv.
SETTINGS = [{"max_depth": depth, "min_samples_leaf": leaf} for depth in (3, 12, None) for leaf in (1, 20)]
tuning = None # replace None with your tableWorked solution below (click ⋯ to open it).
Notebook Cell
def forest_mae(setting, cv):
model = RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1, **setting)
return -cross_val_score(model, X_time, y_time, cv=cv, scoring="neg_mean_absolute_error").mean()
tuning_sol = pd.DataFrame([{**setting, "shuffled": forest_mae(setting, shuffled), "future": forest_mae(setting, future)}
for setting in SETTINGS])
check("tuning", globals(), tuning_sol, "one row per setting, with columns shuffled and future.",
measure=lambda table: pd.DataFrame(table)[["shuffled", "future"]].to_numpy(dtype=float), tol=0.01)
print(tuning.round(2).to_string(index=False, na_rep="none"))
print(f"\nPersistence, future folds: {persistence_mae:.2f} mm")tuning: not answered yet. Hint: one row per setting, with columns shuffled and future.
Using the reference result below.
max_depth min_samples_leaf shuffled future
3.0 1 3.26 15.54
3.0 20 3.26 15.75
12.0 1 0.46 12.37
12.0 20 0.97 13.49
none 1 0.45 12.37
none 20 0.97 13.49
Persistence, future folds: 1.17 mm
Your turn (5): predict the change, not the position¶
Question: does the forest forecast better if we ask it for something within the range it has seen?
A forest can only return averages of the values it was trained on, and P395 keeps moving to positions it has never occupied. The change over 30 days, however, stays within the range seen in training. So we train the forest on X_change, the same features measured from the last observed day, to forecast y_change, the 30-day mean minus that day. In each future fold: train, forecast the change for the validation samples, add last_value back to get a position, and compute the MAE against the true 30-day mean. Store the mean over the folds in change_mae.
Hint: np.mean([mean_absolute_error(y_time[v], last_value[v] + forest.fit(X_change[f], y_change[f]).predict(X_change[v])) for f, v in future.split(X_change)]).
X_change = np.column_stack([samples["mean_60d"] - last_value, samples["mean_10d"] - last_value,
samples[["slope_60d", "season_sin", "season_cos"]].to_numpy()])
y_change = y_time - last_value # mm moved over the next 30 days, relative to the last observed day
change_mae = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
change_mae_sol = np.mean([mean_absolute_error(y_time[v], last_value[v] + forest.fit(X_change[f], y_change[f]).predict(X_change[v]))
for f, v in future.split(X_change)])
check("change_mae", globals(), change_mae_sol, "fit on X_change and y_change, then add last_value back before scoring.", tol=0.01)
print(pd.Series({"forecast position, best of 6 random forests": tuning["future"].min(),
"forecast change in position, 1 random forest": change_mae,
"forecast position, linear regression": line_mae,
"persistence (last observed position)": persistence_mae}).round(2).to_string())change_mae: not answered yet. Hint: fit on X_change and y_change, then add last_value back before scoring.
Using the reference result below.
forecast position, best of 6 random forests 12.37
forecast change in position, 1 random forest 0.84
forecast position, linear regression 0.82
persistence (last observed position) 1.17
Pause and discuss.
Which moved the future-fold error more, the six settings or the change of target? Which moved the shuffled score more?
Shuffled and future folds pick the same setting here. Would shuffled folds have told you that the random forests forecasting the position are not worth using?
Name one change of target or features in your project that would turn an extrapolation into an interpolation.
Points to bring out
The six settings move the forecast error between 12.4 and 15.8 mm, and none comes near persistence (1.17 mm): no setting lets a forest return a position it has never seen. Predicting the change brings the error to 0.84 mm, close to linear regression (0.82 mm). Both kinds of folds pick the same setting, so here the split did not change the tuning, but only future folds showed that the random forests forecasting the position should not be used. Tuning is worth doing last, on the split that matches use; the large gain came from what the model is asked to predict. Examples in other projects: anomalies instead of absolute values, differences between neighboring stations, quantities scaled by a physical reference.
Part 2. Region: soil moisture on a map¶
Data: 🖥️ Model & simulation · 💧 Land water · 💧 Hydrology & land-surface modeling
On Friday you saw that a random forest predicting from map coordinates scores well until the test moves away from its training cells. Here you make that test yourself. The target is the 1991 to 2020 mean of CPC soil moisture (Fan and van den Dool, 2004) on a 0.5° grid over the western United States. Two feature sets compete: coordinates alone, and climate (precipitation and air temperature means).
One caution: CPC soil moisture is a leaky-bucket model driven by precipitation and temperature, so the climate features nearly contain the answer. Measured soil properties would be harder to predict.
Notebook Cell
grid = xr.open_dataset(course_file("Chapter2-DataManipulation/snapshots/cpc_soilw_precl_westUS_1991-2020.nc"))
static = xr.open_dataset(course_file("Chapter2-DataManipulation/snapshots/cpc_westUS_static_1991-2020.nc"))
monthly = grid.groupby("time.month").mean("time")
lon2d, lat2d = np.meshgrid(grid["lon"].values - 360, grid["lat"].values)
cells = pd.DataFrame({"soil": grid["soilw"].mean("time").values.ravel(), "lon": lon2d.ravel(), "lat": lat2d.ravel(),
"precip": grid["precip"].mean("time").values.ravel(),
"precip_winter": monthly["precip"].sel(month=[12, 1, 2]).mean("month").values.ravel(),
"precip_summer": monthly["precip"].sel(month=[6, 7, 8]).mean("month").values.ravel(),
"air": static["air_clim"].mean("month").values.ravel(),
"air_july": static["air_clim"].sel(month=7).values.ravel(),
"air_january": static["air_clim"].sel(month=1).values.ravel()}).dropna().reset_index(drop=True)
COORDINATES = ["lon", "lat"]
CLIMATE = ["precip", "precip_winter", "precip_summer", "air", "air_july", "air_january"]
soil = cells["soil"].to_numpy()
print(f"{len(cells)} land cells")992 land cells
def pooled_r2(columns, cv, groups=None):
"""R² of a forest over all held-out cells of a split."""
model = RandomForestRegressor(n_estimators=200, random_state=SEED, n_jobs=-1)
return r2_score(soil, cross_val_predict(model, cells[columns], soil, cv=cv, groups=groups))Your turn (6): spatial blocks¶
Question: how do we keep neighboring cells out of each other’s validation?
Cut the map into squares of size degrees and give every cell the label of its square. A split that respects these labels keeps each square entirely in training or entirely in validation. Write block_labels(table, size), which returns one label per cell.
Hint: np.floor(table["lon"] / size) * 1000 + np.floor(table["lat"] / size).
block_labels = None # replace this line with your function: def block_labels(table, size): ...Worked solution below (click ⋯ to open it).
Notebook Cell
def block_labels_sol(table, size):
return np.floor(table["lon"] / size) * 1000 + np.floor(table["lat"] / size)
check("block_labels", globals(), block_labels_sol, "two np.floor calls, one for longitude and one for latitude.",
measure=lambda f: pd.Series(f(cells, 4)).groupby(block_labels_sol(cells, 4)).nunique().to_numpy())
print(f"{pd.Series(block_labels(cells, 4)).nunique()} blocks of 4 degrees")block_labels: not answered yet. Hint: two np.floor calls, one for longitude and one for latitude.
Using the reference result below.
26 blocks of 4 degrees
Notebook Cell
# Helper: the soil moisture field and the 4 degree blocks.
def plot_blocks():
fold = np.zeros(len(cells), dtype=int)
for k, (_, val) in enumerate(GroupKFold(5).split(cells, groups=block_labels(cells, 4))):
fold[val] = k
fig, (left, right) = plt.subplots(1, 2, figsize=(10, 4.6))
for ax, values, cmap, title in [(left, soil, "YlGnBu", "CPC soil moisture, mean 1991 to 2020 (mm)"), (right, fold, "Set2", "4° blocks in five folds")]:
shown = ax.scatter(cells["lon"], cells["lat"], c=values, cmap=cmap, s=26, marker="s", linewidths=0)
ax.set(xlabel="Longitude", ylabel="Latitude", title=title, aspect=1.25)
fig.colorbar(left.collections[0], ax=left, shrink=0.8)
plt.tight_layout()
plt.show()
plot_blocks()
Your turn (7): random cells against whole blocks¶
Question: does each forest still map soil moisture in regions it has not seen?
random_r2 below holds the R² when cells go to folds at random. Compute the R² of each feature set when whole 4° blocks are held out, and store both in the dictionary block_r2. R² = 1 is a perfect map; R² = 0 is no better than the mean everywhere.
Hint: pooled_r2(COORDINATES, GroupKFold(5), block_labels(cells, 4)), and the same with CLIMATE.
random_r2 = {"coordinates": pooled_r2(COORDINATES, KFold(5, shuffle=True, random_state=SEED)),
"climate": pooled_r2(CLIMATE, KFold(5, shuffle=True, random_state=SEED))}
block_r2 = {"coordinates": None, "climate": None} # replace each NoneWorked solution below (click ⋯ to open it).
Notebook Cell
block_r2_sol = {"coordinates": pooled_r2(COORDINATES, GroupKFold(5), block_labels(cells, 4)),
"climate": pooled_r2(CLIMATE, GroupKFold(5), block_labels(cells, 4))}
if None in block_r2.values():
block_r2 = None
check("block_r2", globals(), block_r2_sol, "call pooled_r2 with GroupKFold(5) and groups=block_labels(cells, 4).",
measure=lambda d: [d["coordinates"], d["climate"]], tol=0.01)
ladder = pd.DataFrame({"coordinates": [random_r2["coordinates"]], "climate": [random_r2["climate"]]}, index=["random cells"])
for size in BLOCK_SIZES:
groups = block_labels(cells, size)
ladder.loc[f"{size} degree blocks"] = [pooled_r2(COORDINATES, GroupKFold(5), groups), pooled_r2(CLIMATE, GroupKFold(5), groups)]
ladder.round(2)block_r2: not answered yet. Hint: call pooled_r2 with GroupKFold(5) and groups=block_labels(cells, 4).
Using the reference result below.
Read the table from top to bottom as a ladder of splits: each row asks about ground farther from the training cells. On Friday the field’s correlation fell to .40 at 200 to 300 km, and 4° is about 300 to 440 km here.
Pause and discuss.
Random folds rate the two forests as equal. Which would you use to map a region with no stations? How would you have known?
Stock (2025, Frontiers in Remote Sensing) found that block size mattered more than block shape or the number of folds. What sets the right block size for your own data?
Points to bring out
Coordinates let the forest interpolate between neighbors, which is useful inside a surveyed region and worthless beyond it. Blocks should be at least as large as the distance over which the field stays correlated, and they should resemble the gap between your training data and the places you will predict. No single row is the correct score: each row answers a different question.
Part 3 (optional). Event: many stations, one earthquake¶
Data: 🖥️ Model & simulation · 🪨 Solid Earth · 📈 Seismology
This table is synthetic, so that we know the truth: 60 earthquakes recorded at 15 stations, where log peak ground acceleration follows magnitude and distance, plus an offset shared by all recordings of one event and an offset for each station. A real catalog would have the same structure, as a ground-motion model must predict the next earthquake and has never seen its offset.
Notebook Cell
rng = np.random.default_rng(SEED)
n_events, n_stations = 60, 15
station_x, station_y = rng.uniform(0, 200, n_stations), rng.uniform(0, 200, n_stations)
station_term = rng.normal(0, 0.10, n_stations)
records = []
for event in range(n_events):
magnitude = rng.uniform(4, 7)
x, y = rng.uniform(0, 200), rng.uniform(0, 200)
event_term = rng.normal(0, 0.30)
for station in range(n_stations):
distance = np.hypot(x - station_x[station], y - station_y[station]) + 5
log_pga = 0.6 * magnitude - 1.5 * np.log10(distance) + event_term + station_term[station] + rng.normal(0, 0.15)
records.append({"event": event, "magnitude": magnitude, "distance_km": distance, "log_pga": log_pga})
motions = pd.DataFrame(records)
X_event, y_event = motions[["magnitude", "distance_km"]], motions["log_pga"]
random_event_r2 = cross_val_score(forest, X_event, y_event, cv=KFold(5, shuffle=True, random_state=SEED)).mean()
print(f"{len(motions)} recordings, random folds: R² = {random_event_r2:.2f}")900 recordings, random folds: R² = 0.87
Your turn (8): keep each event whole¶
Question: can the forest predict ground motion for an earthquake it has never seen?
Hold out whole events: all recordings of an earthquake go either to training or to validation, never both. Compute the forest’s R² over these folds and store it in event_r2.
Hint: cross_val_score(forest, X_event, y_event, cv=GroupKFold(5), groups=motions["event"]).mean().
event_r2 = None # replace None with your expressionWorked solution below (click ⋯ to open it).
Notebook Cell
event_r2_sol = cross_val_score(forest, X_event, y_event, cv=GroupKFold(5), groups=motions["event"]).mean()
check("event_r2", globals(), event_r2_sol, "use cv=GroupKFold(5) and pass groups=motions['event'].", tol=0.01)
print(f"Random folds {random_event_r2:.2f}, whole events {event_r2:.2f}")event_r2: not answered yet. Hint: use cv=GroupKFold(5) and pass groups=motions['event'].
Using the reference result below.
Random folds 0.87, whole events 0.65
The magnitude is identical for all recordings of an event, so under random folds the forest recognizes the event and recalls its offset. Hold out whole events and that shortcut is gone. Repeated quarry blasts and aftershock sequences create the same trap for a classifier, which 3.5 declares for its leaderboard tables: they carry no event identifier to group by.
Part 4. Choosing the split¶
Ask what your samples share, then keep it on one side of the line.
| Samples share | Why they are correlated | Validate by | scikit-learn |
|---|---|---|---|
| Time | consecutive samples share weather, season, drift | training on the past, validating on the future | TimeSeriesSplit |
| Location | repeated measurements at one location are near copies | holding out whole locations | GroupKFold |
| Event | one earthquake or storm reaches many instruments | holding out whole events | GroupKFold |
| Region | nearby locations lie on the same smooth field | holding out blocks, as large as the correlation distance | GroupKFold on block labels |
| Rare class and groups | a whole group can land in a fold with no positive cases | holding out groups, with rare cases spread across folds | StratifiedGroupKFold |
Three habits go with this table:
Keep train, validation and test apart. Use cross-validation inside the training data to compare models and settings. Score the test set once, at the end.
Put a baseline next to every score, and use physical units where you can.
Be wary of leave-one-out. It costs one fit per sample, and on correlated data each held-out sample keeps its neighbors in training, so it is the shuffled split at its most optimistic.
Your project. Which row applies to your data? What would the score mean under the split you plan to use? Bring your answer to the data-audit check-in on Mon Nov 16.
Part 5 (optional). An error bar that respects correlation¶
“12 mm” is an estimate too. The bootstrap resamples the validation errors and reads an interval from the spread. Resampling single errors assumes they are independent. These errors are not, since neighboring samples share most of their window, so we also resample blocks of 12 samples (60 days).
errors = np.concatenate([np.abs(y_time[v] - RandomForestRegressor(n_estimators=100, random_state=SEED, n_jobs=-1).fit(X_time[f], y_time[f]).predict(X_time[v]))
for f, v in future.split(X_time)])
draw = np.random.default_rng(0)
single = [draw.choice(errors, len(errors)).mean() for _ in range(2000)]
block_length = 12
n_blocks = int(np.ceil(len(errors) / block_length))
blocked = [np.concatenate([errors[s:s + block_length] for s in draw.integers(0, len(errors) - block_length + 1, n_blocks)])[:len(errors)].mean() for _ in range(2000)]
print(f"Mean error {errors.mean():.1f} mm")
print(f"95% interval, single errors: {np.percentile(single, 2.5):.1f} to {np.percentile(single, 97.5):.1f} mm")
print(f"95% interval, 60-day blocks: {np.percentile(blocked, 2.5):.1f} to {np.percentile(blocked, 97.5):.1f} mm")Mean error 12.4 mm
95% interval, single errors: 12.0 to 12.7 mm
95% interval, 60-day blocks: 11.1 to 13.5 mm
Next. 3.9 combines models, and 3.10 lets a search choose among them. Both use the fair comparison you built here.
Your answers to the discussion questions¶
For the Pause and discuss questions of Parts 1 and 2 (three sets), write a few sentences per question below. Use your own numbers.
Your answers:
Reflect on this assignment¶
As for every assignment in this course (1.8), a few sentences each:
What did you learn from this exercise? Name the scientific or technical idea, with one example from your own work in this notebook.
What did you learn from interacting with agents or chatbots? Say what you asked, what the tool got right, what it got wrong, and how you found out.
What would you suggest to improve this assignment so it meets its learning goals? Be specific.
AI-use disclosure. One or two sentences: which tools you used, for what, and what you verified.
Your three answers and your disclosure:
Submit by Monday November 16, 11:59 pm¶
Rename your notebook 3.8_robust_training_UWNETID.ipynb, choose Kernel, Restart Kernel and Run All Cells, save, and upload it to the Canvas assignment “Lab 3.8: robust training”. Graded: tasks 1 to 7 completed by you (task 8 is optional), the notebook runs from top to bottom, your answers to the discussion questions, and your reflection.