A researcher trained five networks on five geoscience problems and reports a result for each. Each run has one hidden error. The researcher’s code runs as written, and its evidence (learning curves, confusion matrices, forecasts against observations) is rendered below each case. Your job, for each case:
Diagnose. Name the cause from the evidence, in one sentence, before opening any code.
Fix. Edit the function
c<k>_fix()so the pipeline no longer has the error.Check. Run the cell Evaluate your fix. It tests the numbers your fix produces against the success test stated in the case’s context card (not your code), and prints PASS or FAIL.
As written, every Evaluate your fix cell prints FAIL, because c<k>_fix() still holds the researcher’s pipeline. Our fix (c<k>_our_fix(), a separate function, so it never replaces yours) and a What went wrong box follow each case; both are folded.
Words used here. The researcher is the fictional scientist whose code, evidence and claim you are given; the error is in their run. Your fix is what you write in c<k>_fix(). Our fix is one worked solution, folded until you open it; other fixes can pass the same test. Reference run (case 5 only) is the same model, data and seed trained with the loop you wrote in 4.7 section 2.4: a control experiment that shows what a correct run of this model gives.
Learning outcomes. After the five cases you can:
read learning curves, a confusion matrix and an error-against-time plot as evidence for one specific error;
link each error to the training and evaluation decisions of 4.7 and to items of the rubric;
state, before running it, which number would show that a fix worked, and test it.
| Case | Geoscience system | What the researcher shows you |
|---|---|---|
| 1 | Local earthquakes at one seismic station | A detector that scores 0.97 on its test set |
| 2 | Igneous rocks of a continental arc | The network calls every rock granite |
| 3 | A volcano during a seismic swarm | A swarm detector with 98% accuracy, ready for the observatory |
| 4 | A GNSS station moving with its plate | A GNSS forecaster that beats persistence, until it does not |
| 5 | Igneous rocks along a differentiation trend | The training loss climbs back up |
In class (lecture 25). Teams of 3 or 4. For each case the slides show the context card and the evidence figure; you have 4 minutes to name the cause, propose a fix, and say which number would show the fix worked. One point for each. Then the reveal.
Alone. Run the setup cell, then any case: each case needs only the setup cell and its own cells (all its names start with c1_ to c5_). The whole notebook runs in under a minute on a laptop CPU; case 3, the longest, takes 20 to 35 s, each other case under 10 s. All data are synthetic, from mlgeo_synth, so the true cause of each error is known.
Setup¶
The shared training loop of 4.7 (one_epoch, train), a plot of the learning curves (plot_curves) and one line of an evaluation table (check). Every case uses them.
# Shared setup cell for the "What went wrong?" notebook (4.7 game). Every case uses it:
# the training loop of 4.7 (one_epoch, train), a plot of the learning curves (plot_curves)
# and one line of an evaluation table (check).
import time
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import mlgeo_synth # the course's synthetic geoscience data (seismograms, rock tables, GNSS)
device = torch.device("cpu") # every case is sized for a laptop CPU
torch.set_num_threads(4)
plt.rcParams.update({"font.size": 14, "axes.titlesize": 15, "legend.fontsize": 12}) # large fonts for the slides
def one_epoch(model, opt, criterion, X, y, batch_size, g):
"""One pass over the training samples in a new random order; one update per batch (4.7 section 2.4).
model, opt, criterion: the network, its optimizer and the loss function.
X, y: the training samples (n_samples, ...) and their targets (n_samples, ...), as tensors.
batch_size: number of samples per update; g: the random generator that sets the order.
Returns nothing; it updates the weights of model in place.
"""
order = torch.randperm(len(X), generator=g) # sample indices 0 to n_samples-1, shuffled
for i in range(0, len(X), batch_size):
idx = order[i:i + batch_size] # the samples of this batch (the last one may be smaller)
# the steps of one update, as in 4.7 section 2.4
opt.zero_grad()
loss = criterion(model(X[idx]), y[idx]) # forward pass and mean loss over the batch
loss.backward()
opt.step()
def train(model, Xtr, ytr, Xva, yva, criterion, epochs=30, lr=1e-3, batch_size=128,
optimizer="adam", seed=0, keep_best=True, epoch_fn=None):
"""The 4.7 loop: learning curves every epoch, and the weights of the best validation epoch kept.
model: the network to train (its weights change in place).
Xtr, ytr: training samples and targets; Xva, yva: validation samples and targets (tensors).
criterion: the loss, e.g. nn.CrossEntropyLoss() (in nats: natural-log units; ln 3 = 1.10 is the
loss of guessing among 3 classes) or nn.MSELoss() (target units squared).
epochs, lr, batch_size, optimizer ("adam" or "sgd"), seed: the training settings.
keep_best: if True, the model ends with the weights of the epoch of lowest validation loss.
epoch_fn: a function with the arguments of one_epoch that replaces it (None: one_epoch).
Returns hist, a dict: "train_loss" and "val_loss" (one value per epoch) and "best_epoch"
(the epoch of lowest validation loss, counted from 0).
"""
epoch_fn = epoch_fn or one_epoch
torch.manual_seed(seed)
opt = {"adam": torch.optim.Adam, "sgd": torch.optim.SGD}[optimizer](model.parameters(), lr=lr)
g = torch.Generator().manual_seed(seed) # sets the order of the samples in every epoch
hist = {"train_loss": [], "val_loss": [], "best_epoch": None}
best, best_state = np.inf, None
for epoch in range(epochs):
# update the weights on the training samples
model.train()
epoch_fn(model, opt, criterion, Xtr, ytr, batch_size, g)
# the learning curves: loss on all training and all validation samples, weights frozen
model.eval()
with torch.no_grad():
hist["train_loss"].append(criterion(model(Xtr), ytr).item())
hist["val_loss"].append(criterion(model(Xva), yva).item())
# checkpoint: keep a copy of the weights whenever the validation loss reaches a new low
if hist["val_loss"][-1] < best:
best, hist["best_epoch"] = hist["val_loss"][-1], epoch
best_state = {k: v.clone() for k, v in model.state_dict().items()}
if keep_best and best_state is not None:
model.load_state_dict(best_state) # return to the weights of the best validation epoch
return hist
def plot_curves(hist, title="", ax=None, logy=False):
"""Plot the training and validation loss against epoch.
hist: the dict returned by train(); title: printed at the top left of the panel.
ax: the panel to draw in (None: a new figure); logy: logarithmic loss axis if True.
Returns the panel (matplotlib Axes).
"""
ax = ax or plt.subplots(figsize=(7, 4))[1]
ax.plot(hist["train_loss"], lw=2.5, label="training")
ax.plot(hist["val_loss"], lw=2.5, ls="--", label="validation")
if logy:
ax.set_yscale("log")
ax.set_xlabel("epoch"); ax.set_ylabel("loss"); ax.set_title(title, loc="left")
ax.legend(); ax.grid(alpha=0.3)
return ax
def check(name, value, target, passed):
"""Print one line of the evaluation table: the number, the target, PASS or FAIL.
name: what is measured; value: the number, already formatted as text; target: the
success test, as text; passed: True if the number meets the target.
Returns passed, so that a case can collect its lines and require all of them.
"""
print(f"{name:45s} {value:>10} target {target:<22s} {'PASS' if passed else 'FAIL'}")
return passedCase 1: A detector that scores 0.97 on its test set¶
A researcher trained an earthquake detector for one seismic station. Before using it on the continuous record, they show you this.
| Geoscience system | Local earthquakes (magnitude 1 to 4, 5 to 80 km away) recorded by one vertical-component seismometer, in background noise whose spectrum changes from record to record (power falls as , with between 0.5 and 2). Dominant frequency of the earthquakes: 2 to 8 Hz. Signal-to-noise ratio (SNR, peak earthquake amplitude over noise standard deviation): 0.5 to 20. |
| Data | 2000 records of 30 s at 25 Hz: 1000 contain an earthquake, 1000 contain only noise (mlgeo_synth.seismogram_dataset, seed 1). To get more training samples, each record is cut into 5 windows of 25 s, shifted by 0.5 s: 10 000 windows. |
| Input and target | Input: the amplitude spectrum of one window, log10, averaged in 20 frequency bands from 0.5 to 12 Hz, with its mean removed (so the amplitude scale is dropped). Target: earthquake (1) or noise (0). |
| How it was split | The 10 000 windows were shuffled and split 60 / 20 / 20 into training (6000), validation (2000) and test (2000) windows. |
| New events | 1000 records the station recorded later (500 earthquakes, 500 noise; seed 2), cut into windows the same way (5000 windows). The researcher computed this score but did not use it for any choice. |
| Model | Fully connected network 20 → 64 → 64 → 2 with ReLU; inputs standardized with the mean and standard deviation of the training windows. |
| How it was trained | Cross-entropy loss, Adam, learning rate 0.001, batch of 64, 60 epochs, seed 0; the epoch with the lowest validation loss is kept. |
| The researcher’s claim | “Validation accuracy 0.962 and test accuracy 0.971: the detector finds earthquakes even when they are below the noise level.” |
| Success test for your fix | No record has windows in both the training and the validation set; the validation accuracy and the new-events accuracy agree within 0.06; the new-events accuracy does not drop more than 0.06 below the researcher’s; the new-events accuracy is the number you report. |
# Case 1: the researcher's pipeline, as run
c1_FS, c1_NWIN, c1_SHIFT_S, c1_WIN_S = 25, 5, 0.5, 25 # Hz, windows per record, shift (s), window (s)
c1_WIN = int(c1_WIN_S * c1_FS) # 625 samples per window
# synthetic records: 30 s at 25 Hz, noise power falling as f^-a with a from 0.5 to 2, earthquakes of 2 to 8 Hz
c1_KW = dict(fs=c1_FS, duration_s=30, noise_color_range=(0.5, 2.0), f0_range=(2.0, 8.0))
# 2000 records of 30 s (1000 earthquakes, 1000 noise), and the 1000 records recorded later (new events)
# each set: records (n_records, 750 samples), labels (1 earthquake, 0 noise), one dict of source parameters per record
c1_rec_X, c1_rec_y, c1_meta = mlgeo_synth.seismogram_dataset(n_events=1000, n_noise=1000, seed=1, **c1_KW)
c1_new_X, c1_new_y, c1_new_meta = mlgeo_synth.seismogram_dataset(n_events=500, n_noise=500, seed=2, **c1_KW)
c1_rec_snr = np.array([m.get("snr", np.nan) for m in c1_meta]) # SNR of each record; NaN for noise records
c1_new_snr = np.array([m.get("snr", np.nan) for m in c1_new_meta])
def c1_augment(X, y):
"""Cut 5 windows of 25 s from each 30-s record, shifted by 0.5 s.
X: (n_records, 750) records at 25 Hz; y: (n_records,) labels, 1 earthquake, 0 noise.
Returns the windows (5 * n_records, 625), their labels, and the index of the record each window comes from."""
starts = (np.arange(c1_NWIN) * c1_SHIFT_S * c1_FS).astype(int) # samples 0, 12, 25, 37, 50
# stack to (n_records, 5, 625), then one row per window
W = np.stack([X[:, s:s + c1_WIN] for s in starts], axis=1).reshape(-1, c1_WIN)
return W, np.repeat(y, c1_NWIN), np.repeat(np.arange(len(X)), c1_NWIN)
c1_freq = np.fft.rfftfreq(c1_WIN, 1 / c1_FS) # 313 frequencies of one window's spectrum, 0 to 12.48 Hz
c1_edges = np.geomspace(0.5, 12.0, 21) # 21 log-spaced edges: 20 frequency bands (Hz)
def c1_features(W):
"""log10 amplitude spectrum of each window in 20 bands, mean removed.
W: (n_windows, 625) windows. Returns (n_windows, 20) log10 band amplitudes, float32."""
A = np.abs(np.fft.rfft(W * np.hanning(W.shape[1]), axis=1)) # Hann taper, amplitude spectrum: (n_windows, 313)
# mean amplitude in each band, log10: (n_windows, 20)
S = np.log10(np.stack([A[:, (c1_freq >= a) & (c1_freq < b)].mean(1)
for a, b in zip(c1_edges[:-1], c1_edges[1:])], axis=1))
return (S - S.mean(1, keepdims=True)).astype(np.float32) # remove each window's mean
def c1_fit(Ftr, ytr, Fva, yva, epochs=60, seed=0):
"""Standardize on the training windows, train the 20-64-64-2 network with train(), keep the best epoch.
Ftr, ytr: training features (n, 20) and labels; Fva, yva: validation features and labels.
Returns a dict: "model", "hist" (the curves from train()), "predict" (features -> 0/1 labels)."""
mu, sd = Ftr.mean(0), Ftr.std(0) # mean and std of each band over the training windows
z = lambda F: torch.tensor((F - mu) / sd) # standardize any features with the training mean and std
torch.manual_seed(seed) # random starting weights, recorded seed
model = nn.Sequential(nn.Linear(Ftr.shape[1], 64), nn.ReLU(),
nn.Linear(64, 64), nn.ReLU(), nn.Linear(64, 2)) # 20 bands -> 2 scores (noise, earthquake)
# cross-entropy, Adam, learning rate 0.001, batches of 64 windows; the lowest-validation-loss epoch is kept
hist = train(model, z(Ftr), torch.tensor(ytr), z(Fva), torch.tensor(yva), nn.CrossEntropyLoss(),
epochs=epochs, lr=1e-3, batch_size=64, seed=seed)
def predict(F):
"""Features (n, 20) -> predicted labels (n,), 1 earthquake, 0 noise."""
with torch.no_grad():
return model(z(F)).argmax(1).numpy()
return {"model": model, "hist": hist, "predict": predict}
def c1_accuracy(predict, F, y):
"""Fraction of windows whose predicted label equals y. F: (n, 20) features; y: (n,) labels."""
return float((predict(F) == y).mean())
def c1_detected_by_snr(predict, F, y, snr_of_window, bins=(0.5, 1, 2, 5, 20)):
"""Fraction of earthquake windows called 'earthquake', in bins of SNR.
snr_of_window: (n,) SNR of the record each window was cut from (NaN for noise). Returns one fraction per bin."""
hit = predict(F) == 1 # True where the window is called 'earthquake'
return [hit[(y == 1) & (snr_of_window >= a) & (snr_of_window < b)].mean() for a, b in zip(bins[:-1], bins[1:])]
# the researcher's pipeline, as run
c1_W, c1_yw, c1_rec = c1_augment(c1_rec_X, c1_rec_y) # 10000 windows, their labels, the record of each
c1_F = c1_features(c1_W) # (10000, 20) features
c1_order = np.random.default_rng(0).permutation(len(c1_F)) # shuffle all windows
# split 60/20/20: indices of 6000 training, 2000 validation and 2000 test windows
c1_tr, c1_va, c1_te = np.split(c1_order, [int(0.6 * len(c1_F)), int(0.8 * len(c1_F))])
c1_res = c1_fit(c1_F[c1_tr], c1_yw[c1_tr], c1_F[c1_va], c1_yw[c1_va]) # train; epoch chosen on validation
c1_new_W, c1_new_yw, c1_new_rec = c1_augment(c1_new_X, c1_new_y) # new events, cut the same way: 5000 windows
c1_new_F = c1_features(c1_new_W) # (5000, 20) features
# the numbers the researcher reports: accuracy (fraction of windows) on each set
c1_scores = {"training": c1_accuracy(c1_res["predict"], c1_F[c1_tr], c1_yw[c1_tr]),
"validation": c1_accuracy(c1_res["predict"], c1_F[c1_va], c1_yw[c1_va]),
"test": c1_accuracy(c1_res["predict"], c1_F[c1_te], c1_yw[c1_te]),
"new events": c1_accuracy(c1_res["predict"], c1_new_F, c1_new_yw)}
c1_res["val_acc"], c1_res["new_acc"] = c1_scores["validation"], c1_scores["new events"] # kept for the evaluation cell
print(f"best epoch {c1_res['hist']['best_epoch']} of 60")
for k, v in c1_scores.items():
print(f"accuracy, {k:12s} {v:.3f}")
# the figure: curves, scores, and which earthquakes are found
c1_bins = (0.5, 1, 2, 5, 20) # SNR bin edges
# each window takes the SNR of the record it was cut from
c1_det_test = c1_detected_by_snr(c1_res["predict"], c1_F[c1_te], c1_yw[c1_te], c1_rec_snr[c1_rec[c1_te]], c1_bins)
c1_det_new = c1_detected_by_snr(c1_res["predict"], c1_new_F, c1_new_yw, c1_new_snr[c1_new_rec], c1_bins)
print("earthquakes detected, by SNR bin:", [f"{a}-{b}" for a, b in zip(c1_bins[:-1], c1_bins[1:])])
print(" test windows ", np.round(c1_det_test, 2))
print(" new events ", np.round(c1_det_new, 2))
fig, ax = plt.subplots(1, 3, figsize=(12, 4), constrained_layout=True)
plot_curves(c1_res["hist"], "(a) learning curves", ax=ax[0], logy=True)
ax[0].set_ylabel("loss (cross-entropy)")
# bars: gray training, orange validation and test, red new events
ax[1].bar(list(c1_scores), list(c1_scores.values()), color=["0.6", "C1", "C1", "C3"])
ax[1].axhline(0.5, color="k", ls=":", lw=1.5, label="majority class") # half the windows are earthquakes
for i, v in enumerate(c1_scores.values()):
ax[1].text(i, v + 0.01, f"{v:.2f}", ha="center")
ax[1].set_ylim(0.4, 1.08); ax[1].set_ylabel("accuracy (fraction of windows)")
ax[1].set_title("(b) scores", loc="left"); ax[1].tick_params(axis="x", rotation=25); ax[1].legend(loc="lower left")
c1_x = np.arange(len(c1_bins) - 1) # one point per SNR bin
ax[2].plot(c1_x, c1_det_test, "o-", lw=2.5, color="C1", label="test windows")
ax[2].plot(c1_x, c1_det_new, "s--", lw=2.5, color="C3", label="new events")
ax[2].set_xticks(c1_x, [f"{a}-{b}" for a, b in zip(c1_bins[:-1], c1_bins[1:])])
ax[2].set_xlabel("SNR (peak amplitude / noise std)"); ax[2].set_ylabel("earthquakes detected (fraction)")
ax[2].set_ylim(0, 1.05); ax[2].set_title("(c) detection by SNR", loc="left"); ax[2].legend(); ax[2].grid(alpha=0.3)
plt.show()best epoch 59 of 60
accuracy, training 0.999
accuracy, validation 0.964
accuracy, test 0.971
accuracy, new events 0.755
earthquakes detected, by SNR bin: ['0.5-1', '1-2', '2-5', '5-20']
test windows [0.91 0.95 0.97 1. ]
new events [0.42 0.63 0.86 0.98]

