Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

4.7 (clinic) Training clinic on real seismograms: one classifier, six decisions

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:

StationDecisionQuestion you answer with a number
1Train, validation and test sets; leakageHow much does the test score change with the way you split?
2Starting weightsWhat happens if every weight starts at zero?
3Learning rate and batch sizeWhich pairs train, and which do not?
4Model size and amount of dataWould more data or a bigger network help more?
5Data augmentationDoes the network still work when the arrival is not where it was in training?
6The lossWhen 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:

  1. Predict the result before you run anything, and write the prediction in the cell provided.

  2. 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.

  3. Run and compare with your prediction.

  4. 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

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.hdf5

The 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.

Look before you train: where are the sources and the stations, and what does each class look like?

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).

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.

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.

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 ln⁡2=0.69\ln 2 = 0.69.

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”.

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.

2.6 Compare with baselines

A score means something only next to a model without learning and a classical model on the same split.

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?

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.

Notebook Cell

(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.

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.

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.

Notebook Cell

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?

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).

Notebook Cell

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?

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.

Notebook Cell

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.

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?

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.

Notebook Cell

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.

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.

Prediction: will training with random shifts close the gap? Will it cost anything on the windows as cut?

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.

Notebook Cell

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 (1−p)γ(1 - p)^\gamma, where pp 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?

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.

Notebook Cell

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?

StationRule (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.

  1. What you learned. Which result of today surprised you most, and what did you expect instead?

  2. 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?

  3. 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?

References
  1. 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