This clinic belongs to the 4.7 training block, and it is optional practice on real records. The lab of 4.7 (Training and evaluating a network) measures each decision on a synthetic lithology table, where every defect is planted and its cost is known exactly. The clinic came first; the lab was then rebuilt in its order on synthetic data, so that each cost can be measured against a known truth. Here nothing is planted, and the numbers are those of real Pacific Northwest records. Homework_DL takes the six decisions of its part 4 from these stations, so the clinic is also a rehearsal for it.
Notebook 4.3 trained a convolutional detector on synthetic seismograms. Today the records are real: miniPNW, a labeled subset of the Pacific Northwest AI-ready benchmark (Ni et al., 2023) that you met in 2.11. Each record is three components of ground velocity (north, east, vertical) at one station, labeled by the Pacific Northwest Seismic Network analysts as an earthquake, an explosion (mostly quarry blasts), a surface event (rockfall, avalanche, debris flow), a sonic boom or thunder.
The task: a binary classifier. From 30 s of three-component ground motion, decide whether the window holds an event (any of the five sources) or no event (background noise only). This is the first step of every catalog: detection, before anyone asks what the source was.
The network is fixed and small. What changes from station to station is one decision a modeler makes while training:
| Station | Decision | Question you answer with a number |
|---|---|---|
| 1 | Train, validation and test sets; leakage | How much does the test score change with the way you split? |
| 2 | Starting weights | What happens if every weight starts at zero? |
| 3 | Learning rate and batch size | Which pairs train, and which do not? |
| 4 | Model size and amount of data | Would more data or a bigger network help more? |
| 5 | Data augmentation | Does the network still work when the arrival is not where it was in training? |
| 6 | The loss | When events are rare, which loss still finds them, and at what cost in false alarms? |
How to work. Take two stations, or all six. Run sections 0 to 2 first: they load the data and define the training code that every station uses. In each station:
Predict the result before you run anything, and write the prediction in the cell provided.
Write the short cell marked Your turn. If you leave it empty, a hidden cell uses a reference answer so the rest of the station still runs.
Run and compare with your prediction.
Write one rule for training a network, backed by the number you measured, in the format of section 9, and find the item of the course rubric (4.7, continued) that covers the same decision.
Every station runs in one to three minutes on a laptop CPU.
0. Setup¶
import os
import sys
import time
try:
import h5py
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.signal import decimate
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import balanced_accuracy_score, confusion_matrix, recall_score
from sklearn.model_selection import GroupShuffleSplit
except ModuleNotFoundError as err:
raise ModuleNotFoundError(
f"'{err.name}' is not installed in this kernel ({sys.executable}).\n"
"Use the course environment. In VS Code: 'Select Kernel' (top right), then 'Python Environments', "
"then the one in .pixi/envs/default, or 'Python (mlgeo-book pixi)'. "
"In a terminal, from the mlgeo-book folder: pixi install, then pixi run jupyter lab.") from None
device = torch.device("cpu") # every station is sized for a laptop CPU
torch.set_num_threads(max(1, min(4, os.cpu_count() or 1)))
SEED = 469 # the seed of every random choice in this notebook
rng = np.random.default_rng(SEED)
plt.rcParams.update({"font.size": 12})
print("PyTorch", torch.__version__, "| threads:", torch.get_num_threads())1. The data: 1,720 records from the Pacific Northwest¶
The two miniPNW files are the ones notebooks 2.11 and 4.3 use, in the same folder. If they are not on your disk, download them at home (671 MB; thirty laptops downloading at once in class stall the network). From the top of your mlgeo-book folder:
mkdir -p book/Chapter2-DataManipulation/data
cd book/Chapter2-DataManipulation/data
BASE=https://dasway.ess.washington.edu/shared/niyiyu/PNW-ML
curl -fL -C - -O $BASE/miniPNW_metadata.csv
curl -fL -C - -O $BASE/miniPNW_waveforms.hdf5The cell below reads one 30 s window per record, from 5 s before the analyst’s P pick to 25 s after, and a second 30 s window that ends where the first one starts: background noise from the same station, minutes before the event. The first is an event window (label 1), the second a no event window (label 0). It keeps 25 samples per second (low-pass filtered, then one sample in four; the highest frequency kept, 12.5 Hz, is above the 5 Hz of local P waves), and saves the windows in a 30 MB file so the next run takes a second.
DATA = os.path.join("..", "Chapter2-DataManipulation", "data")
META = os.path.join(DATA, "miniPNW_metadata.csv")
WAVES = os.path.join(DATA, "miniPNW_waveforms.hdf5")
CACHE = os.path.join(DATA, "miniPNW_clinic_windows_25hz.npz")
FS = 25.0 # samples per second after decimation
PRE, WIN = 500, 3000 # at 100 Hz: 5 s before the P pick, 30 s window
if not os.path.exists(META) or not os.path.exists(WAVES):
raise FileNotFoundError("miniPNW files not found in " + os.path.abspath(DATA) +
". Download them with the commands in the cell above, then rerun.")
meta = pd.read_csv(META)
meta = meta[meta["trace_P_arrival_sample"].notna()].reset_index(drop=True)
print(len(meta), "records with a P pick")
if os.path.exists(CACHE):
z = np.load(CACHE)
X_all, N_all = z["X"], z["N"]
else:
t0 = time.time()
X_all = np.zeros((len(meta), 3, WIN // 4), dtype=np.float32)
N_all = np.zeros_like(X_all)
with h5py.File(WAVES, "r") as f:
for i, name in enumerate(meta["trace_name"]):
bucket, arr = name.split("$")
row = int(arr.split(",")[0])
p = int(meta.loc[i, "trace_P_arrival_sample"])
rec = f["/data/" + bucket][row].astype(np.float64) # (3, 15001): N, E, Z at 100 Hz
sig = rec[:, p - PRE: p - PRE + WIN]
noi = rec[:, p - PRE - WIN: p - PRE]
X_all[i] = decimate(sig, 4, axis=1, zero_phase=True)
N_all[i] = decimate(noi, 4, axis=1, zero_phase=True)
np.savez_compressed(CACHE, X=X_all, N=N_all)
print(f"read and cached in {time.time() - t0:.0f} s")
# one event window (label 1) and one noise window (label 0) per record
CLASSES = ["no event", "event"]
win = pd.concat([meta.assign(label=1), meta.assign(label=0)], ignore_index=True)
y_all = win["label"].to_numpy()
print("each window:", X_all.shape[1:], "(components N E Z, samples at 25 Hz)")
print(f"{(y_all == 1).sum()} event windows, {(y_all == 0).sum()} noise windows")
print(meta["source_type"].value_counts().to_string())Look before you train: where are the sources and the stations, and what does each class look like?
fig = plt.figure(figsize=(14, 6))
ax = fig.add_subplot(1, 2, 1)
SOURCES = ["earthquake", "explosion", "surface_event", "sonic_boom", "thunder"]
colors = dict(zip(SOURCES, ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00"]))
for c in SOURCES:
m = meta[meta.source_type == c]
ax.scatter(m.source_longitude_deg, m.source_latitude_deg, s=10, color=colors[c], label=f"{c} ({len(m)})")
st = meta.drop_duplicates("station_code")
ax.scatter(st.station_longitude_deg, st.station_latitude_deg, marker="^", s=18, color="k", label=f"stations ({len(st)})")
ax.set_xlabel("longitude (°)"); ax.set_ylabel("latitude (°)"); ax.set_aspect(1 / np.cos(np.radians(46)))
ax.set_title("Sources and stations, Pacific Northwest"); ax.legend(fontsize=9, loc="lower left")
t = np.arange(X_all.shape[2]) / FS
examples = [("earthquake", X_all, "event: earthquake"), ("explosion", X_all, "event: explosion"),
("thunder", X_all, "event: thunder"), ("earthquake", N_all, "no event (before\nan earthquake)"),
("surface_event", N_all, "no event (before a\nsurface event)")]
for k, (c, arr, lab) in enumerate(examples):
a = fig.add_subplot(5, 2, 2 * k + 2)
i = np.where(meta.source_type == c)[0][0]
a.plot(t, arr[i, 2], color=colors[c] if arr is X_all else "0.4", lw=0.6)
a.set_yticks([]); a.set_ylabel(lab, rotation=0, ha="right", fontsize=10)
if k < 4:
a.set_xticks([])
a.set_xlabel("time in the 30 s window (s), vertical component, raw counts")
fig.tight_layout()Scaling. Each window, event or noise, is divided by the standard deviation of its own 30 s (one number for the three components, so their relative size is kept). This uses no other record, so it cannot leak information between the training and test sets, and the network cannot use the absolute amplitude: an event window is louder than the noise before it, and a network given the raw counts would only learn “loud means event” (station 1 measures it).
def scale_each(X):
return (X / (X.std(axis=(1, 2), keepdims=True) + 1e-12)).astype(np.float32)
Xs = scale_each(np.concatenate([X_all, N_all])) # windows 0..N-1: events; N..2N-1: noise
groups_event = win["event_id"].to_numpy() # an event window and its noise window share the group
groups_station = win["station_code"].to_numpy()
print("events:", len(set(groups_event)), "| stations:", len(set(groups_station)),
"| events recorded at more than one station:", int((meta.event_id.value_counts() > 1).sum()))2. Train one network, step by step¶
The same order as notebook 4.1: split the data, design the model, choose the loss and the optimizer, write the training loop, train, and look at the learning curve. Every station reuses these pieces and changes one of them.
2.1 Split the data first¶
Before any model, decide which records the network learns from (train), which ones choose the settings (validation), and which ones measure the result once (test): 70%, 15%, 15%. The event window and the noise window of a record come from the same station minutes apart, and records of one earthquake at several stations look alike: all windows of an event go to the same set.
def split_by_group(groups, seed=SEED, val=0.15, test=0.15):
"""Train, validation and test indices such that no group is in two sets."""
idx = np.arange(len(groups))
rest, te = next(GroupShuffleSplit(1, test_size=test, random_state=seed).split(idx, groups=groups))
tr, va = next(GroupShuffleSplit(1, test_size=val / (1 - test), random_state=seed).split(rest, groups=groups[rest]))
return rest[tr], rest[va], te
idx_tr, idx_va, idx_te = split_by_group(groups_event)
part = np.empty(len(y_all), dtype=object)
part[idx_tr], part[idx_va], part[idx_te] = "train", "validation", "test"
pd.crosstab(win["source_type"].where(y_all == 1, "no event"), part)[["train", "validation", "test"]]2.2 Design the model¶
A small convolutional network (notebook 4.3): three blocks of convolution, ReLU and max pooling slide along the 30 s of the three components; an average over time then gives one number per feature map, and a last linear layer gives one score per class.
build draws the starting weights at random with a seed, so a run can be repeated. make_fcn is the alternative for station 4: a fully connected network (notebook 4.1) on a table of 90 numbers per record, the log of the RMS amplitude of each component in each second.
def make_cnn(width=16, kernel=7, n_classes=2):
w = width
return nn.Sequential(
nn.Conv1d(3, w, kernel, padding=kernel // 2), nn.ReLU(), nn.MaxPool1d(4),
nn.Conv1d(w, 2 * w, kernel, padding=kernel // 2), nn.ReLU(), nn.MaxPool1d(4),
nn.Conv1d(2 * w, 2 * w, kernel, padding=kernel // 2), nn.ReLU(),
nn.AdaptiveAvgPool1d(1), nn.Flatten(), nn.Linear(2 * w, n_classes))
class RMSTable(nn.Module):
"""30 s x 3 components -> log RMS amplitude in each second: 90 numbers."""
def forward(self, x):
b = x.shape[0]
return torch.log(x.reshape(b, 3, 30, -1).pow(2).mean(-1).sqrt() + 1e-3).reshape(b, 90)
def make_fcn(width=64, n_classes=2):
return nn.Sequential(RMSTable(), nn.Linear(90, width), nn.ReLU(), nn.Linear(width, n_classes))
def build(arch="cnn", seed=0, **kw):
torch.manual_seed(seed) # random starting weights, drawn with this seed
return (make_cnn if arch == "cnn" else make_fcn)(**kw)
def n_weights(model):
return sum(p.numel() for p in model.parameters())
model = build("cnn", seed=0)
print(model)
print(f"{n_weights(model):,} weights for {len(idx_tr)} training windows")2.3 Loss and optimizer¶
Two classes, event and no event: cross-entropy, with the softmax inside the loss (two scores per window). The optimizer is Adam with a learning rate of 0.001. Before training, the network has no reason to prefer any class, so the loss of a batch should be close to .
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
xb = torch.from_numpy(Xs[idx_tr[:64]])
yb = torch.from_numpy(y_all[idx_tr[:64]])
print(f"loss of one batch before training: {loss_fn(model(xb), yb).item():.3f} (ln 2 = {np.log(2):.3f})")2.4 The training loop¶
The same loop as train_model in 4.7 section 2.4, where you wrote its four central lines. One epoch: shuffle the training records, cut them into batches, and for each batch zero the gradients, compute the loss (mean over the batch), the gradients, and one update. After each epoch, compute the validation loss and keep the weights of the best epoch (the checkpoint).
train builds its own optimizer with the learning rate you pass, so that each station can change one setting: lr, batch, epochs, loss_fn, augment (a function applied to each batch) or max_updates.
The score is the balanced accuracy, the mean of two numbers: the fraction of event windows called events, and the fraction of noise windows called noise. Here the two classes are equal in number, so it equals the accuracy; in station 6, where events become rare, plain accuracy would reward a network that never says “event”.
def train(model, idx_tr, idx_va, lr=1e-3, batch=64, epochs=8, seed=0,
loss_fn=None, augment=None, max_updates=None, verbose=False):
loss_fn = loss_fn or nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
Xtr, ytr = torch.from_numpy(Xs[idx_tr]), torch.from_numpy(y_all[idx_tr])
Xva, yva = torch.from_numpy(Xs[idx_va]), torch.from_numpy(y_all[idx_va])
g = torch.Generator().manual_seed(seed)
hist = {"train_loss": [], "val_loss": [], "val_score": [], "batch_loss": [], "updates": 0}
best, best_state = np.inf, None
for epoch in range(epochs):
model.train()
order = torch.randperm(len(Xtr), generator=g)
losses = []
for i in range(0, len(order), batch):
j = order[i:i + batch]
xb = Xtr[j] if augment is None else augment(Xtr[j].clone())
optimizer.zero_grad() # the four lines of one_epoch (4.7 section 2.4)
loss = loss_fn(model(xb), ytr[j]) # mean loss over the batch
loss.backward() # gradients
optimizer.step() # one update
losses.append(loss.item())
hist["updates"] += 1
if max_updates and hist["updates"] >= max_updates:
break
model.eval()
with torch.no_grad():
val_loss = nn.CrossEntropyLoss()(model(Xva), yva).item()
hist["batch_loss"] += losses
hist["train_loss"].append(np.mean(losses))
hist["val_loss"].append(val_loss)
hist["val_score"].append(score(model, Xs[idx_va], y_all[idx_va]))
if verbose:
print(f"epoch {epoch + 1:2d} train loss {hist['train_loss'][-1]:.3f} "
f"val loss {val_loss:.3f} val balanced accuracy {hist['val_score'][-1]:.3f}")
if val_loss < best: # checkpoint: keep the best epoch
best, best_state = val_loss, {k: v.clone() for k, v in model.state_dict().items()}
if max_updates and hist["updates"] >= max_updates:
break
if best_state is not None: # None if the loss was never finite
model.load_state_dict(best_state)
return hist
def predict(model, X):
model.eval()
with torch.no_grad():
return model(torch.from_numpy(X)).argmax(1).numpy()
def score(model, X, y):
return balanced_accuracy_score(y, predict(model, X))2.5 Train, and plot the learning curve¶
Training and validation loss at every epoch. While both fall, the network is still learning; when the validation loss turns up while the training loss keeps falling, it has started to fit the training records rather than the classes. The test set is used once, at the end.
def plot_curves(histories, title="", ax=None):
ax = ax or plt.subplots(figsize=(7, 4))[1]
for (label, h), c in zip(histories.items(), plt.cm.tab10.colors):
epochs = np.arange(1, len(h["train_loss"]) + 1)
ax.plot(epochs, h["train_loss"], color=c, lw=2, label=f"{label} train")
ax.plot(epochs, h["val_loss"], color=c, lw=2, ls="--", label=f"{label} validation")
ax.set_xlabel("epoch"); ax.set_ylabel("cross-entropy loss"); ax.set_title(title, loc="left")
ax.legend(fontsize=9)
return ax
t0 = time.time()
cnn = build("cnn", seed=0)
h0 = train(cnn, idx_tr, idx_va, verbose=True)
print(f"trained in {time.time() - t0:.0f} s; test balanced accuracy {score(cnn, Xs[idx_te], y_all[idx_te]):.3f}")
plot_curves({"CNN": h0}, "Learning curve of the reference CNN");2.6 Compare with baselines¶
A score means something only next to a model without learning and a classical model on the same split.
# The baseline without learning, and a classical model on the same split
majority = balanced_accuracy_score(y_all[idx_te], np.zeros(len(idx_te), dtype=int))
rms = RMSTable()(torch.from_numpy(Xs)).numpy()
logit = LogisticRegression(max_iter=2000).fit(rms[idx_tr], y_all[idx_tr])
print(f"always 'no event' (no learning): {majority:.3f}")
print(f"logistic regression on the 90 RMS values: {balanced_accuracy_score(y_all[idx_te], logit.predict(rms[idx_te])):.3f}")
print(f"CNN reference run: {score(cnn, Xs[idx_te], y_all[idx_te]):.3f}")3. Station 1: train, validation and test sets, and leakage¶
Three ways information about the test set can reach the model, each measured.
(a) The split. The network is meant to classify sources it has never seen, at stations that may be new. Records of one event at two stations look alike; records of one quarry at one station look alike over years. Compare three splits: records drawn at random, records grouped by event, records grouped by station.
Prediction (write it before running): which split gives the highest test score, and by how much?
my_prediction_1a = "" # e.g. "random split highest, about 0.05 above grouped by station"Your turn (1): a split grouped by station¶
Write idx_tr_st, idx_va_st, idx_te_st so that no station appears in two partitions. One line: the function split_by_group of section 2 takes the group label of each record.
idx_tr_st, idx_va_st, idx_te_st = None, None, None # your line hereNotebook Cell
ref = split_by_group(groups_station)
ok = idx_tr_st is not None and set(groups_station[idx_tr_st]).isdisjoint(groups_station[idx_te_st]) \
and set(groups_station[idx_tr_st]).isdisjoint(groups_station[idx_va_st])
if not ok:
print("idx_*_st: missing, or a station appears in two partitions. Hint: split_by_group(groups_station)."
"\n Using the reference split below.")
idx_tr_st, idx_va_st, idx_te_st = ref
else:
print("station split: no station in two partitions")
perm = rng.permutation(len(y_all))
n_te, n_va = int(0.15 * len(perm)), int(0.15 * len(perm))
random_split = perm[n_te + n_va:], perm[n_te:n_te + n_va], perm[:n_te]
splits = {"random records": random_split, "grouped by event": (idx_tr, idx_va, idx_te),
"grouped by station": (idx_tr_st, idx_va_st, idx_te_st)}
res1 = {}
for name, (a, b, c) in splits.items():
s = []
for seed in range(2):
m = build("cnn", seed=seed)
train(m, a, b, seed=seed)
s.append(score(m, Xs[c], y_all[c]))
res1[name] = s
print(f"{name:20s} test balanced accuracy {np.mean(s):.3f} ± {np.std(s):.3f} (2 seeds)")(b) A shortcut in the amplitude. Before scaling, an event window is louder than the noise window recorded minutes earlier at the same station. Train a logistic regression on one number per window, the logarithm of its standard deviation in raw counts, and nothing else.
raw = np.log(np.concatenate([X_all, N_all]).std(axis=(1, 2)))[:, None]
lr_amp = LogisticRegression(max_iter=2000).fit(raw[idx_tr], y_all[idx_tr])
print(f"balanced accuracy from the raw amplitude alone: {balanced_accuracy_score(y_all[idx_te], lr_amp.predict(raw[idx_te])):.3f}")Compare this number with chance (0.5) and with the CNN of section 2. If the raw amplitude alone scored high, the labels could be predicted from loudness, and a network given raw counts would learn “loud means event”. On a continuous record that rule fails, because the noise level changes by a factor of ten between day and night, with the season, and from station to station. This is why every window is scaled by its own standard deviation (section 1). Why is the raw amplitude a weak predictor here? Look at a few noise windows of surface events and sonic booms: whose “P pick” sits at sample 7000 for every record? Question: name one other property of how these windows were cut that a network could use instead of the waveform.
(c) Choosing on the test set. Train six versions (two learning rates, three widths). A careless report picks the one with the best test score. A careful one picks on the validation score, then reports the test score of that one.
configs = [(lr, w) for lr in (1e-3, 3e-3) for w in (8, 16, 32)]
val_s, test_s = [], []
for lr, w in configs:
m = build("cnn", seed=0, width=w)
train(m, idx_tr, idx_va, lr=lr)
val_s.append(score(m, Xs[idx_va], y_all[idx_va]))
test_s.append(score(m, Xs[idx_te], y_all[idx_te]))
print(f"lr {lr:g}, width {w:2d}: validation {val_s[-1]:.3f} test {test_s[-1]:.3f}")Your turn (2): two reports¶
Write reported_if_chosen_on_test (the best test score of the six) and reported_if_chosen_on_val (the test score of the version with the best validation score). One line each, with np.max, np.argmax and the lists test_s and val_s.
reported_if_chosen_on_test = None
reported_if_chosen_on_val = NoneNotebook Cell
if reported_if_chosen_on_test is None: # your cell is empty: use the reference
reported_if_chosen_on_test = float(np.max(test_s))
if reported_if_chosen_on_val is None: # your cell is empty: use the reference
reported_if_chosen_on_val = float(test_s[int(np.argmax(val_s))])
print(f"\nchosen on test: {reported_if_chosen_on_test:.3f} chosen on validation: {reported_if_chosen_on_val:.3f} "
f"difference: {reported_if_chosen_on_test - reported_if_chosen_on_val:+.3f}")Write your rule (section 9) from the numbers of (a), (b) and (c). Compare the differences with the spread over seeds in (a): which differences are larger than the spread?
4. Station 2: starting weights¶
Notebook 4.0 started from random weights drawn with a seed and said “never zeros”. Test it, and test weights that start too large.
Prediction: with every weight and bias at zero, what is the validation score after 12 epochs? With the default random weights multiplied by 10?
my_prediction_2 = ""Your turn (3): two ways to start¶
Write init_zeros(model), which sets every weight and bias of the model to zero, and init_scaled(model, factor), which multiplies every weight and bias by factor. Both change the model in place inside with torch.no_grad():, looping over model.parameters(). Hint: a tensor p has the methods p.zero_() and p.mul_(factor).
init_zeros = None
init_scaled = NoneNotebook Cell
def _init_zeros(model):
with torch.no_grad():
for p in model.parameters():
p.zero_()
def _init_scaled(model, factor):
with torch.no_grad():
for p in model.parameters():
p.mul_(factor)
if init_zeros is None: # your cell is empty: use the reference
init_zeros = _init_zeros
if init_scaled is None: # your cell is empty: use the reference
init_scaled = _init_scaled
res2, hist2 = {}, {}
for label, prep in [("seeded random (default)", lambda m: None), ("all zeros", init_zeros),
("random x 10", lambda m: init_scaled(m, 10.0)), ("random x 0.1", lambda m: init_scaled(m, 0.1))]:
s = []
for seed in range(2):
m = build("cnn", seed=seed); prep(m)
h = train(m, idx_tr, idx_va, seed=seed)
s.append(h["val_score"][-1])
if seed == 0:
hist2[label] = h
res2[label] = s
print(f"{label:24s} validation balanced accuracy {np.mean(s):.3f} ± {np.std(s):.3f} (2 seeds)")
plot_curves(hist2, "Starting weights, seed 0")Questions. With zero starting weights, how many different output scores does the network give over the validation records? (Try np.unique(predict(m, Xs[idx_va])) on a zero-started model.) Why does a hidden unit that starts equal to its neighbor stay equal to it? Is a balanced accuracy of 0.5 better than chance for two classes?
Write your rule (section 9).
5. Station 3: learning rate and batch size¶
The learning rate sets the size of each update; the batch size sets how many records are averaged in the loss before each update. They act together: a smaller batch means more updates per epoch, each noisier.
Prediction: of learning rates 0.0001, 0.001 and 0.01 with Adam, which trains best in 8 epochs? Does the answer change with a batch of 16 instead of 256?
my_prediction_3 = ""Your turn (4): the grid¶
Write the double loop: for each learning rate in lrs and each batch size in batches, build a CNN with build("cnn", seed=0), train it with train(m, idx_tr, idx_va, lr=lr, batch=b, epochs=8), and store the returned history in grid[(lr, b)]. Four lines.
lrs = [1e-4, 1e-3, 1e-2]
batches = [16, 256]
grid = {}
# your loop hereNotebook Cell
if len(grid) != len(lrs) * len(batches):
print("grid: incomplete. Hint: for lr in lrs: for b in batches: m = build(...); grid[(lr, b)] = train(...)."
"\n Running the reference loop.")
grid = {}
for lr in lrs:
for b in batches:
m = build("cnn", seed=0)
grid[(lr, b)] = train(m, idx_tr, idx_va, lr=lr, batch=b, epochs=8)
fig, axes = plt.subplots(1, 2, figsize=(14, 4), sharey=True)
for ax, b in zip(axes, batches):
plot_curves({f"lr {lr:g}": grid[(lr, b)] for lr in lrs}, f"batch {b}: {grid[(lrs[0], b)]['updates']} updates in 8 epochs", ax)
fig.tight_layout()
print("validation balanced accuracy after 8 epochs (best epoch kept):")
print(pd.DataFrame({f"batch {b}": [max(grid[(lr, b)]["val_score"]) for lr in lrs] for b in batches},
index=[f"lr {lr:g}" for lr in lrs]).round(3))A fair comparison. Batch 16 made far more updates than batch 256 in the same 8 epochs. Train both for the same number of updates (max_updates=200) and look again: which batch size wins now? The noise of the loss from batch to batch is in h["batch_loss"]; plot it for both.
fig, ax = plt.subplots(figsize=(9, 3.5))
for b in batches:
m = build("cnn", seed=0)
h = train(m, idx_tr, idx_va, lr=1e-3, batch=b, epochs=200, max_updates=200)
ax.plot(h["batch_loss"], lw=1, label=f"batch {b}: validation {max(h['val_score']):.3f}")
ax.set_xlabel("update"); ax.set_ylabel("loss of the batch"); ax.legend(); ax.set_title("200 updates each", loc="left")Write your rule (section 9).
6. Station 4: model size and amount of data¶
Two ways to improve a network: give it more weights, or give it more records. A learning curve answers which: the score against the number of training records, for each size of network.
Prediction: with 25% of the training records, does the biggest network do better or worse than the smallest?
my_prediction_4 = ""Your turn (5): a smaller training set¶
Write subsample(idx, fraction, seed), which returns a random subset of the record indices idx of size int(fraction * len(idx)), without repeats. Use np.random.default_rng(seed).choice(...) with replace=False.
subsample = NoneNotebook Cell
def _subsample(idx, fraction, seed):
return np.random.default_rng(seed).choice(idx, int(fraction * len(idx)), replace=False)
if subsample is None: # your cell is empty: use the reference
subsample = _subsample
fractions, widths = [0.25, 0.5, 1.0], [4, 16, 32]
res4 = pd.DataFrame(index=[f"{f:.0%} of train" for f in fractions])
for w in widths:
col = []
for fr in fractions:
s = []
for seed in range(1):
m = build("cnn", seed=seed, width=w)
train(m, subsample(idx_tr, fr, seed), idx_va, seed=seed)
s.append(score(m, Xs[idx_va], y_all[idx_va]))
col.append(np.mean(s))
res4[f"width {w} ({n_weights(m):,} weights)"] = col
print("validation balanced accuracy, seed 0")
print(res4.round(3))
ax = res4.set_index(pd.Index([int(f * len(idx_tr)) for f in fractions])).plot(marker="o", figsize=(7, 4))
ax.set_xlabel("training records"); ax.set_ylabel("validation balanced accuracy"); ax.set_title("Learning curves", loc="left")Fully connected against convolutional. The fully connected network sees 90 numbers per record (log RMS amplitude per second and component), not the waveform. Train it and compare its score and its number of weights with the CNN of section 2.
fcn = build("fcn", seed=0, width=64)
hf = train(fcn, idx_tr, idx_va, epochs=30)
print(f"FCN: {n_weights(fcn):,} weights, test balanced accuracy {score(fcn, Xs[idx_te], y_all[idx_te]):.3f}")
print(f"CNN: {n_weights(cnn):,} weights, test balanced accuracy {score(cnn, Xs[idx_te], y_all[idx_te]):.3f}")
plot_curves({"FCN": hf}, "Fully connected network on the 90 RMS values")Questions. Would you collect more records or build a bigger network? What does the FCN know that the CNN has to learn, and what does it throw away?
Write your rule (section 9).
7. Station 5: data augmentation¶
Every training window starts 5 s before the P pick. A network running on continuous data will see arrivals anywhere in its window, and on a noisier day. Augmentation changes each training batch in ways that keep the label: here, a random shift in time, a random sign (ground motion and its opposite come from the same kind of source), and real background noise from the noise windows of the training set, added to each window at a random level.
First, the test that matters: the same test records with the arrival moved by up to 10 s.
def shift_records(X, max_shift_s, seed):
g = np.random.default_rng(seed)
out = np.empty_like(X)
for i in range(len(X)):
out[i] = np.roll(X[i], int(g.integers(-max_shift_s * FS, max_shift_s * FS + 1)), axis=-1)
return out
X_te_shift = shift_records(Xs[idx_te], 10, seed=1)
print(f"reference CNN, test balanced accuracy: as cut {score(cnn, Xs[idx_te], y_all[idx_te]):.3f}, "
f"arrival moved up to ±10 s {score(cnn, X_te_shift, y_all[idx_te]):.3f}")Prediction: will training with random shifts close the gap? Will it cost anything on the windows as cut?
my_prediction_5 = ""Your turn (6): an augmentation¶
Write augment(xb). It receives a batch, a tensor of shape (windows, 3, 750), and returns a batch of the same shape where each record is (1) moved in time by a random number of samples between −250 and 250 (±10 s) with torch.roll(x, shifts=k, dims=-1), and (2) multiplied by +1 or −1 at random. Use torch.randint for both.
augment = NoneNotebook Cell
def _augment(xb):
out = torch.empty_like(xb)
k = torch.randint(-250, 251, (len(xb),))
sign = torch.randint(0, 2, (len(xb),)) * 2 - 1
for i in range(len(xb)):
out[i] = sign[i] * torch.roll(xb[i], int(k[i]), dims=-1)
return out
if augment is None: # your cell is empty: use the reference
augment = _augment
noise_bank = torch.from_numpy(Xs[idx_tr[y_all[idx_tr] == 0]]) # noise windows of the TRAINING set only
def augment_noise(xb, level=1.0):
xb = augment(xb)
j = torch.randint(0, len(noise_bank), (len(xb),))
return xb + level * torch.rand(len(xb), 1, 1) * noise_bank[j]
res5 = {}
for label, aug in [("no augmentation", None), ("shift and sign", augment), ("shift, sign and real noise", augment_noise)]:
a, b = [], []
for seed in range(2):
m = build("cnn", seed=seed)
train(m, idx_tr, idx_va, augment=aug, seed=seed, epochs=10)
a.append(score(m, Xs[idx_te], y_all[idx_te])); b.append(score(m, X_te_shift, y_all[idx_te]))
res5[label] = (np.mean(a), np.mean(b))
print(pd.DataFrame(res5, index=["test as cut", "test, arrival moved ±10 s"]).T.round(3), "\n(mean of 2 seeds)")Questions. The noise bank uses the pre-event windows of the training records only. What would go wrong if it also used the test records’ noise? Which augmentation would be wrong for this task (it changes the label, or makes records no instrument would record)?
Write your rule (section 9).
8. Station 6: the loss¶
On a continuous record, windows with an event are rare. Make them rare here: train on every noise window but only one event window in ten. Cross-entropy then treats each window alike, and the many noise windows dominate the loss. Four losses, two numbers on the test set (still half events, half noise): the fraction of events found (recall), and the fraction of noise windows called events (false alarms).
cross-entropy, as in every station so far;
weighted cross-entropy: the loss of each window multiplied by a weight for its class, the inverse of the class’s share of the training set;
focal loss (Lin et al., 2017): the loss of each window multiplied by , where is the probability the network gives to the right class, so windows already classified with confidence count less;
label smoothing: the target is 0.95 for the right class and 0.05 for the other, for labels that are sometimes wrong (a small event hidden in a “noise” window).
Prediction: which loss finds the most events? Which raises the fewest false alarms? Which source types are missed most?
my_prediction_6 = ""Your turn (7): the focal loss¶
Write focal_loss(logits, target, gamma=2.0). Steps: logp = F.log_softmax(logits, dim=1); the log-probability of the right class logp_true = logp.gather(1, target[:, None])[:, 0]; p_true = logp_true.exp(); the loss of each record is -(1 - p_true) ** gamma * logp_true; return its mean over the batch.
focal_loss = NoneNotebook Cell
def _focal(logits, target, gamma=2.0):
logp = F.log_softmax(logits, dim=1)
logp_true = logp.gather(1, target[:, None])[:, 0]
return (-(1 - logp_true.exp()) ** gamma * logp_true).mean()
if focal_loss is None: # your cell is empty: use the reference
focal_loss = _focal
# training set with rare events: all noise windows, one event window in ten
ev_tr, no_tr = idx_tr[y_all[idx_tr] == 1], idx_tr[y_all[idx_tr] == 0]
idx_tr_rare = np.concatenate([no_tr, np.random.default_rng(SEED).choice(ev_tr, len(ev_tr) // 10, replace=False)])
counts = np.bincount(y_all[idx_tr_rare], minlength=2)
print(f"training windows: {counts[0]} noise, {counts[1]} events")
w_class = torch.tensor(len(idx_tr_rare) / (2 * counts), dtype=torch.float32)
print("class weights:", dict(zip(CLASSES, w_class.numpy().round(2))))
losses = {"cross-entropy": nn.CrossEntropyLoss(), "weighted cross-entropy": nn.CrossEntropyLoss(weight=w_class),
"focal, gamma 2": focal_loss, "label smoothing 0.1": nn.CrossEntropyLoss(label_smoothing=0.1)}
ev_te = idx_te[y_all[idx_te] == 1]
rows = {}
for label, lf in losses.items():
r = []
for seed in range(2):
m = build("cnn", seed=seed)
train(m, idx_tr_rare, idx_va, loss_fn=lf, seed=seed, epochs=10)
pred = predict(m, Xs[idx_te])
row = {"recall of events": pred[y_all[idx_te] == 1].mean(), "false alarms": pred[y_all[idx_te] == 0].mean()}
found = pd.Series(predict(m, Xs[ev_te]), index=win.loc[ev_te, "source_type"].to_numpy())
row.update({f"found: {k}": v for k, v in found.groupby(level=0).mean().items()})
r.append(row)
rows[label] = pd.DataFrame(r).mean()
res6 = pd.DataFrame(rows).T
print(res6.round(2), "\n(test set, mean of 2 seeds)")Your own loss. Write a loss that encodes a cost you care about, and train with it (copy the cell above, keep one row). Two ideas: a missed explosion costs a monitoring agency more than an explosion called an earthquake, so penalize that one error more (a cost matrix applied to the predicted probabilities); or combine cross-entropy with the focal term. State the cost in physical or operational terms before you write the code.
Write your rule (section 9).
9. Your rules¶
Write one rule per station you ran, in this format. A rule says what to do, how to check it, and the number from your run that justifies it. Then compare them with the course rubric (4.7, continued): which item does each rule match, and which rule has no item yet?
| Station | Rule (what to do) | Check (how someone else verifies it) | Evidence (your number, with seeds) |
|---|---|---|---|
Example of the format, from notebook 4.1: “Scale the inputs with statistics of the training records only. Check: the line that fits the scaler. Evidence: the scaler is fit on X_train before the validation and test sets are transformed.”
10. Reflection¶
Answer in two or three sentences each.
What you learned. Which result of today surprised you most, and what did you expect instead?
What you learned from the agents. If you ran the agent exercise of lecture 22, a coding agent built a detector from one prompt. Which of these six decisions did it make well, which did it skip, and how would you have known without running the stations yourself?
How to improve it. Which station would you change, or which decision is missing from the six, to make this clinic more useful for your project?
- Ni, Y., Hutko, A., Skene, F., Denolle, M., Malone, S., Bodin, P., Hartog, R., & Wright, A. (2023). Curated Pacific Northwest AI-ready Seismic Dataset. Seismica, 2(1). 10.26443/seismica.v2i1.368