What do you see?
In panel (b), the validation and test windows agree with each other, and the new events score much lower. Both are earthquakes and noise at the same station, drawn from the same magnitudes, distances, SNR and noise spectra. What differs between them?
In panel (c), the test windows with SNR between 0.5 and 1 are earthquakes whose peak amplitude is below the standard deviation of the noise. Is the detection rate in that bin physically plausible? How does it compare with the new events?
Which step of the pipeline could make the validation and test windows easier than the new events?
Your diagnosis (one sentence):
Hint
Take one validation window and trace it back to the 30-s record it was cut from (c1_rec[c1_va] gives the record of each validation window). Where did the other windows cut from that record go? How different are their spectra?
# Your fix
def c1_fix():
"""Rebuild the detector.
Must return a dict with
"predict": a function that takes features (an array from c1_features) and returns 0/1 labels,
"hist": the history returned by train() (c1_fit returns it),
"val_acc": the accuracy of the model on your validation windows,
"train_records", "val_records": bookkeeping for the evaluation, the record (0 to 1999) of
each training and each validation sample (c1_augment returns it as its third output).
Keep the 2000 records, the features, the network and the training settings (use c1_fit),
and keep 60 / 20 / 20 fractions. Do not use the new-events set for any choice.
As written, it runs the researcher's pipeline unchanged.
"""
# your changes here
W, yw, rec = c1_augment(c1_rec_X, c1_rec_y) # 10000 windows, their labels, the record of each
F = c1_features(W) # (10000, 20) features
order = np.random.default_rng(0).permutation(len(F)) # shuffle all windows
tr, va, te = np.split(order, [int(0.6 * len(F)), int(0.8 * len(F))]) # split 60/20/20 (window indices)
fit = c1_fit(F[tr], yw[tr], F[va], yw[va]) # train; epoch chosen on validation
return {"predict": fit["predict"], "hist": fit["hist"],
"val_acc": c1_accuracy(fit["predict"], F[va], yw[va]),
"train_records": rec[tr], "val_records": rec[va]}# Evaluate your fix
def c1_evaluate(fix, tol=0.06, label="your fix"):
"""Success test of the context card; tests the numbers, not the code.
fix: the dict returned by c1_fix() or c1_our_fix(); tol: largest accuracy gap allowed (0.06);
label: name of the fix in the table and figure. Prints the table and figure; returns True if all tests pass."""
if "train_records" not in fix or "val_records" not in fix:
print('c1_fix() must also return "train_records" and "val_records". Case 1 result: FAIL.')
return False
new_acc = c1_accuracy(fix["predict"], c1_new_F, c1_new_yw) # 5000 windows of the 1000 later records
gap = abs(fix["val_acc"] - new_acc) # an honest validation set scores like new events
floor = c1_res["new_acc"] - tol # lowest new-events accuracy allowed: the researcher's minus tol
# bookkeeping check, explained in What went wrong
shared = float(np.isin(np.asarray(fix["val_records"]), np.asarray(fix["train_records"])).mean())
print(f"{'':45s} {'value':>10}")
print(f"{f'best epoch ({label})':45s} {fix['hist']['best_epoch']:>10}")
print(f"{'validation accuracy (your split)':45s} {fix['val_acc']:>10.3f}")
# the three tests: the bookkeeping check, validation agrees with new events,
# new-events accuracy at most 0.06 below the researcher's
ok = [check("validation samples with their record in training", f"{shared:.3f}", "0 (no record on both sides)",
shared == 0),
check("|validation - new events|", f"{gap:.3f}", f"<= {tol}", gap <= tol),
check("new-events accuracy", f"{new_acc:.3f}", f">= {floor:.3f} (researcher - {tol})", new_acc >= floor)]
print(f"\nCase 1 result: {'PASS' if all(ok) else 'FAIL'}. Number to report: new-events accuracy {new_acc:.3f}"
f" (shared records: {shared:.3f})")
# figure: learning curves of the researcher and of the fix on one loss scale, then the accuracies side by side
fig, ax = plt.subplots(1, 3, figsize=(12, 4), constrained_layout=True)
plot_curves(c1_res["hist"], "(a) researcher", ax=ax[0], logy=True)
plot_curves(fix["hist"], f"(b) {label}", ax=ax[1], logy=True)
lo = min(ax[0].get_ylim()[0], ax[1].get_ylim()[0]); hi = max(ax[0].get_ylim()[1], ax[1].get_ylim()[1])
for a in ax[:2]:
a.set_ylim(lo, hi); a.set_ylabel("loss (cross-entropy)") # same y range in panels (a) and (b)
x = np.arange(2) # bar groups: researcher, the fix
vals = {"validation": [c1_res["val_acc"], fix["val_acc"]], "new events": [c1_res["new_acc"], new_acc]}
for j, (lab, v) in enumerate(vals.items()):
ax[2].bar(x + (j - 0.5) * 0.38, v, 0.38, label=lab, color=["C1", "C3"][j]) # bars 0.38 wide, side by side
for xi, vi in zip(x + (j - 0.5) * 0.38, v):
ax[2].text(xi, vi + 0.01, f"{vi:.2f}", ha="center", fontsize=12)
ax[2].set_xticks(x, ["researcher", label]); ax[2].set_ylim(0.4, 1.1)
ax[2].set_ylabel("accuracy (fraction of windows)"); ax[2].set_title("(c) validation vs new events", loc="left")
ax[2].legend(loc="upper right")
plt.show()
return all(ok)
# prints FAIL until c1_fix() is changed
c1_evaluate(c1_fix()); value
best epoch (your fix) 59
validation accuracy (your split) 0.964
validation samples with their record in training 0.975 target 0 (no record on both sides) FAIL
|validation - new events| 0.208 target <= 0.06 FAIL
new-events accuracy 0.755 target >= 0.695 (researcher - 0.06) PASS
Case 1 result: FAIL. Number to report: new-events accuracy 0.755 (shared records: 0.975)

Our fix below (click to open it).
Notebook Cell
def c1_our_fix():
"""Our fix: split the 2000 records first, then cut the windows of each part.
Returns the dict c1_evaluate expects; "train_records" and "val_records" are record indices (0 to 1999)."""
order = np.random.default_rng(0).permutation(len(c1_rec_X)) # shuffle records, not windows
# split records 60/20/20: 1200 training, 400 validation, 400 test records; no record is in two parts
tr, va, te = np.split(order, [int(0.6 * len(order)), int(0.8 * len(order))])
Wtr, ytr, _ = c1_augment(c1_rec_X[tr], c1_rec_y[tr]) # windows of training records only: 6000
Wva, yva, _ = c1_augment(c1_rec_X[va], c1_rec_y[va]) # windows of validation records only: 2000
Ftr, Fva = c1_features(Wtr), c1_features(Wva)
fit = c1_fit(Ftr, ytr, Fva, yva) # same network and training settings
# validation windows now come from records the network never trained on, so val_acc measures unseen
# records, like the new events
return {"predict": fit["predict"], "hist": fit["hist"],
"val_acc": c1_accuracy(fit["predict"], Fva, yva),
"train_records": tr, "val_records": va}
# how many of the researcher's validation windows had a window of the same record in training?
# c1_rec maps each window to its record; windows of one record share the same earthquake and noise
c1_shared = np.isin(c1_rec[c1_va], c1_rec[c1_tr]).mean()
print(f"researcher's validation windows whose record also has a window in training: {c1_shared:.3f}")researcher's validation windows whose record also has a window in training: 0.975
# Evaluate our fix
# the same three tests as for your fix
c1_evaluate(c1_our_fix(), label="our fix");Output
value
best epoch (our fix) 1
validation accuracy (your split) 0.779
validation samples with their record in training 0.000 target 0 (no record on both sides) PASS
|validation - new events| 0.013 target <= 0.06 PASS
new-events accuracy 0.792 target >= 0.695 (researcher - 0.06) PASS
Case 1 result: PASS. Number to report: new-events accuracy 0.792 (shared records: 0.000)

