In Chapter 4 every method was taught on synthetic data, where the truth is known and nothing else gets in the way. This homework takes the same pipeline to real records.
The data. miniPNW is a labeled subset of the Pacific Northwest AI-ready seismic 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 of the Pacific Northwest Seismic Network (PNSN), labeled by its 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 detector: 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). Detection is the first step of every earthquake catalog.
What you do.
| Part | Points | What |
|---|---|---|
| 1 | 10 | Look at the data |
| 2 | 15 | Split without leakage, and two baselines |
| 3 | 20 | Write the training loop and train a convolutional network (CNN) |
| 4 | 20 | Three training decisions of notebook 4.7, tested on real data |
| 5 | 7 | The test set, used once |
| 6 | 3 | Reflection and AI-use disclosure |
One network trains in about 20 s on a laptop CPU. Part 4 trains about fifteen of them: start it early.
0. Setup¶
import os
import time
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
from sklearn.model_selection import GroupShuffleSplit
torch.set_num_threads(max(1, min(4, os.cpu_count() or 1)))
SEED = 469
plt.rcParams.update({"font.size": 12})Download the data at home (671 MB). 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 cuts two 30 s windows from each record. The event window (label 1) starts 5 s before the analyst’s P pick. The no event window (label 0) is the 30 s just before it, at the same station. Both are low-pass filtered and kept at 25 samples per second. The windows are saved 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
meta = pd.read_csv(META)
meta = meta[meta["trace_P_arrival_sample"].notna()].reset_index(drop=True)
if os.path.exists(CACHE):
z = np.load(CACHE)
X_all, N_all = z["X"], z["N"]
else:
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
X_all[i] = decimate(rec[:, p - PRE: p - PRE + WIN], 4, axis=1, zero_phase=True)
N_all[i] = decimate(rec[:, p - PRE - WIN: p - PRE], 4, axis=1, zero_phase=True)
np.savez_compressed(CACHE, X=X_all, N=N_all)
# windows 0..n-1 are events (label 1), windows n..2n-1 their noise windows (label 0)
win = pd.concat([meta.assign(label=1), meta.assign(label=0)], ignore_index=True)
y_all = win["label"].to_numpy()
t = np.arange(X_all.shape[2]) / FS
print(len(meta), "records; each window has shape", X_all.shape[1:], "(components N E Z, samples at 25 Hz)")Scaling. Each window is divided by the standard deviation of its own 30 s. This uses no other window, so it cannot leak anything between the training and test sets. It also hides the absolute loudness from the network (part 2.4 says why that matters).
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]))1. Look at the data (10 points)¶
1.1 Counts (3 points)¶
Task: print the number of records of each source type, the number of distinct stations (station_code) and events (event_id), and the number of events recorded at more than one station. Use meta, with value_counts() and nunique().
# TODO: counts of source types, stations, events, and events recorded at more than one stationThe map of sources and stations, for context.
SOURCES = ["earthquake", "explosion", "surface_event", "sonic_boom", "thunder"]
colors = dict(zip(SOURCES, ["#0072B2", "#D55E00", "#009E73", "#CC79A7", "#E69F00"]))
fig, ax = plt.subplots(figsize=(7, 6))
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="stations")
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", loc="left"); ax.legend(fontsize=9, loc="lower left");1.2 One record, both windows (4 points)¶
Task: pick one earthquake record. Plot its event window (X_all[i]) and its noise window (N_all[i]), the three components on three rows, time in seconds on the x-axis (t). Mark the P pick, 5 s into the event window, with a vertical line.
# TODO: three components of the event window and of the noise window of one earthquake record1.3 Real against synthetic (3 points)¶
Task: name three ways these records differ from the synthetic seismograms of notebooks 4.3 and 4.7, and say for each one how it could make the detector harder (or easier) to train.
2. Split without leakage, and two baselines (15 points)¶
2.1 A split grouped by event (5 points)¶
The event window and the noise window of one record come from the same station minutes apart, and one earthquake is often recorded at several stations. All windows of one event must go to the same set.
Task: write split_by_group(groups, seed=SEED, val=0.15, test=0.15). It returns the indices of the training, validation and test windows such that no group appears in two of them. Use GroupShuffleSplit twice: once to set aside the test windows, once to split the rest into training and validation. Then split with groups_event and print how many windows each set has.
groups_event = win["event_id"].to_numpy()
# TODO: split_by_group, then idx_tr, idx_va, idx_te = split_by_group(groups_event)2.2 Why group (3 points)¶
Task: answer in three sentences. (1) What would a split of windows drawn at random let the network see during training that it should not? (2) A split grouped by station is stricter. What question would it answer that the split by event does not? (3) Which of the two splits fits a detector meant to run on a new station?
2.3 Two baselines (5 points)¶
A score means something only next to a model without learning and a classical model on the same split.
Task: on the validation windows, compute the balanced accuracy of (1) a model that always answers “no event”, and (2) a LogisticRegression(max_iter=2000) trained on rms_table(Xs), the log RMS amplitude of each component in each second (90 numbers per window). The balanced accuracy is the mean of the fraction of events found and the fraction of noise windows called noise (balanced_accuracy_score).
def rms_table(X):
"""30 s x 3 components -> log RMS amplitude in each second: 90 numbers per window."""
n = X.shape[0]
return np.log(np.sqrt((X.reshape(n, 3, 30, -1) ** 2).mean(-1)) + 1e-3).reshape(n, 90)
# TODO: balanced accuracy on validation of "always no event" and of logistic regression on rms_table(Xs)2.4 The loudness shortcut (2 points)¶
Task: train a logistic regression on one number per window, the log of its standard deviation in raw counts (np.concatenate([X_all, N_all]), before scaling), and report its validation balanced accuracy. In one sentence: why would a detector that learned “loud means event” fail on a continuous record?
# TODO: logistic regression on log(std) of the raw windows3. Train a convolutional network (20 points)¶
The network is given: three blocks of convolution, ReLU and max pooling, then an average over time and one linear layer that gives two scores, one per class (notebook 4.3). build draws the starting weights at random with a seed. make_fcn is a fully connected network on the 90 RMS numbers, for part 4.
def make_cnn(width=16, kernel=7):
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, 2))
class RMSTable(nn.Module):
def forward(self, x):
n = x.shape[0]
return torch.log(x.reshape(n, 3, 30, -1).pow(2).mean(-1).sqrt() + 1e-3).reshape(n, 90)
def make_fcn(width=64):
return nn.Sequential(RMSTable(), nn.Linear(90, width), nn.ReLU(), nn.Linear(width, 2))
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 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))
model = build("cnn", seed=0)
print(model)
print(sum(p.numel() for p in model.parameters()), "weights")3.1 The loss before training (2 points)¶
Task: compute the cross-entropy loss (nn.CrossEntropyLoss()) of the untrained model on the first 64 training windows. A network that gives both classes a probability of 1/2 has a loss of . Is your untrained network close to that? In one sentence, why is it not exactly ?
# TODO: loss of one batch before training, next to ln 23.2 The training loop (10 points)¶
Task: write train(model, idx_tr, idx_va, lr=1e-3, batch=64, epochs=8, seed=0, loss_fn=None, augment=None). It returns a dictionary hist with three lists, one value per epoch: train_loss, val_loss, val_score.
loss_fndefaults tonn.CrossEntropyLoss(); the optimizer istorch.optim.Adamwith learning ratelr.Each epoch: a new random order of the training windows (
torch.randpermwith atorch.Generatorseeded byseed), batches ofbatchwindows, and for each batch the five steps: scores, loss,zero_grad,backward,step.If
augmentis given, apply it to each batch before the scores (part 4).After each epoch: the validation loss with
model.eval()andtorch.no_grad(), the validation balanced accuracy withscore, andmodel.train()again.Keep a copy of the weights of the epoch with the lowest validation loss (
model.state_dict()), and load them back at the end.
# TODO: def train(model, idx_tr, idx_va, lr=1e-3, batch=64, epochs=8, seed=0, loss_fn=None, augment=None):3.3 Train, and plot the learning curve (4 points)¶
Task: train build("cnn", seed=0) for 8 epochs. Plot the training and validation loss against the epoch on one panel, and the validation balanced accuracy on a second panel, with the two baselines of 2.3 as horizontal lines.
# TODO: train the reference CNN, plot its learning curve3.4 Read the curve (4 points)¶
Task: in two or three sentences. Is the network still learning at epoch 8, or has it started to fit the training windows rather than the classes? Which epoch did train keep? Is the CNN better than the logistic regression by more than you would expect from a change of seed (try seed=1 once)?
4. Three training decisions (20 points)¶
Notebook 4.7 tested each decision of a modeler on synthetic data. Pick three of the six below and test them on miniPNW. For each one:
Predict the result before you run anything, in one sentence (1 point).
Measure: one controlled experiment that changes only that decision, at least two seeds per setting, scored on the validation set. Show a table or a figure (3 points).
Write a rule in the format of the class rubric (4.7): what to do, how someone else checks it, and your number as evidence (2 points).
| Decision | One experiment | |
|---|---|---|
| A | Starting weights | default random weights, all zeros, random × 10 |
| B | Learning rate and batch size | learning rates 1e-4, 1e-3, 1e-2 with batches of 16 and 256 |
| C | Model size and amount of data | widths 4, 16, 32 with 25%, 50% and 100% of the training windows |
| D | Convolutional or fully connected | build("cnn") against build("fcn") on the RMS table |
| E | Augmentation | random shifts of ±10 s and random sign; score on validation windows shifted with shift_records |
| F | The loss when events are rare | keep one event window in ten in the training set; cross-entropy, weighted cross-entropy, focal loss; report the fraction of events found and of false alarms |
Write each experiment in its own cell below.
def shift_records(X, max_shift_s, seed):
"""Move each window by a random number of samples, up to max_shift_s seconds (for decision E)."""
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 out4.1 First decision (6 points)¶
Prediction:
# TODO: experiment for your first decisionRule (what to do / how to check / evidence):
4.2 Second decision (6 points)¶
Prediction:
# TODO: experiment for your second decisionRule (what to do / how to check / evidence):
4.3 Third decision (6 points)¶
Prediction:
# TODO: experiment for your third decisionRule (what to do / how to check / evidence):
4.4 Signal or seed? (2 points)¶
Task: for each of your three experiments, is the difference you measured larger than the difference between two seeds of the same setting? One sentence each.
5. The test set, used once (7 points)¶
5.1 Final model (3 points)¶
Task: choose your final settings from the validation results of parts 3 and 4, and state them. Train that model, then compute its balanced accuracy on the test windows with a 95% bootstrap confidence interval (bootstrap_ci below). Do the same for the logistic regression of 2.3, on the same test windows.
def bootstrap_ci(y_true, y_pred, n_boot=2000, seed=0):
"""95% bootstrap confidence interval of the balanced accuracy."""
g = np.random.default_rng(seed)
n = len(y_true)
s = [balanced_accuracy_score(y_true[j], y_pred[j]) for j in (g.integers(0, n, n) for _ in range(n_boot))]
return np.percentile(s, [2.5, 97.5])
# TODO: final model, test balanced accuracy and its interval; the same for the logistic regression5.2 Which events are missed (2 points)¶
Task: on the test event windows only, print the fraction found by your final model for each source type (win.loc[idx, "source_type"]), with the number of windows of each type.
# TODO: fraction of test event windows found, per source type5.3 Verdict (2 points)¶
Task: in two or three sentences: does the CNN beat the logistic regression on the test set, given the two intervals? Which source type is missed most often, and what about its signal (frequency, duration, amplitude, the way its window was cut) could explain it?
6. Reflection and AI-use disclosure (3 points)¶
Reflection (two or three sentences each, course policy):
What did you learn from this homework? Which result on real data differed most from what notebook 4.7 showed on synthetic data?
What did you learn from interacting with agents or chatbots?
What would you change in this homework so it meets its learning goals better?
Disclosure (1.8, 6.4): one row per tool, the task it did, and what you verified. If you used no assistant, write one row saying so. The training loop of 3.2 was 🔒 by hand and must not appear as an assistant task.
| Tool | Task | What I verified |
|---|---|---|
- 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