What went wrong
Cause. The five windows cut from one 30-s record overlap by at least 23 of their 25 s: they carry the same earthquake and the same noise, and their spectra are nearly identical. The researcher cut the windows first and then split the windows at random, so 97.5 % of the validation windows had a window from their own record in the training set. The network learned to recognize records, and the validation and test sets rewarded it for that.
Why the symptom follows. A near-copy of a training window is not a new observation. The validation and test accuracies (0.962 and 0.971) measured how well the network remembers records it trained on, not how well it detects an earthquake it has never seen (0.761 on the new events). Earthquakes with SNR between 0.5 and 1 were “detected” in 91 % of the test windows because their records had been memorized; on the new events, 42 % of them are detected.
Fix. Split the records (the events) first, then cut the shifted windows inside each part, or drop the shifted copies. With an honest validation set the curves tell a different story: the validation loss is lowest after the second epoch (best epoch 1, counting from 0) and rises after it. The network overfits, which the leaky split hid; that is the next thing to work on (D6).
How the evaluation proves it. With records split first, no validation window has its record in the training set (the researcher’s split: 0.975), and the validation accuracy (0.779) and the new-events accuracy (0.792) agree within 0.06, as two samples of the same kind of data should (0.06 is about two and a half standard errors of an accuracy near 0.8 measured on 400 validation records and 1000 new records). The new-events accuracy did not drop: 0.792 against the researcher’s 0.761. The validation score can now guide choices, and 0.792 is the number to report. Dropping the shifted copies (one window per record) passes too: validation 0.775, new events 0.790. Stopping the researcher’s run after 5 epochs is not a fix: validation and new events then both score 0.790, but 97.5 % of the validation windows still have their record in training, so the validation score still measures memory of records, and the shared-record line fails.
Rubric items. A3 (name the deployment axis: new earthquakes), A4 (split along it: hold out events, not windows), E5 (one test along the deployment axis that was not used for any choice).
In real data. One earthquake recorded at several stations, or on three components, sits on both sides of a split made by waveform. Overlapping windows cut from continuous records (tremor, landslide signals, glacial earthquakes) do the same, and so do repeating earthquakes, whose waveforms are nearly identical by definition. Outside seismology, pixels of one satellite scene and plots of one forest are near-copies of their neighbors: Ploton et al. (2020, Nature Communications) showed that random cross-validation overstated the skill of a forest biomass map of central Africa, and that validation on spatially separated plots did not. Split by event, sequence, station or region, then augment.
Case 2: The network calls every rock granite¶
| Geoscience system | Igneous rocks of a continental arc. Basalt (mafic), andesite (intermediate) and granite (felsic) record how far a magma differentiated: as it evolves it gains SiO and K and loses FeO, MgO and CaO, and its density and magnetic susceptibility drop. |
| Data | One sample is one rock specimen; 4,000 specimens. Nine measurements per specimen, each in the unit its instrument reports: six major oxides from laboratory XRF (wt%), potassium from a portable XRF (ppm), bulk density (kg/m), magnetic susceptibility from a handheld meter (10 SI). Synthetic: mlgeo_synth.geochem_table with a measurement-noise floor. |
| Input and target | X: the nine columns as they appear in the spreadsheet. Y: the lithology; granite 55%, basalt 35%, andesite 10% of the specimens. |
| Split | Random, stratified by lithology: 2,400 training, 800 validation and 800 test specimens. The test specimens are held out. |
| Model | Fully connected network 9 → 32 → 32 → 3, ReLU, one score per lithology, cross-entropy loss. |
| Training | A colleague’s script: stochastic gradient descent (SGD), learning rate 0.1, batches of 64 specimens, 40 epochs, seed 2; the epoch with the lowest validation loss is kept (the shared train()). |
| The researcher’s claim | “Validation accuracy 0.556, and the network calls 797 of the 800 validation specimens granite. These nine measurements cannot tell the three lithologies apart.” |
| Success test for your fix | On the 800 held-out test specimens: training loss at the last epoch below half the loss of predicting the class proportions; test accuracy at least that of a logistic regression fit to the same spreadsheet; andesite recall at least the logistic regression’s. |
# Case 2: the researcher's pipeline, as run
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
C2_CLASSES = ["granite", "basalt", "andesite"] # class index 0, 1, 2
def c2_lab_table(n=4000, seed=2):
"""The lab spreadsheet (synthetic): one row per rock specimen, nine measurement columns.
Built from mlgeo_synth.geochem_table plus a measurement-noise floor of
0.7 standard deviation per column, so that no single column separates the classes.
n: number of rock specimens; seed: seed of the synthetic rocks and of the noise.
Returns a DataFrame of n rows: nine measurement columns and the "lithology" column."""
g = mlgeo_synth.geochem_table(n=n, seed=seed)
rng = np.random.default_rng(seed + 100)
# measurement noise: 0.7 standard deviation of each column, added to oxides and density
oxides = ["SIO2", "AL2O3", "FEO", "MGO", "CAO", "NA2O", "K2O"]
for c in oxides + ["density_g_cm3"]:
g[c] = g[c] + rng.normal(0, 0.7 * g[c].std(), n)
g[oxides] = g[oxides].clip(lower=0.01) # detection limit, wt%
# susceptibility spans decades, so its noise is added to log10 of it
log_chi = np.log10(g["mag_susc_si"])
log_chi = log_chi + rng.normal(0, 0.7 * log_chi.std(), n)
# the nine columns of the lab spreadsheet, and the lithology of each specimen
return pd.DataFrame({
"SiO2 (wt%)": g["SIO2"], "Al2O3 (wt%)": g["AL2O3"], "FeO (wt%)": g["FEO"],
"MgO (wt%)": g["MGO"], "CaO (wt%)": g["CAO"], "Na2O (wt%)": g["NA2O"],
"K (ppm)": g["K2O"] * 8301.0,
"density (kg/m3)": g["density_g_cm3"] * 1000.0,
"susceptibility (1e-6 SI)": 10 ** log_chi * 1e6, # handheld susceptibility meter
"lithology": g["label"]})
c2_df = c2_lab_table() # 4000 specimens
print(c2_df.head().round(2).to_string(), "\n")
# split: 60% training, 20% validation, 20% test, stratified by lithology
# (stratified: the same share of each lithology in every set)
c2_X = c2_df.drop(columns="lithology").to_numpy(np.float32) # (4000, 9) the nine measurement columns
c2_y = c2_df["lithology"].map({c: i for i, c in enumerate(C2_CLASSES)}).to_numpy() # (4000,) class index
# 2400 training specimens; the other 1600 are split in half below
c2_Xtr, c2_Xrest, c2_ytr, c2_yrest = train_test_split(c2_X, c2_y, test_size=0.4, stratify=c2_y, random_state=2)
# 800 validation and 800 test specimens (the test specimens are held out)
c2_Xva, c2_Xte, c2_yva, c2_yte = train_test_split(c2_Xrest, c2_yrest, test_size=0.5, stratify=c2_yrest, random_state=2)
def c2_tensor(a):
"""Array of specimens, (n_specimens, 9), to a float32 tensor of the same shape."""
return torch.as_tensor(np.asarray(a), dtype=torch.float32)
def c2_make_model():
"""The 9-32-32-3 network with ReLU: nine measurements in, one score per lithology out."""
return nn.Sequential(nn.Linear(9, 32), nn.ReLU(), nn.Linear(32, 32), nn.ReLU(), nn.Linear(32, 3))
# train: the colleague's training settings: SGD, learning rate 0.1, batches of 64, 40 epochs
torch.manual_seed(2) # random starting weights, recorded seed
c2_model = c2_make_model()
c2_hist = train(c2_model, c2_tensor(c2_Xtr), torch.as_tensor(c2_ytr), c2_tensor(c2_Xva), torch.as_tensor(c2_yva),
nn.CrossEntropyLoss(), epochs=40, lr=0.1, batch_size=64, optimizer="sgd", seed=2)
def c2_predict_researcher(X_lab):
"""Lithology of each specimen from the researcher's network.
X_lab: (n_specimens, 9) measurements from the lab spreadsheet.
Returns (n_specimens,) class indices: 0 granite, 1 basalt, 2 andesite."""
with torch.no_grad():
return c2_model(c2_tensor(X_lab)).argmax(1).numpy() # the lithology with the highest score
c2_researcher = {"hist": c2_hist, "predict": c2_predict_researcher}
# the numbers the researcher reports
c2_pred_va = c2_predict_researcher(c2_Xva) # (800,) predicted class, validation specimens
print(f"training samples {len(c2_ytr)}, validation {len(c2_yva)}, test {len(c2_yte)} (held out)")
print(f"training loss: epoch 0 {c2_hist['train_loss'][0]:.3f}, epoch 39 {c2_hist['train_loss'][-1]:.3f}")
print(f"best validation epoch {c2_hist['best_epoch']}, validation accuracy {(c2_pred_va == c2_yva).mean():.3f}")
# the evidence: learning curves, and the confusion matrix of the validation specimens
def c2_show_evidence():
"""Plot the learning curves and the 3 x 3 confusion matrix of the 800 validation specimens."""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
plot_curves(c2_hist, title="Learning curves, as run", ax=ax1)
ax1.set_ylabel("cross-entropy loss (nats)"); ax1.set_ylim(0, 1.1)
cm = confusion_matrix(c2_yva, c2_pred_va, labels=[0, 1, 2]) # rows: true lithology, columns: predicted
ax2.imshow(cm, cmap="Blues")
for i in range(3): # write the count of specimens in each box
for j in range(3):
ax2.text(j, i, cm[i, j], ha="center", va="center", fontsize=14,
color="white" if cm[i, j] > cm.max() / 2 else "black")
ax2.set_xticks(range(3), C2_CLASSES); ax2.set_yticks(range(3), C2_CLASSES)
ax2.set_xlabel("predicted lithology"); ax2.set_ylabel("true lithology")
ax2.set_title("Validation specimens (counts)", loc="left")
plt.tight_layout()
plt.show()
c2_show_evidence() SiO2 (wt%) Al2O3 (wt%) FeO (wt%) MgO (wt%) CaO (wt%) Na2O (wt%) K (ppm) density (kg/m3) susceptibility (1e-6 SI) lithology
0 74.54 14.87 4.94 0.01 8.60 2.59 26536.69 2503.87 39.80 granite
1 87.95 14.93 2.66 0.01 1.31 3.59 30855.86 2672.75 226.73 granite
2 57.76 15.50 9.37 9.45 10.47 3.13 8198.22 2906.34 2556.57 basalt
3 61.85 14.40 4.14 0.01 0.01 3.70 27460.08 2529.44 187.02 granite
4 44.84 14.38 8.46 5.64 8.74 3.37 19369.96 3032.31 668.00 basalt
training samples 2400, validation 800, test 800 (held out)
training loss: epoch 0 0.948, epoch 39 0.923
best validation epoch 16, validation accuracy 0.556

What do you see?
The training loss stays between 0.92 and 0.95 for all 40 epochs. What loss does a model reach if it ignores the measurements and predicts the class proportions (55%, 35%, 10%) for every specimen? Compute .
In notebook 4.7 (section 1), the scatter of MgO against SiO separates granite from basalt by eye. Is the information missing from these nine columns, or is the network not using it? Which quick experiment would tell the two apart?
Look at the printed rows of the table: which numbers enter the first layer of the network?
Your diagnosis (one sentence):
Hint
Print c2_df.describe() and compare the spread of each column. In the first layer, the gradient of the weight that multiplies column is the error signal of its neuron times the input: . Ask what one SGD update with learning rate 0.1 does to the weights of the columns with the largest , and then what the ReLUs that follow output.
# Your fix: edit this function. The evaluation cell below calls it.
def c2_fix():
"""Return a dict with two entries:
"hist": the curves returned by train() with nn.CrossEntropyLoss() (loss per epoch);
"predict": a function that takes rows shaped like c2_Xte (one row per specimen, 9 columns)
and returns one class index per row (0 granite, 1 basalt, 2 andesite).
As written, it runs the researcher's pipeline unchanged."""
# your changes here
# the researcher's split: 2400 training and 800 validation specimens, 9 columns each
Xtr, Xva = c2_Xtr, c2_Xva
# train: the colleague's settings (SGD, learning rate 0.1, batches of 64, 40 epochs, seed 2)
torch.manual_seed(2) # random starting weights, recorded seed
model = c2_make_model()
hist = train(model, c2_tensor(Xtr), torch.as_tensor(c2_ytr), c2_tensor(Xva), torch.as_tensor(c2_yva),
nn.CrossEntropyLoss(), epochs=40, lr=0.1, batch_size=64, optimizer="sgd", seed=2)
def predict(X_lab):
"""Class index (0 granite, 1 basalt, 2 andesite) of each specimen.
X_lab: (n_specimens, 9) measurements from the lab spreadsheet. Returns (n_specimens,)."""
with torch.no_grad():
return model(c2_tensor(X_lab)).argmax(1).numpy() # the lithology with the highest score
return {"hist": hist, "predict": predict}# Evaluate your fix on the 800 held-out test specimens (never used for training or for choices)
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import recall_score
# reference loss: a model that ignores the measurements and predicts the class proportions
c2_prior = np.bincount(c2_ytr) / len(c2_ytr) # (3,) share of granite, basalt, andesite in training
c2_prior_loss = float(-(c2_prior * np.log(c2_prior)).sum()) # loss of always predicting the class proportions
# classical baseline (rubric A6, C1.4): logistic regression on the same table and split
c2_logit = LogisticRegression(max_iter=5000).fit(c2_Xtr, c2_ytr) # fit on the 2400 training specimens
c2_logit_pred = c2_logit.predict(c2_Xte) # (800,) class index, test specimens
c2_acc_lr = float((c2_logit_pred == c2_yte).mean())
def c2_scores(pred):
"""Accuracy and recall of each lithology on the 800 test specimens.
pred: (800,) predicted class index of each test specimen.
Returns (accuracy, recall), recall shaped (3,) in the order granite, basalt, andesite."""
pred = np.asarray(pred).ravel()
return (pred == c2_yte).mean(), recall_score(c2_yte, pred, labels=[0, 1, 2], average=None, zero_division=0)
def c2_evaluate(result, label="your fix"):
"""The success test of case 2, on the outcome only: any change of the pipeline may pass.
result: the dict from c2_fix() or c2_our_fix() ("hist" and "predict"); label: name in the table and figure.
Prints one line per test and draws the training loss and the recall per lithology; returns "PASS" or "FAIL"."""
hist = result["hist"]
acc, rec = c2_scores(result["predict"](c2_Xte)) # predictions of the fix for the 800 test specimens
acc_lr, rec_lr = c2_scores(c2_logit_pred)
last = hist["train_loss"][-1] # training loss at the last epoch (nats)
print(f"{label}; class-proportion loss {c2_prior_loss:.3f} nats; logistic baseline: accuracy {acc_lr:.3f}, "
f"andesite recall {rec_lr[2]:.3f}")
# three tests: the network learned from the measurements (loss well below the class-proportion loss),
# it is at least as accurate as the linear baseline, and it finds the rare andesite (10% of specimens)
ok = [check("training loss, last epoch (nats)", f"{last:.3f}", f"< {0.5 * c2_prior_loss:.3f} (half)",
bool(np.isfinite(last) and last < 0.5 * c2_prior_loss)),
check("test accuracy", f"{acc:.3f}", f">= {acc_lr:.3f} (logistic)",
bool(acc >= acc_lr)),
check("andesite recall, test", f"{rec[2]:.3f}", f">= {rec_lr[2]:.3f} (logistic)",
bool(rec[2] >= rec_lr[2]))]
# left: training loss of the researcher and of the fix, against the class-proportion loss
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4))
ax1.plot(c2_hist["train_loss"], lw=2.5, color="tab:gray", label="researcher")
ax1.plot(hist["train_loss"], lw=2.5, color="tab:blue", label=label)
ax1.axhline(c2_prior_loss, color="k", ls=":", lw=1.5, label="class proportions")
ax1.set_yscale("log"); ax1.set_ylim(0.02, 3); ax1.set_xlabel("epoch"); ax1.set_ylabel("training loss (nats)")
ax1.set_title("Training loss", loc="left"); ax1.legend(); ax1.grid(alpha=0.3)
# right: recall of each lithology on the test specimens, researcher, logistic baseline and the fix
_, rec_r = c2_scores(c2_researcher["predict"](c2_Xte))
x = np.arange(3)
for k, (r, name, col) in enumerate([(rec_r, "researcher", "tab:gray"), (rec_lr, "logistic", "tab:orange"),
(rec, label, "tab:blue")]):
ax2.bar(x + (k - 1) * 0.27, r, width=0.27, color=col, label=name) # three bars per lithology
ax2.set_xticks(x, C2_CLASSES); ax2.set_ylim(0, 1.32); ax2.set_yticks(np.arange(0, 1.01, 0.2))
ax2.set_ylabel("recall (fraction found)"); ax2.set_title("Test specimens, by lithology", loc="left")
ax2.legend(loc="upper center", ncol=3, fontsize=13); ax2.grid(alpha=0.3, axis="y")
plt.tight_layout()
plt.show()
verdict = "PASS" if all(ok) else "FAIL"
print(f"Case 2, {label}: {verdict}")
return verdict
c2_evaluate(c2_fix(), "your fix");your fix; class-proportion loss 0.928 nats; logistic baseline: accuracy 0.963, andesite recall 0.793
training loss, last epoch (nats) 0.923 target < 0.464 (half) FAIL
test accuracy 0.557 target >= 0.963 (logistic) FAIL
andesite recall, test 0.000 target >= 0.793 (logistic) FAIL

Case 2, your fix: FAIL
Our fix below (click to open it).
Notebook Cell
# Our fix: standardize every column with the training samples' mean and standard deviation.
# Raw columns span 0.01 wt% (oxides) to tens of thousands (K in ppm, susceptibility); the gradient of a
# first-layer weight is proportional to its input, so the large columns throw their weights far on the
# first SGD steps and silence most ReLUs. After scaling, every column has mean 0 and standard deviation 1.
def c2_our_fix():
"""Same pipeline as the researcher's; the inputs are standardized with training statistics only.
Returns the same dict as c2_fix(): "hist" and "predict" (which takes specimens in the lab's units)."""
mu, sd = c2_Xtr.mean(axis=0), c2_Xtr.std(axis=0) # 9 means, 9 standard deviations, training rows only
def scale(X):
"""(n_specimens, 9) lab units to standardized units, with the 18 training numbers.
The same mu and sd serve training, validation, test and any new specimen, so no
validation or test specimen informs the scaling."""
return (np.asarray(X) - mu) / sd
# train: unchanged settings (SGD, learning rate 0.1, batches of 64, 40 epochs, seed 2), scaled inputs
torch.manual_seed(2) # same starting weights as the researcher's run
model = c2_make_model()
hist = train(model, c2_tensor(scale(c2_Xtr)), torch.as_tensor(c2_ytr),
c2_tensor(scale(c2_Xva)), torch.as_tensor(c2_yva),
nn.CrossEntropyLoss(), epochs=40, lr=0.1, batch_size=64, optimizer="sgd", seed=2)
def predict(X_lab):
"""Class index of each specimen; X_lab in the lab's units, (n_specimens, 9), scaled here."""
with torch.no_grad():
return model(c2_tensor(scale(X_lab))).argmax(1).numpy() # new specimens get the training scaling
return {"hist": hist, "predict": predict}# Evaluate our fix: the same test as above, on the same 800 held-out test specimens
c2_evaluate(c2_our_fix(), "our fix");Output
our fix; class-proportion loss 0.928 nats; logistic baseline: accuracy 0.963, andesite recall 0.793
training loss, last epoch (nats) 0.051 target < 0.464 (half) PASS
test accuracy 0.985 target >= 0.963 (logistic) PASS
andesite recall, test 0.939 target >= 0.793 (logistic) PASS

Case 2, our fix: PASS
What went wrong
Cause. The inputs were never standardized. Potassium in ppm (up to 73,109 in the training rows), density in kg/m (about 2,300 to 3,300) and susceptibility in 10 SI (up to 27,349) enter the first layer next to oxides measured in wt%, all below 100. The gradient of a first-layer weight is the error signal of its neuron times its input, so on the first batch the weights on potassium receive gradients 391 times larger than those on SiO (density 43 times, susceptibility 14 times). The first SGD updates throw those weights so far that, by the end, 29 of the 32 first-layer ReLUs output zero for every training specimen.
Why the symptom follows. With almost every ReLU silent, the output barely depends on the rock: the network learns the class proportions through the bias of its last layer and gives 797 of the 800 validation specimens the same answer, granite. Its training loss (0.923) is close to the loss of predicting the proportions (0.928), and its accuracy is the share of granite.
Fix. Standardize each column with the mean and standard deviation of the 2,400 training specimens only, apply those same 18 numbers to the validation, test and any new specimen, and change nothing else. On the test specimens: accuracy 0.985 instead of 0.557, andesite recall 0.939 instead of 0.000, last training loss 0.051.
Is a different optimizer the fix? No. Adam on the raw columns, learning rate 0.001, 40 epochs: test accuracy 0.863, andesite recall 0.122; after 200 epochs 0.926 and 0.683. Both fail. Adam gives each weight its own step size, which removes the outsized updates, but the network’s output is still set by the large columns. Converting the columns back to wt%, g/cm and 10 SI also fails (accuracy 0.554): the card’s “each in the unit its instrument reports” points at units, but consistent units are not standardized inputs, and the training means of the columns still range from 0.74 to 62.5, far from zero. With standardized inputs, SGD and Adam both pass (0.985 and 0.985); scaling each column to the training minimum and maximum passes too (0.980).
How the evaluation proves it. It grades the outcome on 800 test specimens that no choice was tuned on: the training loss falls below half the class-proportion loss; accuracy reaches at least that of a logistic regression fit to the same spreadsheet (0.974); and the rare andesite is found at least as often as by that logistic regression (0.854). The accuracy line is the logistic accuracy itself, not one standard error (0.006) above it, because valid fixes scatter by about that much from seed to seed: min-max scaling with seeds 0 to 4 scores 0.975 to 0.983. The andesite recall and the training loss are the lines that separate fixes from non-fixes: Adam on the raw columns finds 0.122 of the andesite, and a learning rate of 0.00001 finds none. The logistic regression alone refutes the claim: the information is in the measurements. Given standardized inputs, the logistic regression reaches 0.985 as well, so on this table the network ties a linear model (rubric E3): the classes are nearly linear in these nine measurements.
Rubric items. C1.1 (inputs standardized), A5 (the scaling fit on the training specimens only), A6 and C1.4 (a logistic baseline on the same split would have refuted the claim at once), E2 (the confusion matrix and the recall of each class), D4 and D5 (the flat curve is not a learning-rate problem: lowering it alone fails, SGD with a learning rate of 0.00001 reaches 0.833 and finds no andesite).
In real data. Whole-rock compilations put majors in wt% next to trace elements in ppm (Sr, Zr, Ba in the hundreds to thousands); well logs put bulk density in kg/m next to resistivity spanning four decades and gamma ray in API units; seismic feature tables put amplitudes in counts next to durations in seconds. Two related errors follow the same path: a scaler fit on all rows lets the test rows inform training, and a model deployed without its training means and standard deviations misreads every new specimen.
Case 3: A swarm detector with 98% accuracy, ready for the observatory¶
One seismometer sits on a volcano during a seismic swarm. Small local earthquakes arrive among the continuous background noise of the station (wind, ocean, the volcano itself). The observatory wants an automatic detector that flags every 30-s window holding an earthquake, so that the analyst on duty reviews those windows and nothing else.
| Geoscience system | Vertical ground velocity at one station during a swarm: earthquakes of magnitude 1 to 4, 5 to 80 km from the station (P and S waves), on top of background noise whose amplitude falls with frequency. |
| Data | 7983 windows of 30 s, 100 samples per second: 66.5 hours of record (synthetic, mlgeo_synth.seismogram_dataset). An analyst marked 183 windows as holding an earthquake (signal-to-noise ratio of 2 or more). |
| Input and target | Input: one window band-passed 2 to 8 Hz, resampled to 20 samples per second (600 values) and divided by its largest absolute value. Target: 1 for an earthquake window, 0 for noise. |
| Split | In time: the first 50% of the record (33.3 h) for training, the next 25% for validation, the last 25% (16.6 h) for testing. |
| Model | Convolutional network: two layers of 8 kernels of 9 samples, max pooling, one score per window. The probability of an earthquake is the sigmoid of the score; the detector fires when it is 0.5 or more. |
| Training | Binary cross-entropy (BCEWithLogitsLoss), Adam, learning rate 0.001, batches of 128, 15 epochs, the best validation epoch kept, seed 0. |
| Claim | “Accuracy 0.98 on 16.6 hours of record the network never saw. The detector is ready to run at the observatory.” |
| Success test for your fix | The observatory’s requirement: at least 3 of 4 earthquakes detected (recall 0.75) and at most one false alarm per hour (24 per day). It must hold on the validation record, where the threshold and every other choice are made, and on the 16.6 h of test record. |
# Case 3: the researcher's pipeline, as run
c3_t0 = time.time() # wall-clock start, printed at the end of the cell
# 1. The record: 30-s windows of one station during a swarm, in time order
c3_wave_all, c3_y_all, c3_meta = mlgeo_synth.seismogram_dataset(n_events=320, n_noise=7800, seed=3)
c3_snr_all = np.array([m.get("snr", np.inf) for m in c3_meta]) # SNR of each earthquake; inf for noise windows
c3_keep = (c3_y_all == 0) | (c3_snr_all >= 2) # the analyst marked earthquakes with SNR >= 2
c3_time_order = np.random.default_rng(3).permutation(c3_keep.sum()) # the order of the windows along the record
c3_wave = c3_wave_all[c3_keep][c3_time_order] # (n windows, 3000 samples at 100 Hz)
c3_y = c3_y_all[c3_keep][c3_time_order] # 1 = earthquake, 0 = noise
C3_WINDOW_S = 30.0 # length of one window (s), to convert counts to hours and days
def c3_prepare(wave):
"""Band-pass 2-8 Hz, resample to 20 samples/s, divide by the peak: (n, 3000) -> (n, 1, 600).
wave: (n windows, 3000) vertical ground velocity at 100 samples/s.
Returns a float32 tensor (n windows, 1 channel, 600 samples at 20 samples/s), peak absolute value 1.
"""
f = np.fft.rfftfreq(wave.shape[1], d=0.01) # frequency (Hz) of each Fourier coefficient; 0.01 s sampling
spec = np.fft.rfft(wave, axis=1)
spec[:, (f < 2) | (f > 8)] = 0 # keep 2 to 8 Hz only
x = np.fft.irfft(spec, n=wave.shape[1], axis=1).reshape(len(wave), -1, 5).mean(axis=2) # mean of 5 samples: 100 -> 20 samples/s
x = x / np.abs(x).max(axis=1, keepdims=True) # each window divided by its own largest absolute value
return torch.tensor(x, dtype=torch.float32).unsqueeze(1) # add the channel axis: (n, 1, 600)
# 2. Split in time: 50% training, 25% validation, 25% test
c3_X = c3_prepare(c3_wave) # (n windows, 1, 600)
c3_yt = torch.tensor(c3_y, dtype=torch.float32) # labels as floats, as BCEWithLogitsLoss expects
c3_n = len(c3_y)
c3_i1, c3_i2 = int(0.5 * c3_n), int(0.75 * c3_n) # window indices where validation and test start
c3_Xtr, c3_ytr = c3_X[:c3_i1], c3_yt[:c3_i1] # training: first half of the record
c3_Xva, c3_yva = c3_X[c3_i1:c3_i2], c3_yt[c3_i1:c3_i2] # validation: the next quarter
c3_Xte, c3_yte = c3_X[c3_i2:], c3_yt[c3_i2:] # test: the last quarter (16.6 h)
# 3. The detector: one raw score (logit) per window; the sigmoid 1/(1+e^-score) maps it to a probability
def c3_make_detector():
"""Build the convolutional detector: (n, 1, 600) windows -> (n,) scores (logits).
Two layers of 8 kernels of 9 samples (the first spans 0.45 s at 20 samples/s; the second, after a step
of 4 and a pool of 4, about 7 s), then the largest response of each kernel
over the window, then one weighted sum. Shapes: (n, 1, 600) -> (n, 8, 150) -> pool (n, 8, 37)
-> (n, 8, 37) -> (n, 8, 1) -> (n, 8) -> (n, 1) -> (n,).
"""
return nn.Sequential(
# padding=4: 4 zeros added at each end so the edges are scanned; step of 4 samples: 600 -> 150;
# max pooling keeps the largest of each 4 values: 150 -> 37
nn.Conv1d(1, 8, 9, stride=4, padding=4), nn.ReLU(), nn.MaxPool1d(4),
nn.Conv1d(8, 8, 9, padding=4), nn.ReLU(), nn.AdaptiveMaxPool1d(1), # largest response of each kernel in the window
nn.Flatten(), nn.Linear(8, 1), nn.Flatten(0)) # one score per window, shape (n,)
def c3_scores(model, X):
"""Probability of an earthquake for each window.
model: a detector that returns one logit per window; X: (n windows, 1, 600).
Returns a numpy array (n windows,) of probabilities between 0 and 1 (sigmoid of the logit).
"""
model.eval()
with torch.no_grad():
return torch.sigmoid(model(X)).numpy()
def c3_rates(p, y, threshold):
"""Recall of the earthquake windows, and false alarms per day of record, when firing at p >= threshold.
p: (n windows,) probabilities of an earthquake; y: (n windows,) analyst labels, 1 earthquake, 0 noise;
threshold: the probability at or above which the detector fires.
Returns (fraction of earthquake windows detected, noise windows flagged per 24 h of record).
"""
fire, quake = p >= threshold, np.asarray(y) == 1 # boolean, one per window
recall = (fire & quake).sum() / quake.sum()
false_alarms_per_day = (fire & ~quake).sum() / (len(quake) * C3_WINDOW_S / 86400) # divided by days of record
return recall, false_alarms_per_day
# 4. Training: the shared train() of the setup cell, best validation epoch kept
torch.manual_seed(0) # random starting weights, recorded seed
c3_model = c3_make_detector()
c3_hist = train(c3_model, c3_Xtr, c3_ytr, c3_Xva, c3_yva, nn.BCEWithLogitsLoss(),
epochs=15, lr=1e-3, batch_size=128, seed=0)
c3_researcher = (c3_model, 0.5) # the researcher's detector: (network, firing threshold)
# 5. What the researcher reports
c3_p_te = c3_scores(c3_model, c3_Xte) # probability of an earthquake, one per test window
c3_fire_te = c3_p_te >= 0.5 # the detector fires at probability 0.5 or more
c3_acc = (c3_fire_te == (c3_yte.numpy() == 1)).mean() # fraction of test windows where detector and analyst agree
print(f"record: {c3_n} windows = {c3_n * C3_WINDOW_S / 3600:.1f} h; test: {len(c3_yte)} windows = "
f"{len(c3_yte) * C3_WINDOW_S / 3600:.1f} h")
print(f"test accuracy: {c3_acc:.3f}")
# Evidence: learning curves, and the confusion matrix of the test windows
# confusion matrix: rows = what the analyst says (noise, earthquake), columns = what the detector says
c3_cm = np.array([[np.sum((c3_yte.numpy() == t) & (c3_fire_te == p)) for p in (0, 1)] for t in (0, 1)])
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 4), gridspec_kw={"width_ratios": [1.6, 1]})
plot_curves(c3_hist, "learning curves (binary cross-entropy)", ax=ax1)
ax2.imshow(c3_cm, cmap="Blues", norm=plt.matplotlib.colors.LogNorm(vmin=1, vmax=c3_cm.max())) # log color scale of counts
for i in range(2):
for j in range(2):
ax2.text(j, i, c3_cm[i, j], ha="center", va="center", fontsize=18,
color="white" if c3_cm[i, j] > 100 else "black") # white text on the dark cells
ax2.set_xticks([0, 1], ["noise", "earthquake"]); ax2.set_yticks([0, 1], ["noise", "earthquake"])
ax2.set_xlabel("detector says"); ax2.set_ylabel("analyst says")
ax2.set_title("test windows (counts)", loc="left")
fig.tight_layout()
print(f"case 3 pipeline: {time.time() - c3_t0:.1f} s")record: 7983 windows = 66.5 h; test: 1996 windows = 16.6 h
test accuracy: 0.979
case 3 pipeline: 3.4 s

What do you see?
Read the confusion matrix row by row. How many earthquakes are in the 16.6 hours of test record, and how many did the detector report?
What accuracy would a detector reach that never fires at all? Compare it with 0.98.
What two numbers does the analyst on duty need to know about this detector, that accuracy does not give?
Your diagnosis (one sentence):
Hint
Count the windows of each class in c3_ytr. Then compute the probabilities on the validation windows, p_va = c3_scores(c3_model, c3_Xva), and compare those of the earthquakes, p_va[c3_yva.numpy() == 1], with those of the noise windows. Are the earthquakes scored like noise, or higher than noise but below the line where the detector fires? c3_rates(p_va, c3_yva.numpy(), threshold) gives the recall and the false alarms per day for any threshold.
# Your fix: edit this function. The evaluation cell below calls it.
def c3_fix():
"""Your fix of the swarm detector. As written, it runs the researcher's pipeline unchanged.
Return (model, threshold):
model: a trained network that takes windows shaped like c3_X, (n, 1, 600), and returns
one score (logit) per window; the probability of an earthquake is its sigmoid;
threshold: the probability at or above which the detector fires.
Train on c3_Xtr, c3_ytr; make every choice on c3_Xva, c3_yva.
Never look at c3_Xte, c3_yte: they are the test of cell "Evaluate your fix".
"""
# your changes here
torch.manual_seed(0) # same random starting weights as the researcher
model = c3_make_detector() # (n, 1, 600) windows -> (n,) logits
criterion = nn.BCEWithLogitsLoss() # binary cross-entropy on the logit
train(model, c3_Xtr, c3_ytr, c3_Xva, c3_yva, criterion,
epochs=15, lr=1e-3, batch_size=128, seed=0) # the researcher's settings; best validation epoch kept
threshold = 0.5 # fire when the probability of an earthquake is 0.5 or more
return model, threshold# Evaluate your fix against the observatory's requirement (the success test of the card):
# at least 3 of 4 earthquakes detected, at most one false alarm per hour (24 per day),
# on the validation record (where the choices are made) and on the 16.6 h of test record.
C3_MIN_RECALL, C3_MAX_FA_PER_DAY = 0.75, 24.0 # recall (fraction of earthquakes), false alarms per day
def c3_evaluate(result, label="your fix"):
"""Success test of case 3: tests the detections, not the code; prints PASS or FAIL and draws the test record.
result: (model, threshold), as returned by c3_fix() or c3_our_fix();
label: the name used in the printout and the figure.
Returns True when recall and false alarms per day meet the requirement on both validation and test.
"""
model, threshold = result
p = c3_scores(model, c3_Xte) # probability of an earthquake, one per test window
y = c3_yte.numpy() # analyst labels of the test windows
rec, fa = c3_rates(p, y, threshold) # the detector under test on the 16.6 h of test record
rec0, fa0 = c3_rates(c3_p_te, y, 0.5) # the researcher's detector on the same windows
acc = ((p >= threshold) == (y == 1)).mean() # accuracy: printed to compare with the claim, not tested
print(f"Case 3, {label}: {len(y) * C3_WINDOW_S / 3600:.1f} h of test record, "
f"{int(y.sum())} earthquakes, threshold {threshold:.3f}")
print(f"researcher (threshold 0.5): accuracy {c3_acc:.3f}, recall {rec0:.2f}, false alarms/day {fa0:.1f}")
print(f"{label} (threshold {threshold:.2f}): accuracy {acc:.3f}, recall {rec:.2f}, false alarms/day {fa:.1f}")
# the two numbers the analyst on duty needs, first on validation (where the choices are made), then on test
rec_va, fa_va = c3_rates(c3_scores(model, c3_Xva), c3_yva.numpy(), threshold)
ok = check("validation: earthquakes detected (recall)", f"{rec_va:.2f}", f">= {C3_MIN_RECALL}",
rec_va >= C3_MIN_RECALL)
ok &= check("validation: false alarms per day", f"{fa_va:.1f}", f"<= {C3_MAX_FA_PER_DAY:.0f} (1 per hour)",
fa_va <= C3_MAX_FA_PER_DAY)
ok &= check("test: earthquakes detected (recall)", f"{rec:.2f}", f">= {C3_MIN_RECALL}", rec >= C3_MIN_RECALL)
ok &= check("test: false alarms per day", f"{fa:.1f}", f"<= {C3_MAX_FA_PER_DAY:.0f} (1 per hour)",
fa <= C3_MAX_FA_PER_DAY)
print("Case 3 verdict:", "PASS" if ok else "FAIL") # PASS only if all four lines pass
# Before and after: the probability of each test window along the record
hours = np.arange(len(y)) * C3_WINDOW_S / 3600 # start time of each test window (h)
fig, axes = plt.subplots(1, 2, figsize=(12, 4), sharey=True)
for ax, (pp, thr, name) in zip(axes, [(c3_p_te, 0.5, "researcher"), (p, threshold, label)]):
quake, fire = y == 1, pp >= thr
ax.scatter(hours[~quake], np.clip(pp[~quake], 1e-3, 1), s=6, c="0.6", label="noise window") # floor at 0.001 for the log axis
ax.scatter(hours[quake], np.clip(pp[quake], 1e-3, 1), s=40, c="C1", edgecolor="k",
label="earthquake window", zorder=3)
ax.axhline(thr, ls="--", c="k", lw=1.5) # the firing threshold
ax.set_yscale("log"); ax.set_ylim(1e-3, 1.5)
ax.set_xlabel("time in the test record (h)")
ax.set_title(f"{name}: {np.sum(fire & quake)} of {quake.sum()} found, "
f"{np.sum(fire & ~quake)} false", loc="left")
axes[0].set_ylabel("probability of an earthquake")
axes[0].legend(loc="lower left", fontsize=11)
fig.tight_layout()
return ok
c3_t1 = time.time()
c3_evaluate(c3_fix(), "your fix")
print(f"({time.time() - c3_t1:.1f} s)") # time to train and evaluate your fixCase 3, your fix: 16.6 h of test record, 42 earthquakes, threshold 0.500
researcher (threshold 0.5): accuracy 0.979, recall 0.00, false alarms/day 0.0
your fix (threshold 0.50): accuracy 0.979, recall 0.00, false alarms/day 0.0
validation: earthquakes detected (recall) 0.00 target >= 0.75 FAIL
validation: false alarms per day 0.0 target <= 24 (1 per hour) PASS
test: earthquakes detected (recall) 0.00 target >= 0.75 FAIL
test: false alarms per day 0.0 target <= 24 (1 per hour) PASS
Case 3 verdict: FAIL
(1.1 s)

Our fix below (click to open it).
Notebook Cell
def c3_our_fix():
"""Our fix: weight the earthquake windows in the loss, then choose the threshold on validation.
Same network, seed, optimizer and epochs as the researcher. Two changes:
the loss weights each earthquake window by (noise windows / earthquake windows) in training, so the
earthquakes are no longer outvoted by the noise; the threshold is the lowest one that keeps the
validation false alarms within half of the observatory's budget.
Returns (model, threshold), like c3_fix().
"""
torch.manual_seed(0) # same random starting weights as the researcher
model = c3_make_detector()
n_quake = c3_ytr.sum() # earthquake windows in the training record
n_noise = len(c3_ytr) - n_quake # noise windows in the training record
# pos_weight multiplies the loss of every earthquake window: together, the earthquake windows weigh as much
# as all the noise windows, so scoring every window as noise no longer gives the lowest loss
criterion = nn.BCEWithLogitsLoss(pos_weight=n_noise / n_quake)
train(model, c3_Xtr, c3_ytr, c3_Xva, c3_yva, criterion,
epochs=15, lr=1e-3, batch_size=128, seed=0)
# Threshold: the lowest one that keeps validation false alarms at or below 12 per day
# (half of the requirement, a margin for a new stretch of record). A lower threshold detects more
# earthquakes, so the lowest one within the budget gives the highest recall it allows.
p_va = c3_scores(model, c3_Xva) # probabilities of the validation windows; the test is not used
candidates = np.round(np.arange(0.05, 1.0, 0.01), 2) # thresholds 0.05, 0.06, ..., 0.99
ok = [t for t in candidates if c3_rates(p_va, c3_yva.numpy(), t)[1] <= 12] # [1]: false alarms per day
threshold = float(min(ok))
rec_va, fa_va = c3_rates(p_va, c3_yva.numpy(), threshold)
print(f"validation: threshold {threshold:.2f}, recall {rec_va:.2f}, false alarms/day {fa_va:.1f}")
return model, threshold# Evaluate our fix: the same test as above
c3_t1 = time.time()
c3_evaluate(c3_our_fix(), "our fix")
print(f"({time.time() - c3_t1:.1f} s)") # time to train and evaluate our fixOutput
validation: threshold 0.44, recall 0.98, false alarms/day 11.5
Case 3, our fix: 16.6 h of test record, 42 earthquakes, threshold 0.440
researcher (threshold 0.5): accuracy 0.979, recall 0.00, false alarms/day 0.0
our fix (threshold 0.44): accuracy 0.992, recall 0.95, false alarms/day 18.8
validation: earthquakes detected (recall) 0.98 target >= 0.75 PASS
validation: false alarms per day 11.5 target <= 24 (1 per hour) PASS
test: earthquakes detected (recall) 0.95 target >= 0.75 PASS
test: false alarms per day 18.8 target <= 24 (1 per hour) PASS
Case 3 verdict: PASS
(1.1 s)

What went wrong
Cause. Earthquakes fill 2.3% of the windows (183 of 7983). With an unweighted cross-entropy, the noise windows make almost all of the loss, and the network lowers the loss most by scoring every window as noise. It does learn to rank: the median test earthquake scores 0.07 against 0.01 for noise, but no earthquake reaches 0.5 (the highest is 0.13), so the detector never fires. Accuracy rewards that: a detector that never fires is right on 97.9% of the test windows.
Why the symptom follows. The learning curves look healthy (both fall and flatten together) and the accuracy is high, yet the confusion matrix shows 0 of 42 test earthquakes reported. Accuracy is set by the noise windows, the class the observatory does not need flagged.
Fix. Weight the earthquake windows in the loss by the ratio of noise to earthquake windows (pos_weight), or resample the training windows so that each batch holds as many earthquakes as noise windows, and choose the threshold on the validation windows against a false-alarm budget. Report recall and false alarms per day of record, never accuracy alone.
How the evaluation proves it. The requirement (recall 0.75, 24 false alarms per day) is checked on validation, where the choices are made, and then on 16.6 hours of test record that no choice used. Our fix (weights, threshold 0.44 chosen on validation) has recall 0.98 and 11.5 false alarms per day on validation; on test it finds 40 of the 42 earthquakes (recall 0.95) with 13 false alarms, 18.8 per day. The test reads only the detections, so other fixes pass when they meet the requirement on both: class weights at a threshold of 0.5 (test recall 0.93, 5.8 per day), or batches resampled to hold as many earthquakes as noise windows (0.95, 0.0 per day). Moving the threshold alone on the researcher’s network is valid but marginal, because its earthquakes score only 0.01 to 0.13: at 0.04, chosen on validation, recall is 0.84 with 15.9 false alarms per day on validation and 0.81 with 5.8 on test, a pass; at 0.05 the validation recall is 0.73, the requirement is missed where the choice is made, and the evaluation fails it even though the test happens to give 0.79. Accuracy barely moves (0.979 to 0.992): it could not have told the two detectors apart.
Rubric items. A6 (the majority-class baseline: never firing scores 0.979), D2 (cross-entropy with class weights when classes are unbalanced), E2 (confusion matrix, recall and precision per class, accuracy against the majority class), D8 (the threshold is chosen on validation; the test is used once).
In real geoscience data. On continuous seismic records, earthquake windows are rare, and rarer still on a quiet station than during this swarm; the same holds for landslides in satellite scenes, eruptions in tremor records, and floods in discharge series. Observatories tune detectors by the false alarms per day an analyst can review and by the share of catalog events they miss, which is why both numbers belong in any report.
Case 4: A GNSS forecaster that beats persistence, until it does not¶
| Geoscience system | A continuous GNSS station on a plate interior, moving east at a steady 12 mm/yr (interseismic plate motion), with an annual and semi-annual hydrological loading cycle of a few mm and temporally correlated (flicker and random-walk) noise. Synthetic daily east positions from mlgeo_synth.gnss_series (10 years, 2015-2024, seed 4), standing in for a Nevada Geodetic Laboratory daily position series. |
| Data | One sample is 30 consecutive daily east positions (mm) and the position on the next day. 3,622 samples, one per day from 2015-01-31 to 2024-12-30. |
| Input and target | Input: the east positions of the last 30 days (mm). Target: the east position tomorrow (mm). |
| Split | By time. Test: every day of 2022-2024 (1,095 samples), never used for a choice. Validation: every April, August and December of 2015-2021 (644 samples), so that validation covers all seasons. Training: the other months of 2015-2021 (1,883 samples). |
| Model | Fully connected network, 30 inputs, two hidden layers of 32 neurons with tanh activations, one output. Inputs and target standardized with the mean and standard deviation of the training positions. |
| Training | Shared train() loop: mean squared error, Adam, learning rate 0.001, batch of 64, 60 epochs, seeded starting weights (seed 4), the epoch with the lowest validation loss kept. |
| Baseline | Persistence: tomorrow’s position is today’s position. |
| Success test for your fix | On the test days of 2022-2024: (1) mean absolute error at least 5% below persistence on the same days; (2) no growth of error with time, measured as the MAE of 2024 divided by the MAE of 2022, at most 1.2. |
| The researcher’s claim | “Validation mean absolute error (MAE) is 1.34 mm against 1.44 mm for persistence. The network forecasts tomorrow’s position better than repeating today’s, and is ready to run on new days.” |
# Case 4: the researcher's pipeline, as run
# --- data: one GNSS station, daily east position, 2015-2024
c4_df = mlgeo_synth.gnss_series(n_years=10, velocity_mm_yr=12.0, seed=4) # daily east position (mm)
c4_pos = c4_df["disp_mm"].to_numpy(np.float32) # (n_days,) east position (mm)
c4_N = 30 # days of input
def c4_windows(series, N=c4_N):
'''Cut a daily series into samples: the N previous days as input, the next day as target.
series: (n_days,) daily east positions (mm).
Returns X, (n_days - N, N) positions of the N previous days (mm), oldest first,
and y, (n_days - N,) the position on the next day (mm).
'''
X = np.stack([series[i - N:i] for i in range(N, len(series))])
return X, series[N:]
c4_X, c4_y = c4_windows(c4_pos) # (3622, 30) inputs, (3622,) targets (mm)
c4_date = c4_df["date"].to_numpy()[c4_N:] # date of each target day
c4_year = c4_df["date"].dt.year.to_numpy()[c4_N:]
c4_month = c4_df["date"].dt.month.to_numpy()[c4_N:]
# --- split by date: test 2022-2024, validation months and training months in 2015-2021
c4_is_test = c4_year >= 2022 # 2022-2024
c4_is_val = ~c4_is_test & (c4_month % 4 == 0) # April, August, December of 2015-2021
c4_is_tr = ~c4_is_test & ~c4_is_val # the other months of 2015-2021
c4_persist = c4_X[:, -1] # baseline: tomorrow = today
def c4_t(a):
'''Convert an array (or list) to a float32 torch tensor of the same shape.'''
return torch.tensor(np.asarray(a), dtype=torch.float32)
def c4_net(seed=4):
'''The forecaster: 30 daily positions in, one position out.
seed: seed of the random starting weights.
Returns the network 30 -> 32 -> 32 -> 1 with tanh activations.
'''
torch.manual_seed(seed) # seeded random starting weights
return nn.Sequential(nn.Linear(c4_N, 32), nn.Tanh(),
nn.Linear(32, 32), nn.Tanh(), nn.Linear(32, 1))
# --- standardize inputs and target with the training samples only
c4_mu, c4_sd = c4_X[c4_is_tr].mean(), c4_X[c4_is_tr].std() # one mean, one std (mm): inputs and target
c4_sc = lambda a: c4_t((a - c4_mu) / c4_sd) # positions (mm) -> standardized tensor
# --- train: 60 epochs, the epoch with the lowest validation loss is kept
c4_model = c4_net()
c4_hist = train(c4_model, c4_sc(c4_X[c4_is_tr]), c4_sc(c4_y[c4_is_tr])[:, None],
c4_sc(c4_X[c4_is_val]), c4_sc(c4_y[c4_is_val])[:, None],
nn.MSELoss(), epochs=60, lr=1e-3, batch_size=64, seed=4)
# --- forecast every day of 2015-2024, back in mm
with torch.no_grad():
c4_pred = c4_model(c4_sc(c4_X)).numpy().ravel() * c4_sd + c4_mu # mm, every day
c4_pred_researcher = c4_pred[c4_is_test] # (1095,) test days, kept for the evaluation plots
# the numbers they report, and the same numbers on the test years
c4_mae = lambda p, m: float(np.abs(p[m] - c4_y[m]).mean()) # mean absolute error (mm) of forecast p on days m
print(f"{'MAE (mm)':26s}{'network':>9s}{'persistence':>13s}")
for name, m in [("validation (2015-2021)", c4_is_val), ("test (2022-2024)", c4_is_test)] + \
[(f" test, {k}", c4_year == k) for k in (2022, 2023, 2024)]:
print(f"{name:26s}{c4_mae(c4_pred, m):9.2f}{c4_mae(c4_persist, m):13.2f}")
# evidence: learning curves, and one more diagnostic: prediction against observation in time
fig, (c4_a0, c4_a1) = plt.subplots(1, 2, figsize=(12, 4), gridspec_kw={"width_ratios": [1, 2]})
plot_curves(c4_hist, "a. learning curves", ax=c4_a0)
c4_a0.set_ylabel("loss (MSE, standardized)")
# panel b: observed and forecast east position on every day of 2015-2024
c4_a1.axhspan(c4_y[c4_is_tr].min(), c4_y[c4_is_tr].max(), color="C2", alpha=0.15,
label="range of training targets")
c4_a1.plot(c4_date, c4_y, color="0.55", lw=1, label="observed")
c4_a1.plot(c4_date, c4_pred, color="C3", lw=1.2, label="network, next day")
c4_a1.axvline(np.datetime64("2022-01-01"), color="k", ls=":", lw=1.5) # start of the test years
c4_a1.text(np.datetime64("2022-02-01"), c4_y.min(), "test", fontsize=13, va="bottom")
c4_a1.set_xlabel("year"); c4_a1.set_ylabel("east position (mm)")
c4_a1.set_title("b. prediction and observation", loc="left")
c4_a1.legend(loc="upper left"); c4_a1.grid(alpha=0.3)
plt.tight_layout(); plt.show()MAE (mm) network persistence
validation (2015-2021) 1.34 1.44
test (2022-2024) 8.57 1.53
test, 2022 3.06 1.49
test, 2023 8.19 1.55
test, 2024 14.46 1.54

What do you see?
On validation the network beats persistence; on the test years it does not. Besides the date, what differs between a validation day and a test day?
In panel b, when does the prediction leave the observations, and where is it then relative to the shaded band?
The test error grows from 2022 to 2024. Which property of this station grows at the same pace?
Your diagnosis (one sentence):
Hint
Print the smallest and largest target of the training samples, of the validation samples and of the test samples, and compare them with the top of the shaded band. Then ask what the network was shown during training for an input of 100 mm.
# Your fix
def c4_fix():
'''Retrain the forecaster and forecast every test day of 2022-2024.
Must return a dict {"pred": ..., "hist": ...}.
pred: the forecast east position (mm) for each test day of 2022-2024, in date order,
one value per row of c4_X[c4_is_test] (c4_is_test.sum() values, 1095 days).
hist: the training history returned by train(), or None.
The body below is the researcher's pipeline, unchanged. Use only 2015-2021 for any choice.'''
# your changes here
X, y = c4_X, c4_y # inputs (3622, 30) and target (3622,), mm
mu, sd = X[c4_is_tr].mean(), X[c4_is_tr].std() # training samples only
sc = lambda a: c4_t((a - mu) / sd) # positions (mm) -> standardized tensor
model = c4_net() # same network and seed as the researcher
# train on the training months, keep the epoch with the lowest loss on the validation months
hist = train(model, sc(X[c4_is_tr]), sc(y[c4_is_tr])[:, None],
sc(X[c4_is_val]), sc(y[c4_is_val])[:, None],
nn.MSELoss(), epochs=60, lr=1e-3, batch_size=64, seed=4)
# forecast the test days and convert back to mm
with torch.no_grad():
pred = model(sc(X[c4_is_test])).numpy().ravel() * sd + mu
return {"pred": pred, "hist": hist}# Evaluate your fix
import matplotlib.dates as mdates
def c4_evaluate(result, label="your fix"):
'''Success test of the context card on the test days of 2022-2024; it tests the numbers, not the code.
(1) test MAE at least 5% below persistence on the same days;
(2) no growth of error with time: MAE of 2024 at most 1.2 times the MAE of 2022.
result: the dict returned by c4_fix(), with "pred" the (1095,) forecast positions (mm) of the test days.
label: name of the fix in the printout and the legends.
Returns True if both tests pass, and plots the test-year forecasts and the error of each year.'''
y, yr = c4_y[c4_is_test].astype(float), c4_year[c4_is_test] # observed positions (mm) and year of each test day
pred = np.asarray(result["pred"], dtype=float).ravel()
# the forecast must give one finite position per test day
if pred.shape != y.shape or not np.all(np.isfinite(pred)):
print(f"pred must hold {y.size} finite positions (mm), one per test day; got shape {pred.shape}")
print("Case 4: FAIL")
return False
# absolute error (mm) on each test day: the fix, persistence, the researcher's network
err, err_p, err_r = (np.abs(p - y) for p in (pred, c4_persist[c4_is_test], c4_pred_researcher))
mae, mae_p = err.mean(), err_p.mean()
growth = err[yr == 2024].mean() / err[yr == 2022].mean() # 1 if the error does not grow with time
print(f"{label}: next-day forecasts of {y.size} test days, 2022-2024")
ok = [check("test MAE (mm)", f"{mae:.2f}", f"<= {0.95 * mae_p:.2f} (0.95 x pers.)", mae <= 0.95 * mae_p),
check("MAE 2024 / MAE 2022", f"{growth:.2f}", "<= 1.20", growth <= 1.20)]
print(f"Case 4: {'PASS' if all(ok) else 'FAIL'}")
# panel a: test-year forecasts against observations and the range of the training targets
fig, (ax0, ax1) = plt.subplots(1, 2, figsize=(12, 4), gridspec_kw={"width_ratios": [2, 1]})
d = c4_date[c4_is_test]
ax0.axhspan(c4_y[c4_is_tr].min(), c4_y[c4_is_tr].max(), color="C2", alpha=0.15,
label="range of training targets")
ax0.plot(d, y, color="0.55", lw=1, label="observed")
ax0.plot(d, c4_pred_researcher, color="C3", lw=2.5, label="researcher")
ax0.plot(d, pred, color="C0", lw=1.2, label=label)
ax0.set_ylim(min(y.min(), pred.min()) - 15, max(y.max(), pred.max()) + 5) # 15 mm margin below, 5 mm above
ax0.xaxis.set_major_locator(mdates.YearLocator()); ax0.xaxis.set_major_formatter(mdates.DateFormatter("%Y"))
ax0.set_xlabel("year"); ax0.set_ylabel("east position (mm)")
ax0.set_title("a. test years, next-day forecast", loc="left")
ax0.legend(loc="upper left", ncol=2); ax0.grid(alpha=0.3)
# panel b: MAE of each test year, for persistence, the researcher and the fix
years = np.array([2022, 2023, 2024])
for i, (e, name, c) in enumerate([(err_p, "persistence", "0.55"),
(err_r, "researcher", "C3"), (err, label, "C0")]):
ax1.bar(years + (i - 1) * 0.27, [e[yr == k].mean() for k in years], 0.27, color=c, label=name)
ax1.set_yscale("log"); ax1.set_ylim(1, 30); ax1.set_xticks(years)
ax1.set_yticks([1, 2, 5, 10, 20], ["1", "2", "5", "10", "20"]); ax1.minorticks_off()
ax1.set_xlabel("test year"); ax1.set_ylabel("MAE (mm, log axis)")
ax1.set_title("b. error by year", loc="left"); ax1.legend(fontsize=13); ax1.grid(alpha=0.3, axis="y")
plt.tight_layout(); plt.show()
return all(ok)
c4_result = c4_fix()
c4_evaluate(c4_result, "your fix");your fix: next-day forecasts of 1095 test days, 2022-2024
test MAE (mm) 8.57 target <= 1.45 (0.95 x pers.) FAIL
MAE 2024 / MAE 2022 4.72 target <= 1.20 FAIL
Case 4: FAIL

Our fix below (click to open it).
Notebook Cell
def c4_our_fix():
'''Our fix: forecast tomorrow's change in position, then add it to today's position.
The station moves 12 mm/yr east, so nearly all test positions of 2022-2024 (97%) lie above every
training position; a daily change in 2024 looks like a daily change in 2015, so the test inputs and
targets stay inside what the network saw in training.
Validation moves to 2021, after the training years 2015-2020, as the test follows them.
Returns {"pred": (1095,) forecast positions (mm) of the test days, "hist": training history}.'''
is_tr, is_va = c4_year <= 2020, c4_year == 2021 # time-forward split inside 2015-2021
today = c4_X[:, -1:] # (3622, 1) today's position (mm)
X = c4_X - today # the last 30 days relative to today (mm): the accumulated plate-motion offset is removed
y = c4_y - today[:, 0] # tomorrow's change (mm): 99% within 5 mm, all within 7.4 mm
mu_x, sd_x = X[is_tr].mean(), X[is_tr].std() # training samples only
mu_y, sd_y = y[is_tr].mean(), y[is_tr].std() # the target gets its own scale
model = c4_net() # same network and seed as the researcher
hist = train(model, c4_t((X[is_tr] - mu_x) / sd_x), c4_t((y[is_tr] - mu_y) / sd_y)[:, None],
c4_t((X[is_va] - mu_x) / sd_x), c4_t((y[is_va] - mu_y) / sd_y)[:, None],
nn.MSELoss(), epochs=60, lr=1e-3, batch_size=64, seed=4)
with torch.no_grad():
change = model(c4_t((X[c4_is_test] - mu_x) / sd_x)).numpy().ravel() * sd_y + mu_y # mm
return {"pred": today[c4_is_test, 0] + change, "hist": hist} # back to position: today + change# Evaluate our fix with the same success test as yours
c4_evaluate(c4_our_fix(), "our fix");Output
our fix: next-day forecasts of 1095 test days, 2022-2024
test MAE (mm) 1.31 target <= 1.45 (0.95 x pers.) PASS
MAE 2024 / MAE 2022 1.02 target <= 1.20 PASS
Case 4: PASS

What went wrong
Cause. The station moves east by 12 mm every year, so its position never comes back. The network was trained on positions from -1.4 to 83.3 mm (2015-2021); the test targets run from 79.2 to 124.0 mm, and 97% of them lie above the top of the training range. Above 83 mm the network has no training targets, so its forecast there is an extrapolation. It keeps rising, but at about 6.4 mm/yr instead of the station’s 12.1 (yearly mean forecast 87.3, 95.0 and 100.1 mm against observed 90.3, 103.2 and 114.6 mm in 2022, 2023 and 2024), and reaches 102.5 mm when the station is at 124.0 mm. The error grows each year: 3.06, 8.19 and 14.46 mm. The validation months sat inside the training years, and so inside the training range, which is why validation could not see it. A second, minor leak: the 30-day input of each validation day reaches back into the training month before it, so the first days of every validation month share inputs with training samples. It is not the cause of the test failure: training on 2015-2020 and validating on 2021, with the position still as the target, fails as before (test MAE 14.14 mm, 2024/2022 ratio 3.66).
Fix. Take the plate motion out of the quantity the network learns: give it the last 30 days relative to today and ask for tomorrow’s change, then add the change to today’s position. A daily change in 2024 looks like a daily change in 2015, so the test inputs fall inside the training range. Removing a trend fitted on 2015-2021 only, and adding it back, works too.
How the evaluation shows it. Our fix forecasts the change and also validates on 2021, after its training years 2015-2020, as rubric A4 asks. On the 1,095 test days it has an MAE of 1.31 mm against 1.53 mm for persistence (researcher: 8.57 mm), and the ratio of the 2024 to the 2022 MAE is 1.02 (researcher: 4.72). The same change target with the researcher’s validation months gives 1.31 mm and 1.03: the target, not the validation months, decided the test.
Rubric items. A7 (check the range; predict a change or an anomaly), A6 and C3.3 (persistence baseline on the same days), A4 (validate on later times, along the deployment axis, not on months inside the training years), E5 (one test along the deployment axis).
In real geoscience data. Any record with a trend leaves its training range: GNSS positions under plate motion or postseismic relaxation, cumulative subsidence over a pumped aquifer, the Mauna Loa CO2 record of notebook 4.10, sea level, glacier thinning, river discharge in a basin that is warming. Forecasting the change, or the anomaly relative to a trend fitted on the training period, is standard for these series.
Case 5: The training loss climbs back up¶
A researcher wants to know whether a network classifies igneous rocks better than a linear boundary does. Granite, andesite and basalt sit along one differentiation trend: the more evolved the magma, the more SiO and KO and the less FeO, MgO and CaO. The question is whether the boundaries between the three rock types along that trend are curved enough to need hidden layers.
| Geoscience system | Igneous rocks along a differentiation trend, basalt to andesite to granite (synthetic table, mlgeo_synth.geochem_table, the table of 4.7) |
| Data | 3000 rock samples. One sample is one rock: 9 measurements, seven major-element oxides (wt%), density (g/cm) and magnetic susceptibility (SI). Granite 56%, basalt 34%, andesite 10% |
| Input and target | Input: the 9 measurements. Target: the rock type (3 classes) |
| Split | Random, 2250 training and 750 validation samples. Features standardized with the mean and standard deviation of the training samples only, then the measurement-noise floor of 4.7 (one standard deviation per feature) added to every sample |
| Model | Fully connected network, 9 inputs, two hidden layers of 64 neurons with ReLU, 3 class scores (4995 weights). Starting weights random with seed 0 |
| Training | Cross-entropy, Adam, learning rate 0.001, batches of 128, 30 epochs. The researcher wrote their own epoch loop (in the code below) and passed it to the course’s train(), which keeps the weights of the epoch with the lowest validation loss |
| Comparison | Reference run: the same model, split, seed and settings, trained with the epoch loop of 4.7 section 2.4 (the four lines you wrote). It shows what a correct run of this model gives, as a control does in a lab experiment. A logistic regression (scikit-learn) was fit on the same split |
| The researcher’s claim | “The network reaches a validation accuracy of 0.939, below the 0.951 of logistic regression. Hidden layers do not help on this table; we report the linear model.” |
| Success test for your fix | Same data, model, seed and 30 epochs. Validation accuracy within 0.005 of the reference run; training loss at the last epoch at most 1.2 times the reference run’s; the training loss rises by more than 10% from one epoch to the next at most once |
# Case 5: the researcher's pipeline, as run
from sklearn.linear_model import LogisticRegression
from torch.optim.optimizer import register_optimizer_step_pre_hook
from matplotlib.ticker import FixedLocator, NullFormatter, ScalarFormatter
def c5_loss_ticks(ax):
'''Plain numbers on a logarithmic loss axis.
ax: the matplotlib axis whose y axis (cross-entropy loss) gets ticks at 0.1, 0.2, 0.3, 0.5 and 1.0.
'''
ax.yaxis.set_major_locator(FixedLocator([0.1, 0.2, 0.3, 0.5, 1.0]))
ax.yaxis.set_major_formatter(ScalarFormatter()) # 0.2 rather than 2 x 10^-1
ax.yaxis.set_minor_formatter(NullFormatter()) # no labels on the minor ticks
# --- data: 3000 rock samples, 9 measurements, 3 rock types
C5_CLASSES = ["granite", "basalt", "andesite"] # class 0, 1, 2
c5_df = mlgeo_synth.geochem_table(n=3000, seed=5) # one row per rock, plus a "label" column
c5_features = [c for c in c5_df.columns if c != "label"] # 7 oxides (wt%), density (g/cm3), susceptibility (SI)
c5_X = c5_df[c5_features].to_numpy(np.float32) # (3000, 9) measurements
c5_y = c5_df["label"].map({c: i for i, c in enumerate(C5_CLASSES)}).to_numpy() # (3000,) rock type 0, 1 or 2
# --- split: random, 2250 training / 750 validation
c5_rng = np.random.default_rng(5) # one generator for the split and the noise
c5_order = c5_rng.permutation(len(c5_X)) # shuffle the 3000 rocks
c5_itr, c5_iva = c5_order[:2250], c5_order[2250:] # 75% training, 25% validation
# standardize with training statistics only, then add the measurement-noise floor of notebook 4.7 (1 std per measurement)
c5_mu, c5_sd = c5_X[c5_itr].mean(0), c5_X[c5_itr].std(0) # (9,) mean and std of the training rocks
c5_Xs = (c5_X - c5_mu) / c5_sd + c5_rng.normal(0, 1, c5_X.shape) # noise of one standard deviation per measurement
c5_Xtr = torch.tensor(c5_Xs[c5_itr], dtype=torch.float32) # (2250, 9) training rocks
c5_Xva = torch.tensor(c5_Xs[c5_iva], dtype=torch.float32) # (750, 9) validation rocks
c5_ytr, c5_yva = torch.tensor(c5_y[c5_itr]), torch.tensor(c5_y[c5_iva])
# --- model: 9 -> 64 -> 64 -> 3
def c5_make_model(seed=0):
'''The rock classifier: 9 measurements in, one score per rock type out (4995 weights).
seed: seed of the random starting weights.
Returns the untrained network.
'''
torch.manual_seed(seed) # random starting weights, recorded seed
return nn.Sequential(nn.Linear(9, 64), nn.ReLU(),
nn.Linear(64, 64), nn.ReLU(),
nn.Linear(64, 3)) # one score per rock type
def c5_accuracy(model, X, y):
'''Fraction of rocks whose highest score is their true rock type.
X: (n_rocks, 9) standardized measurements; y: (n_rocks,) rock types 0, 1 or 2.
Returns a float between 0 and 1.
'''
model.eval()
with torch.no_grad():
return (model(X).argmax(1) == y).float().mean().item() # argmax: the rock type with the highest score
# --- the researcher's own epoch loop
def c5_researcher_epoch(model, opt, criterion, X, y, batch_size, g):
'''My epoch: shuffle the 2250 rocks, then update the weights once per batch of 128.
X, y: the 2250 training rocks and their rock types; g: the random generator that orders them.
Called once per epoch by train(); returns nothing, the weights of model change in place.
'''
order = torch.randperm(len(X), generator=g) # a new order of the training rocks
for i in range(0, len(X), batch_size): # 128 rocks per batch
idx = order[i:i + batch_size]
loss = criterion(model(X[idx]), y[idx]) # cross-entropy of this batch
loss.backward()
opt.step() # Adam updates the weights
def c5_train(epoch_fn, seed=0):
'''The 30-epoch run of the context card, with the epoch loop given.
epoch_fn: the epoch loop that train() calls once per epoch.
Returns (model, hist): the network at its best validation epoch and the losses of every epoch.
'''
model = c5_make_model(seed)
hist = train(model, c5_Xtr, c5_ytr, c5_Xva, c5_yva, nn.CrossEntropyLoss(),
epochs=30, lr=1e-3, batch_size=128, optimizer="adam",
seed=seed, epoch_fn=epoch_fn)
return model, hist
# --- train: the researcher's run, the reference run and the linear baseline, all on the same split
c5_model, c5_hist = c5_train(c5_researcher_epoch) # the researcher's run
c5_ref_model, c5_ref_hist = c5_train(one_epoch) # the reference run (4.7 loop)
c5_logit = LogisticRegression(max_iter=3000).fit(c5_Xtr.numpy(), c5_ytr.numpy()) # linear boundaries
# validation accuracy of the three models (750 validation rocks)
c5_acc = c5_accuracy(c5_model, c5_Xva, c5_yva)
c5_ref_acc = c5_accuracy(c5_ref_model, c5_Xva, c5_yva)
c5_logit_acc = c5_logit.score(c5_Xva.numpy(), c5_yva.numpy())
c5_ref_last = c5_ref_hist["train_loss"][-1] # reference training loss at the last of the 30 epochs (epoch 29, counted from 0)
# --- one more diagnostic: the size of the gradient the optimizer receives at each update
def c5_gradient_sizes(epoch_fn, seed=0):
'''Rerun c5_train and record the norm of all gradients just before each update.
epoch_fn: the epoch loop to rerun; seed: the seed of the starting weights.
Returns an array of 540 gradient norms (30 epochs x 18 updates), one per update.
'''
sizes = []
def record(opt, args, kwargs):
'''Append the norm of the gradient over all 4995 weights that the coming update will use.'''
sq = sum((p.grad ** 2).sum() for grp in opt.param_groups
for p in grp["params"] if p.grad is not None) # sum of squares over all weights
sizes.append(float(sq) ** 0.5)
handle = register_optimizer_step_pre_hook(record) # record() runs before every opt.step()
try:
c5_train(epoch_fn, seed)
finally:
handle.remove() # later runs are not recorded
return np.array(sizes)
c5_grad = c5_gradient_sizes(c5_researcher_epoch)
c5_ref_grad = c5_gradient_sizes(one_epoch)
# --- the numbers
print(f"{'':34s} {'researcher':>11s} {'reference':>10s} {'logistic':>9s}")
print(f"{'validation accuracy':34s} {c5_acc:11.3f} {c5_ref_acc:10.3f} {c5_logit_acc:9.3f}")
c5_se = (c5_ref_acc * (1 - c5_ref_acc) / len(c5_yva)) ** 0.5 # binomial standard error, 750 rocks
print(f"one standard error of a validation accuracy near {c5_ref_acc:.3f} on {len(c5_yva)} samples: {c5_se:.3f}")
for name, h in [("researcher", c5_hist), ("reference", c5_ref_hist)]:
tl = np.array(h["train_loss"]) # training loss, one value per epoch
print(f"{name:11s} training loss: lowest {tl.min():.3f} at epoch {tl.argmin()}, "
f"last epoch {tl[-1]:.3f}; best validation epoch {h['best_epoch']}")
print(f"size of the gradient at update 1 and update {len(c5_grad)}: "
f"researcher {c5_grad[0]:.2f} -> {c5_grad[-1]:.2f}, "
f"reference {c5_ref_grad[0]:.2f} -> {c5_ref_grad[-1]:.2f}")
# --- the figure: two learning curves on a log axis, and the gradient at each update
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
plot_curves(c5_hist, "A. researcher's loop", ax=axes[0], logy=True)
plot_curves(c5_ref_hist, "B. reference run, 4.7 loop", ax=axes[1], logy=True)
# same loss range on panels A and B, so the two runs compare by eye
lo = min(min(h[k]) for h in (c5_hist, c5_ref_hist) for k in ("train_loss", "val_loss"))
hi = max(max(h[k]) for h in (c5_hist, c5_ref_hist) for k in ("train_loss", "val_loss"))
for ax in axes[:2]:
ax.set_ylim(0.8 * lo, 1.25 * hi)
ax.set_ylabel("cross-entropy loss (nats)")
c5_loss_ticks(ax)
axes[2].semilogy(np.arange(1, len(c5_grad) + 1), c5_grad, lw=1.5, color="tab:red", label="researcher")
axes[2].semilogy(np.arange(1, len(c5_ref_grad) + 1), c5_ref_grad, lw=1.5, color="0.4", label="reference run")
axes[2].set_xlabel("update (18 per epoch)") # 2250 rocks / 128 per batch, rounded up
axes[2].set_ylabel(r"gradient size $|\partial L/\partial w|$")
axes[2].set_title("C. gradient size", loc="left")
axes[2].legend(); axes[2].grid(alpha=0.3)
fig.suptitle("Rock type from 9 measurements, synthetic (mlgeo_synth)", fontsize=15, x=0.01, ha="left")
plt.tight_layout()
plt.show() researcher reference logistic
validation accuracy 0.939 0.953 0.951
one standard error of a validation accuracy near 0.953 on 750 samples: 0.008
researcher training loss: lowest 0.182 at epoch 5, last epoch 0.311; best validation epoch 5
reference training loss: lowest 0.105 at epoch 29, last epoch 0.105; best validation epoch 14
size of the gradient at update 1 and update 540: researcher 0.84 -> 64.77, reference 0.84 -> 0.16

What do you see?
Panel A: after its low at epoch 5, the researcher’s training loss jumps up and down and ends higher. The data, the model and the learning rate are the same as in panel B. What could make a network fit the same 2250 samples worse with more training?
Panel C: in the first epochs the loss falls in both runs. What should happen to the size of the gradient as the network approaches a minimum of the loss, and what happens in the researcher’s run?
Read the researcher’s
c5_researcher_epochnext to the four lines you wrote in 4.7 section 2.4.
Your diagnosis (one sentence):
Hint
The gradient in panel C grows from one update to the next, even while the loss of each batch is falling. A gradient computed from one batch of 128 samples cannot do that. PyTorch stores the gradient of each weight in .grad between two calls to .backward(). What does .backward() do with a value that is already there, and which line of the loop is supposed to clear it?
# Your fix: edit this cell
def c5_fix():
'''Retrain the researcher's network on the same split (c5_Xtr, c5_ytr, c5_Xva, c5_yva).
Must return (model, hist): the trained network and the dictionary returned by train().
Keep the data, the model (c5_make_model(seed=0)), the seed and the 30 epochs;
change only what your diagnosis points to.
'''
# your changes here
# the researcher's epoch loop, copied from c5_researcher_epoch
def epoch_fn(model, opt, criterion, X, y, batch_size, g):
'''The researcher's epoch: shuffle the 2250 rocks, then update the weights once per batch of 128.'''
order = torch.randperm(len(X), generator=g) # a new order of the training rocks
for i in range(0, len(X), batch_size): # 128 rocks per batch
idx = order[i:i + batch_size]
loss = criterion(model(X[idx]), y[idx]) # cross-entropy of this batch
loss.backward()
opt.step() # Adam updates the weights
# the run of the context card: same model, seed, split and 30 epochs
model = c5_make_model(seed=0)
hist = train(model, c5_Xtr, c5_ytr, c5_Xva, c5_yva, nn.CrossEntropyLoss(),
epochs=30, lr=1e-3, batch_size=128, optimizer="adam",
seed=0, epoch_fn=epoch_fn)
return model, hist# Evaluate your fix against the success test of the context card
def c5_evaluate(result, label="your fix"):
'''Score a fix: validation accuracy and the shape of the training curve, against the reference run.
result: (model, hist) as returned by c5_fix(); label: the name of the run in the table and figure.
Prints one PASS or FAIL line per test, plots the loss curves, and returns True if all three tests pass.
'''
model, hist = result
acc = c5_accuracy(model, c5_Xva, c5_yva) # on the 750 validation rocks
tl = np.array(hist["train_loss"]) # training loss, one value per epoch (30)
rises = int((np.diff(tl) > 0.10 * tl[:-1]).sum()) # epochs whose loss is > 10% above the epoch before
# the three tests of the context card; 0.005 and 1.2 are the tolerances it states
ok = [
check("validation accuracy", f"{acc:.3f}",
f">= {c5_ref_acc - 0.005:.3f} ({c5_ref_acc:.3f}-0.005)",
acc >= c5_ref_acc - 0.005),
check("training loss at the last epoch", f"{tl[-1]:.3f}",
f"<= {1.2 * c5_ref_last:.3f} (1.2 x {c5_ref_last:.3f})", tl[-1] <= 1.2 * c5_ref_last),
check("epochs where training loss rises > 10%", f"{rises}", "<= 1", rises <= 1),
]
verdict = all(ok)
print(f"\nCase 5: {'PASS' if verdict else 'FAIL'}")
# the figure: training and validation loss of the researcher, the reference run and the fix
fig, axes = plt.subplots(1, 2, figsize=(12, 4), sharey=True)
for ax, key, name in zip(axes, ["train_loss", "val_loss"], ["training", "validation"]):
ax.plot(c5_hist[key], lw=2.5, color="tab:red", label="researcher")
ax.plot(c5_ref_hist[key], lw=4, color="0.75", label="reference run (4.7 loop)")
ax.plot(hist[key], lw=2, ls="--", color="tab:blue", label=label)
ax.set_yscale("log"); ax.grid(alpha=0.3); c5_loss_ticks(ax)
ax.set_xlabel("epoch"); ax.set_title(f"{name} loss", loc="left")
axes[0].set_ylabel("cross-entropy loss (nats)")
fig.legend(*axes[0].get_legend_handles_labels(), loc="lower center", ncol=3)
fig.suptitle("Rock type from 9 measurements, synthetic (mlgeo_synth): before and after the fix",
fontsize=15, x=0.01, ha="left")
plt.tight_layout(rect=(0, 0.1, 1, 1)) # leave the bottom 10% for the legend
plt.show()
return verdict
c5_evaluate(c5_fix());validation accuracy 0.939 target >= 0.948 (0.953-0.005) FAIL
training loss at the last epoch 0.311 target <= 0.125 (1.2 x 0.105) FAIL
epochs where training loss rises > 10% 8 target <= 1 FAIL
Case 5: FAIL

Our fix below (click to open it).
Notebook Cell
def c5_our_fix():
'''Our fix: clear the gradients before each backward pass, as in 4.7 section 2.4.
Returns (model, hist).
'''
def epoch_fn(model, opt, criterion, X, y, batch_size, g):
'''The researcher's epoch loop with opt.zero_grad() added: each update uses the gradient of one batch.'''
order = torch.randperm(len(X), generator=g) # a new order of the 2250 training rocks
for i in range(0, len(X), batch_size): # 128 rocks per batch
idx = order[i:i + batch_size]
opt.zero_grad() # the missing line: start each batch from zero
loss = criterion(model(X[idx]), y[idx]) # cross-entropy of this batch
loss.backward() # .grad holds this batch's gradient only, not the sum since the first batch
opt.step() # Adam steps along the current batch, so the run can settle at a minimum
# nothing else changes: same model, seed, split, learning rate and 30 epochs
model = c5_make_model(seed=0)
hist = train(model, c5_Xtr, c5_ytr, c5_Xva, c5_yva, nn.CrossEntropyLoss(),
epochs=30, lr=1e-3, batch_size=128, optimizer="adam",
seed=0, epoch_fn=epoch_fn)
return model, hist# Evaluate our fix
c5_fixed = c5_our_fix() # (model, hist)
c5_evaluate(c5_fixed, "our fix");
# A held-out test the validation set cannot give: 3000 new rocks (seed 55), the same
# standardization (training means and standard deviations) and the same noise floor.
# The 750 validation rocks also chose the best epoch, so they favor the network a little;
# no choice saw these rocks.
c5_new = mlgeo_synth.geochem_table(n=3000, seed=55)
c5_new_X = (c5_new[c5_features].to_numpy(np.float32) - c5_mu) / c5_sd # (3000, 9), training statistics
c5_new_X = (c5_new_X + np.random.default_rng(55).normal(0, 1, c5_new_X.shape)).astype(np.float32) # noise floor, 1 std
c5_new_y = c5_new["label"].map({c: i for i, c in enumerate(C5_CLASSES)}).to_numpy()
# the fixed network against the linear baseline, both on the new rocks
c5_new_acc = c5_accuracy(c5_fixed[0], torch.tensor(c5_new_X), torch.tensor(c5_new_y))
c5_new_logit = c5_logit.score(c5_new_X, c5_new_y)
print(f"3000 new rocks (seed 55): fixed network {c5_new_acc:.3f}, logistic regression {c5_new_logit:.3f}, "
f"one standard error {(c5_new_acc * (1 - c5_new_acc) / len(c5_new_y)) ** 0.5:.3f}")Output
validation accuracy 0.953 target >= 0.948 (0.953-0.005) PASS
training loss at the last epoch 0.105 target <= 0.125 (1.2 x 0.105) PASS
epochs where training loss rises > 10% 0 target <= 1 PASS
Case 5: PASS

3000 new rocks (seed 55): fixed network 0.944, logistic regression 0.942, one standard error 0.004
What went wrong
Cause. The researcher’s loop never calls opt.zero_grad(). PyTorch adds each new gradient to the one already stored in .grad, so the update at batch k uses the sum of the gradients of all k batches since the start, not the gradient of the batch k. The size of that gradient grows from 0.84 at the first update to 64.77 at the 540th (panel C), while that of the reference run falls to 0.16.
Why the curve looks like this. Adam divides each step by a running size of the gradient, so the steps do not blow up; but their direction follows the old batches more than the current one. The network passes its minimum and cannot settle: the training loss is lowest at epoch 5 (0.182), then jumps between epochs and ends at 0.311, three times the 0.105 of the reference run. The checkpoint of train() saved epoch 5, which is why the validation accuracy (0.939) looks only a little low.
Fix. Add opt.zero_grad() before loss.backward() in each batch (or pass the course’s one_epoch to train()).
How the evaluation shows it. With the same data, model and seed, the fixed loop gives a validation accuracy of 0.953, the number of the reference run, a training loss of 0.105 at the last epoch, and no epoch where the training loss rises by more than 10%. The researcher’s claim does not survive: the network (0.953) and logistic regression (0.951) tie: the difference is smaller than one standard error of a validation accuracy on 750 samples (0.008). The network is not worse than the linear boundary. Both numbers come from the 750 validation samples that also chose the epoch, a small selection in the network’s favor; on 3000 new rocks that no choice saw (seed 55, same scaling and noise floor), the fixed network scores 0.944 and the logistic regression 0.942, still a tie. Lowering the learning rate to 0.0001 without the missing line is not a fix: validation accuracy 0.939 and training loss 0.170 at the last epoch, and the test fails.
Rubric items. D3 (each update uses the mean loss of one batch), D4 (training and validation loss at every epoch: the curve exposed the error), D5 (an erratic curve looks like a learning-rate problem, and changing the learning rate does not cure this one), E3 and F4 (a network-versus-baseline claim needs a training run you trust, and a difference this small is a tie).
In real geoscience data. It appears most often in custom loops for large inputs: 3D seismic volumes, long continuous seismograms or multi-band satellite scenes, where only a few samples fit in memory and researchers sum gradients over several batches on purpose before one update. The line that clears the gradients then moves, or goes missing, and the curve drifts upward while nothing in the data changed.
The five errors in one table¶
Open after you have played the five cases
| Case | Symptom | Cause | Check that the fix worked | Rubric |
|---|---|---|---|---|
| 1. Earthquake detector | Validation 0.962 and test 0.971, but 0.761 on new events | The 5 shifted windows of one record fell on both sides of the split | No record on both sides of the split; validation and new-events accuracy agree within 0.06 (fix: 0.779 and 0.792) | A3, A4, E5 |
| 2. Rock classifier | Every specimen called granite; training loss flat at the loss of the class proportions (0.928) | Columns in ppm, kg/m and 10 SI entered the network unscaled next to wt% | Test accuracy and andesite recall at least those of a logistic regression on the same spreadsheet, 0.974 and 0.854 (fix: 0.985 and 0.939) | C1.1, A5, A6, E2 |
| 3. Swarm detector | Accuracy 0.979, 0 of 42 test earthquakes detected | Earthquakes are 2.3% of the windows; unweighted loss and a threshold of 0.5 | Recall at least 0.75 with at most 24 false alarms per day, on validation and on test (fix, test: 0.95 and 18.8) | A6, D2, E2, D8 |
| 4. GNSS forecaster | Beats persistence on validation; test error 8.57 mm against 1.53 mm, growing each year | The station moved past the range of positions seen in training; validation months sat inside the training years | Test MAE 5% below persistence, MAE 2024 / 2022 at most 1.2 (fix: 1.31 mm, 1.02) | A7, A4, A6, E5 |
| 5. Rock classifier, own loop | Training loss lowest at epoch 5, then rises and jumps | No opt.zero_grad(): each update used the sum of all gradients since the start | Same validation accuracy and final training loss as the reference run, no rising epochs (fix: 0.953, 0.105, 0) | D3, D4, D5, E3 |
Reflection¶
Two or three sentences each.
What you learned. Which case took your team longest to diagnose, and which piece of evidence finally gave the cause away?
What you learned from the agents. If an assistant helped you diagnose or fix a case, which of its suggestions was wrong, and how did you find out (which number, which figure)?
How to improve this game. Which case was too easy or too hard, and which error from your own project would you add as a sixth case?