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.3 Convolutional Neural Networks

Convolutional neural networks (CNNs) are the workhorse of deep learning on data laid out on a grid: images, maps, spectrograms and time series. This notebook covers:

  1. Convolutions and kernels, on a simple synthetic seismogram (1-D) and a simple synthetic temperature map (2-D).

  2. The building blocks of a CNN: convolution, activation, pooling; how the shape of a network (wide and shallow, or long and skinny) sets what it can see; and the last block that turns feature maps into class probabilities.

  3. A 2-D CNN regressing warming trends from a gridded synthetic climate field, against a least-squares baseline.

  4. A 1-D CNN earthquake detector trained on synthetic seismograms, its detection floor as a function of signal-to-noise ratio, and the classical STA/LTA detector measured on the same traces.

  5. How to translate a published architecture table into working code.

The same kind of detector on real seismograms (miniPNW) is the homework, Homework_DL.

πŸ–₯️ Lecture slides β€” Session 22 (Fri Nov 20)

Using device: cpu

0. To reviewΒΆ

At this point, you should understand:

  • The perceptron

  • The role of activation functions

  • Why and how to implement a simple gradient descent

  • Loss functions

  • Batching

  • Multilayer perceptrons

1. ConvolutionsΒΆ

Just like perceptrons and multilayer perceptrons, each element in a CNN receives inputs, performs a dot product, and passes that product through an activation function. The difference is that a CNN applies the same small set of weights, called a kernel, everywhere in the input. These networks work well on structured 1-D, 2-D, and 3-D data such as time series and images.

As their name implies, CNNs rely on convolutions:

(fβˆ—g)(x)=βˆ«Ο„=βˆ’βˆž+∞f(Ο„)g(xβˆ’Ο„)dΟ„(f*g)(x)= \int\limits^{+\infty}_{\tau=-\infty}f(\tau)g(x-\tau)d\tau

where gg is the input, ff is the kernel of convolution, and Ο„\tau is a dummy variable.

A kernel of three weights on ten numbers: each output is a weighted sum of three neighbors (lecture 22)

For discrete functions, you simply sum:

(fβˆ—g)(x)=βˆ‘Ο„=βˆ’βˆž+∞f(Ο„)g(xβˆ’Ο„)(f*g)(x)= \sum\limits^{+\infty}_{\tau=-\infty} f(\tau)g(x-\tau)

Deep-learning libraries compute the same sliding sum without flipping the kernel (a cross-correlation, βˆ‘Ο„f(Ο„) g(x+Ο„)\sum_\tau f(\tau)\,g(x+\tau)), and still call it a convolution. Since the kernel weights are learned, the flip makes no difference to what a network can do. We follow the library convention below.

1.1 One dimension: multiply, add, slideΒΆ

A synthetic seismogram, 20 s at 100 samples per second: a slow drift, white noise, and two 5 Hz arrivals at 5 s and 13 s, the second one half as strong.

<Figure size 1300x300 with 2 Axes>

At one position, the convolution multiplies each weight by the sample under it and adds the products. That sum is one output value. Sliding the kernel by one sample and repeating gives the next value. The output is large where the record looks like the kernel.

Multiply, add, slide: a kernel moving along a synthetic record (lecture 22)

The same computation, by hand, at two positions: on the first arrival, and in the noise.

position  4.6 s (kernel centred on the first arrival): sum of the 80 products = +14.62
position  9.0 s (in the noise): sum of the 80 products = +0.87
output length: 1921 = record length 2000 - kernel length 80 + 1

PyTorch’s nn.Conv1d does exactly this. Give it our kernel as its weights and compare.

same as the loop: True

Your turn (1): the cartoon by handΒΆ

The figure at the top of this section slides the kernel [1, 2, 1] along ten numbers. Write out, the list of the 8 outputs: for each start position k from 0 to 7, the sum of kernel3 * x10[k:k + 3]. One line, a list comprehension. You should find the numbers of the figure.

None

Answer below (click to open it).

Notebook Cell
[4, 6, 4, 1, -1, -4, -6, -4]

Different kernels pull different things out of the same record. Three of them, each a filter you met in Chapter 2:

  • a 1 s average (100 equal weights): a low-pass filter, keeps the slow drift;

  • a difference of two samples 0.05 s apart: a high-pass filter, removes the drift and marks rapid changes;

  • the wave packet above: a band-pass filter at 5 Hz, a template of the arrival.

<Figure size 1200x700 with 4 Axes>

1.2 Two dimensions: a temperature mapΒΆ

Convolution extends to multiple dimensions: the kernel becomes a small square that slides along both directions.

A 3 x 3 kernel on a 6 x 6 map: cold rows above, warm rows below (lecture 22)

A synthetic temperature map, 60 by 80 cells: cold to the north and warm to the south, separated by a sharp, wavy front; a small warm anomaly (a lake or a city) in the cold part; and noise.

For example, consider the mean filter (here, for a 3 x 3 kernel):

[191919191919191919]\begin{bmatrix} \frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ \frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ \frac{1}{9} & \frac{1}{9} & \frac{1}{9} \\ \end{bmatrix}
<Figure size 1100x360 with 3 Axes>

The mean filter blurs. Other kernels detect structure. The Sobel filters approximate the gradient of the map and respond to edges: here, the front and the rim of the anomaly.

<Figure size 1500x320 with 4 Axes>

The same 3 x 3 computation on a real map, the air temperature of 7 January 2014 over North America (NCEP/NCAR Reanalysis 1, lecture 22): nine temperatures, nine weights, one sum per position.

A 3 x 3 kernel sliding over a reanalysis temperature map (lecture 22)

The point of a CNN is that it does not use hand-designed kernels like these. It learns the kernel weights from data by gradient descent. Early layers often end up learning edge detectors on their own.

Exercise 1. Change filterDimension from 3 to 15 in the mean-filter cell. What happens to the front and to the warm anomaly, and why?

2. Assembling a CNNΒΆ

The architecture of a CNN classically comprises:

  1. A convolutional layer

  2. An activation layer

  3. A pooling layer

  4. A fully connected layer

2.1 The convolutional layerΒΆ

Here we consider a CNN that takes in images and returns some output.

Aspects of this layer:

Inputs: In the case of 2D convolutions, three dimensions: height, width, depth.

Filters: The convolutional kernels, each with a bias and a weight for each element of the kernel. The output of a filter is a feature map. Generally, the number of filters is greater than the input depth. The kernel size is often square, but does not need to be.

Stride: The step size by which the filter moves.

Padding: Values added to the edges of the input.

Channels and kernels: three components in, one filter holds one kernel per input channel (lecture 22)

A filter has one kernel per input channel. Its output is the sum of the three convolutions plus a bias: one feature map. A layer with 16 filters gives 16 feature maps, the channels of the next layer.

A good lecture about CNNs is Stanford’s CS230 cheatsheet.

How would you interpret the following code?

Conv2d(3, 64, kernel_size=(6, 6), stride=(1, 1))

This layer takes an input with 3 channels (for example an RGB image), applies 64 filters of size 6 x 6 (each spanning all 3 input channels), and outputs 64 feature maps.

In one dimension, the length of each feature map depends on the kernel size kk, the stride ss and the padding pp: Lout=⌊(Lin+2pβˆ’k)/sβŒ‹+1L_{out} = \lfloor (L_{in} + 2p - k)/s \rfloor + 1. Four filters on our 20 s record:

kernel 7, stride 1, padding 0: (1, 1, 2000) -> (1, 4, 1994)   (32 weights)
kernel 7, stride 1, padding 3: (1, 1, 2000) -> (1, 4, 2000)   (32 weights)
kernel 7, stride 2, padding 3: (1, 1, 2000) -> (1, 4, 1000)   (32 weights)

Padding of (kβˆ’1)/2(k-1)/2 keeps the length; a stride of 2 halves it. Each of the 4 filters has 7 weights and a bias: 32 weights, whatever the length of the record.

2.2 The activation layerΒΆ

The convolutional layer is followed by an activation layer. This layer applies an activation function to each value of each feature map. Without it, a stack of convolutions would still be one linear filter. The common choices:

<Figure size 1600x300 with 5 Axes>
  • ReLU (rectified linear unit) keeps positive values and sets negative ones to zero. It is the default in CNNs: cheap, and its slope is 1 for every positive input, so gradients do not shrink as they pass back through many layers.

  • Leaky ReLU and GELU let a little of the negative side through, so a unit whose input is negative still gets a gradient.

  • Sigmoid and tanh flatten out for large inputs (they saturate): their slope tends to zero, and so do the gradients of the layers below. LeNet-5 (LeCun et al., 1998) used sigmoid, as networks did then.

What ReLU does to a feature map: the output of the wave-packet kernel, before and after.

<Figure size 1200x400 with 2 Axes>

2.3 The pooling layerΒΆ

The pooling layer downsamples the feature maps. By combining values, pooling reduces the size of the model and makes it less sensitive to small shifts of the input.

Max pooling layers take the maximum value within a given neighborhood (set by the pooling size). Average pooling takes the mean.

Max and average pooling, in 1-D and 2-D (lecture 22)

Max and average pooling by 10 on the ReLU feature map: 2000 values become 200.

<Figure size 1200x300 with 1 Axes>

2.4 Some notes on translationΒΆ

In the convolutional layer, the neurons are not connected to every part of the input data.

A dense layer learns global patterns. A convolution layer learns local patterns and is translation equivariant: shift the input and the feature map shifts with it, so a pattern learned in one part of the image (or time series) is detected anywhere else. The approximate translation invariance of a full CNN, the same prediction wherever the pattern sits, comes from the pooling layers that discard position as they downsample; the 1-D detector in section 4 gets its shift tolerance from its global average pool. CNNs also learn hierarchical patterns: a first layer learns a local pattern, a second layer combines the local features into broader-scale features.

The same record shifted: the feature map moves with it, its maximum does not (lecture 22)

Check both properties on our record, moved 3 s later.

equivariance: the shifted map is the map shifted by 3 s: True
invariance after global max pooling: 15.320 before the shift, 15.320 after

2.5 The shape of a network: wide and shallow, or long and skinnyΒΆ

With the same number of weights, a CNN can be wide and shallow (one layer with many filters) or long and skinny (many layers with few filters each). The choice sets two things:

  • What one output unit can see: the receptive field, the span of input that reaches one unit of the last layer. Each convolution adds (kβˆ’1)(k-1) input steps to it, and each pooling multiplies the step size by the pooling factor. Depth with pooling makes it grow fast; width does not change it.

  • What kinds of pattern the network can combine: a wide layer learns many patterns at one scale; a deep stack combines small patterns into larger ones (hierarchy).

Three 1-D networks for a 30 s record at 100 Hz, with a few thousand weights each.

Loading...

Similar numbers of weights, receptive fields from a third of a second to more than ten seconds. For an earthquake detector, the question is physical: the S wave arrives 0.6 s after the P wave at 5 km and almost 10 s after it at 80 km. A unit that should see both arrivals needs a receptive field longer than the S βˆ’ P time.

How far one unit of the section 4 detector sees, layer by layer (lecture 22)

In practice most CNNs take the middle road, a funnel: the number of filters grows as pooling shortens the feature maps (8, 16, 32 here), so each layer has a similar cost while the receptive field grows. Very deep, skinny stacks see far but are harder to train, because the gradient passes through many layers on its way back; batch normalization and residual connections (ResNet, He et al., 2016) were invented for that.

Exercise 2. Add one more block, *block(32, 64, 7, 4), to the funnel. How many weights does it add, and how long is the receptive field now? Is that long enough for an event at 80 km?

2.6 The last block: from feature maps to class probabilitiesΒΆ

The convolution and pooling layers return feature maps, shaped (batch, channels, length). A classifier must return one score per class for each record. The last block does it in three steps:

  1. Flatten the feature maps into one vector per record, either all values in order (nn.Flatten), or first one average per channel over the whole length (nn.AdaptiveAvgPool1d(1), global average pooling), then flatten.

  2. A fully connected layer (nn.Linear) turns the vector into one score per class. These scores are called logits; they can be any real number.

  3. The softmax turns the scores z1,…,zCz_1, \dots, z_C into probabilities that are positive and sum to 1: pc=ezc/βˆ‘jezjp_c = e^{z_c} / \sum_j e^{z_j}. The predicted class is the one with the highest probability.

Two records through the funnel, for two classes (noise, event):

feature maps:               (2, 32, 46) (batch, channels, length)
A. flatten:                 (2, 1472) -> linear with 2,946 weights
B. global average, flatten: (2, 32) -> linear with 66 weights

logits (one score per class):
 [[ 0.181 -0.269]
 [ 0.174 -0.259]]

The softmax, by hand and with PyTorch:

probabilities (noise, event):
 [[0.611 0.389]
 [0.607 0.393]]
same as torch.softmax: True
each row sums to 1: [1. 1.]
predicted class (0 noise, 1 event): [0 0]

The weights are still random, so the probabilities are close to 0.5 and mean nothing yet; training (section 4.3) changes that.

Two practical notes:

  • The model ends at the logits, without a softmax layer. nn.CrossEntropyLoss applies the softmax itself (in a numerically safer form) before taking the negative log of the probability of the right class. Call torch.softmax only when you want probabilities, after training.

  • Flatten or global average? Option A keeps the position of each value and ties the network to one input length: a 2000-sample record would no longer fit the linear layer. Option B forgets position, works for any length, and has far fewer weights; it is the choice for detection, where an event can occur anywhere. Keep position (option A, or no pooling at all) when position is the answer, as when picking an arrival time.

Exercise 3. Pass a record of 2000 samples through funnel and then through each head. Which one fails, and what does the error message say?

2.7 Aside: image segmentation vocabularyΒΆ

Classification assigns one label to a whole image. Segmentation assigns labels at the pixel level, and comes in three flavors. A standard illustration is a street scene shown three ways: semantic segmentation colors every pixel by class (road, sky, person, car) without separating individuals; instance segmentation outlines each individual object (this person, that car) separately; panoptic segmentation combines both, labeling every pixel by class while keeping object instances distinct.

3. A 2-D CNN on a gridded geoscience fieldΒΆ

Gridded fields β€” reanalysis temperature, satellite radiances, model output β€” are the native 2-D data of the geosciences, We use the course generator mlgeo_synth.climate_field: monthly temperature anomalies on a 40 x 80 latitude-longitude grid, with a hemisphere-antisymmetric seasonal cycle, a slow zonal mode, spatially correlated weather noise, and a linear warming trend amplified at high northern latitudes. Because the generator is ours, the true local trend of every pixel is known exactly.

The task. Regress the local warming trend, in Β°C per decade, from 8 x 8-pixel patches. Each patch enters the network as a 30-channel image: 30 annual-mean anomaly maps, one channel per year. Channels-as-time is the standard trick for feeding a time-evolving field to a 2-D CNN.

The split. Every patch from one field shares that field’s global trend value, so patches from the same field must never straddle the train/test boundary β€” the grouped-splitting doctrine of Chapter 3.8, applied. We generate 24 fields with trends drawn uniformly between 0.05 and 0.5 Β°C/decade, and split by field: 18 for training, 6 for testing.

The baseline first. Average each patch spatially and fit a straight line through its 30 annual means β€” one call to np.polyfit. If the CNN cannot beat that, we want to know.

patches: (1200, 30, 8, 8) | true local trends 0.05 to 1.36 C/decade
train: 900 patches from 18 fields | test: 300 patches from 6 fields
least-squares baseline, test MAE: 0.083 C/decade
parameters: 17,953
epoch 10: train MSE 0.0008 (C/decade)^2
epoch 20: train MSE 0.0001 (C/decade)^2
epoch 30: train MSE 0.0001 (C/decade)^2
test MAE (C/decade)  naive least squares: 0.083   + known mode: 0.009   2-D CNN: 0.008
<Figure size 1200x400 with 3 Axes>

Both learned and classical estimators recover the poleward-amplified trend structure, but the margins deserve a careful read. The naive straight-line fit lands at 0.083 Β°C/decade MAE while the CNN reaches 0.008 β€” a factor of ten. Before crediting the network with magic, ask what it learned. The generator superposes a slow 5-year zonal mode on every field, and over a 30-year record that mode does not average out of a straight-line fit: it aliases into the slope. The middle panel gives the classical estimator that one piece of physics β€” the known mode as a single extra regressor β€” and its MAE drops to 0.009 Β°C/decade, statistically indistinguishable from the CNN.

So the honest takeaway: the CNN’s win over naive least squares is really a win over an underspecified baseline. What the network extracted from 18 training fields is the confounding interannual mode β€” which it could do only because that mode is identical in every synthetic field. Deep models earn their keep when the confounders are unknown or unwritable; when you can write them down, the classical fit with the right regressors matches the CNN at a fraction of the cost. Also note what the grouped split bought us: had patches from one field landed on both sides of the boundary, the CNN could have memorized field-specific noise and the comparison would be meaningless. The earthquake detector below gets exactly the same treatment against its own classical baseline.

4. A 1-D CNN earthquake detectorΒΆ

Convolutions are not limited to images. Seismologists use 1-D CNNs to scan continuous seismograms and classify short windows as β€œearthquake” or β€œnoise”. ConvNetQuake (Perol et al., 2018) was an early example; modern pickers such as EQTransformer and PhaseNet follow the same idea at larger scale.

Real waveform datasets are large and their labels are imperfect. Here we instead use the course’s synthetic seismogram generator, mlgeo_synth. Each event trace contains a P arrival followed by a stronger S arrival, on top of colored noise; each noise trace contains only colored noise. Each window draws its own noise color and each event its own dominant frequency (2 to 8 Hz), so the detector cannot separate the classes by one fixed spectral shape. Because we control the generator, every trace comes with exact metadata: arrival times and the signal-to-noise ratio (SNR, defined as peak signal amplitude divided by noise standard deviation).

4.1 Generate and inspect the dataΒΆ

X: (1600, 3000) - y: (1600,)
Class balance: 800 events, 800 noise
Example event metadata: {'t_p': 9.21, 't_s': 12.21, 'peak_amplitude': 0.5, 'snr': 0.58, 'magnitude': 2.91, 'distance_km': 25.23, 'noise_color': 1.72, 'f0': 7.48}
<Figure size 900x700 with 4 Axes>

Low-SNR events are hard to see by eye. That is exactly the regime where we want to know how a detector behaves.

Before training we standardize each trace (remove its mean, divide by its standard deviation). This is important: without it, the network could classify on absolute amplitude alone instead of on waveform shape.

train 1120, val 240, test 240

4.2 The modelΒΆ

The 1-D analog of the image CNN: three blocks of Conv1d β†’ ReLU β†’ MaxPool1d, then an AdaptiveAvgPool1d that averages each feature map down to a single value, and a linear head with 2 outputs (noise, event). Global average pooling keeps the parameter count small and makes the model independent of the input length.

========================================================================================== Layer (type:depth-idx) Output Shape Param # ========================================================================================== Sequential [1, 2] -- β”œβ”€Conv1d: 1-1 [1, 8, 3000] 64 β”œβ”€ReLU: 1-2 [1, 8, 3000] -- β”œβ”€MaxPool1d: 1-3 [1, 8, 750] -- β”œβ”€Conv1d: 1-4 [1, 16, 750] 912 β”œβ”€ReLU: 1-5 [1, 16, 750] -- β”œβ”€MaxPool1d: 1-6 [1, 16, 187] -- β”œβ”€Conv1d: 1-7 [1, 32, 187] 3,616 β”œβ”€ReLU: 1-8 [1, 32, 187] -- β”œβ”€MaxPool1d: 1-9 [1, 32, 46] -- β”œβ”€AdaptiveAvgPool1d: 1-10 [1, 32, 1] -- β”œβ”€Flatten: 1-11 [1, 32] -- β”œβ”€Linear: 1-12 [1, 2] 66 ========================================================================================== Total params: 4,658 Trainable params: 4,658 Non-trainable params: 0 Total mult-adds (Units.MEGABYTES): 1.55 ========================================================================================== Input size (MB): 0.01 Forward/backward pass size (MB): 0.34 Params size (MB): 0.02 Estimated Total Size (MB): 0.37 ==========================================================================================

Under 5,000 parameters, against 61,706 for LeNet-5 (1998). Small models train fast and are hard to overfit on 1,120 training traces.

Your turn (2): the weights of the first layerΒΆ

A Conv1d layer with C_in input channels, C_out filters and kernels of k weights has C_out * (C_in * k + 1) weights (the 1 is the bias of each filter). Write n_first, the number of weights of the first layer of model_seis, from that formula, and compare with the first row of the summary above.

Answer below (click to open it).

Notebook Cell
64 weights in the first layer

4.3 Train and evaluateΒΆ

The training function: for each epoch, a pass over the training batches (scores, loss, gradients, update), then the validation loss and accuracy with gradients turned off. It keeps a copy of the weights of the epoch with the best validation accuracy, and restores it at the end. Twelve epochs run in a few seconds.

[Epoch 1] train loss: 0.693 - val loss: 0.688 - val accuracy: 59.6%
[Epoch 2] train loss: 0.679 - val loss: 0.663 - val accuracy: 59.2%
[Epoch 3] train loss: 0.619 - val loss: 0.567 - val accuracy: 67.5%
[Epoch 4] train loss: 0.500 - val loss: 0.470 - val accuracy: 81.2%
[Epoch 5] train loss: 0.449 - val loss: 0.473 - val accuracy: 70.4%
[Epoch 6] train loss: 0.418 - val loss: 0.448 - val accuracy: 79.2%
[Epoch 7] train loss: 0.395 - val loss: 0.411 - val accuracy: 81.7%
[Epoch 8] train loss: 0.385 - val loss: 0.399 - val accuracy: 83.3%
[Epoch 9] train loss: 0.369 - val loss: 0.422 - val accuracy: 80.0%
[Epoch 10] train loss: 0.362 - val loss: 0.380 - val accuracy: 84.6%
[Epoch 11] train loss: 0.381 - val loss: 0.422 - val accuracy: 80.0%
[Epoch 12] train loss: 0.370 - val loss: 0.384 - val accuracy: 82.5%
Restored checkpoint with best validation accuracy: 84.6%
<Figure size 900x320 with 2 Axes>
Test accuracy: 82.5%

Accuracy in the 80s: far above chance, but well short of perfect. Why not 100%? The dataset deliberately includes events with SNR well below 1, which are close to undetectable. That leads to the real question: where does the detector fail?

4.4 The payoff: the detection floor, with a classical opponentΒΆ

With real seismograms you never know the true SNR of a missed event, so a detector’s low-SNR behavior is hard to characterize. Synthetics give us the knob real data never does: we can generate events at any SNR we choose and measure exactly where detection breaks down.

The CNN does not get the stage to itself. The STA/LTA trigger (short-term average over long-term average; Allen, 1978) β€” the classical detector that has run in observatory pipelines for decades, and whose detection floor we measured on Ricker wavelets in Chapter 2.10 β€” runs on the same traces, with the same SNR definition (peak signal amplitude over noise standard deviation). Its threshold is set the honest way, from noise alone: the 99th percentile of peak STA/LTA over all 600 noise-only windows, which pins its false-alarm rate at 1% by construction.

The sweep below generates 60 events at each of 10 SNR values from about 0.3 to 20 (log-spaced), with magnitude, distance, and noise seed varied, plus 60 matched noise-only windows per SNR value. The trained network runs in inference mode; no retraining is involved. Each detection probability is 60 Bernoulli trials, so both curves carry binomial (Wilson) error bars.

STA/LTA threshold (99th percentile of noise-only peaks): 4.11
   SNR   CNN detect   CNN false alarm   STA/LTA detect
  0.32         0.00              0.02             0.00
  0.50         0.03              0.00             0.00
  0.79         0.07              0.00             0.02
  1.26         0.40              0.00             0.02
  2.00         0.92              0.02             0.02
  3.16         0.97              0.02             0.03
  5.01         1.00              0.03             0.13
  7.94         1.00              0.02             0.33
 12.59         1.00              0.05             0.77
 19.95         1.00              0.00             0.98
<Figure size 700x420 with 1 Axes>

Read the two curves at their operating points first: the dashed false-alarm rates are comparable (1% pinned for STA/LTA, 0-5% measured for the CNN), so the detection curves can be compared directly. Three regimes. Below SNR β‰ˆ 0.8 the two detectors agree at their false-alarm floor: no algorithm, learned or classical, rescues a signal buried that deep in noise. At SNR 20 they agree again, near 1.0; there the classical trigger is the right engineering choice, because it costs nothing to train or maintain and cannot drift when the data change. The CNN earns its complexity in the band between: at SNR 2 it detects 90% of events while STA/LTA at the same false-alarm budget catches 2%, and its 50% crossing sits near SNR 1.4 against the trigger’s near SNR 9 (interpolated between the points of the table). In this run the noise color changes from window to window, which makes the trigger’s floor higher than with a single noise model; compare with the floor the Ricker-wavelet experiment found in Chapter 2.10. About a decade of SNR is the territory the learned detector wins. Whether that territory matters is a scientific question, not an architectural one; in seismology it happens to be where most small earthquakes live, which is why learned detectors displaced energy triggers in catalog building.

This kind of controlled measurement is the main argument for synthetic benchmarks: with real data you can only report performance on the events you happened to catalog, and the catalog itself is biased against low-SNR events.

Why not template matching? There is a classical method that beats both of these detectors at low SNR: template matching, which cross-correlates a known event waveform against continuous data and triggers on the correlation coefficient. For a known waveform in stationary noise it is the matched filter β€” statistically optimal β€” and in practice it detects repeating events roughly an order of magnitude below the STA/LTA floor (Gibbons & Ringdal, 2006); it is how low-frequency earthquakes were pulled out of tremor (Shelly et al., 2007). The catch is in the name: it needs a template, so it only finds events that repeat a waveform you already have β€” aftershock sequences, swarms, repeating earthquakes, induced seismicity. It answers a narrower question (β€œdid this source rupture again?”) than the detectors above (β€œis any event present?”), and benchmarking it fairly would require a repeating-source dataset, which is why it stays out of worked scope here.

Exercise 2. From the sweep results, estimate the SNR at which the CNN’s detection probability crosses 50%, and the same for STA/LTA. Then retrain the model with only 2 epochs and rerun the sweep. Does the CNN’s detection floor move? Does STA/LTA’s?

5. How to read and recode published networksΒΆ

Say a research paper describes the architecture of the CNN the authors used for their analysis, but provides no code. How would you reproduce it?

Consider this paper:

Rouet-Leduc, B., Hulbert, C., McBrearty, I. W., Johnson, P. A. (2020). Probing slow earthquakes with deep learning. Geophysical Research Letters, 47, e2019GL085870. Rouet‐Leduc et al. (2020)

(Figure 1 of Rouet-Leduc et al. (2020) shows the network architecture; see the paper at Rouet‐Leduc et al. (2020) β€” the figure is not reproduced here for licensing reasons.)

Reading the paper and its supplementary material, we can list the layers:

  • Input: spectrogram image of 129 x 95 x 1 pixels

  • Conv2D: kernel size 16 x 16, depth 32 (number of channels), producing feature maps of size 114 x 80; ReLU activation (found in the supplementary material)

  • Max pooling of size 2

  • Dropout 5% (found in the supplementary material)

  • Conv2D: kernel size 8 x 8, depth 64

  • Max pooling of size 2

  • Dropout 5% (found in the supplementary material)

  • Conv2D: kernel size 4 x 4, depth 128

  • Fully connected (dense) layer flattening to 36,608 values (found in the supplementary material)

  • Fully connected (dense) layer with 10 neurons

  • Fully connected (dense) layer with 1 neuron, sigmoid activation, giving the probability that the window contains tremor

Now we translate that list, line by line, into a torch.nn.Sequential stack:

To check the translation, we run a forward pass on a dummy tensor with the paper’s input shape, (batch, channels, height, width) = (1, 1, 129, 95), and inspect the shape after every layer:

Input shape: 		 torch.Size([1, 1, 129, 95])
Conv2d output shape: 	 torch.Size([1, 32, 114, 80])
ReLU output shape: 	 torch.Size([1, 32, 114, 80])
MaxPool2d output shape: 	 torch.Size([1, 32, 57, 40])
Dropout output shape: 	 torch.Size([1, 32, 57, 40])
Conv2d output shape: 	 torch.Size([1, 64, 50, 33])
ReLU output shape: 	 torch.Size([1, 64, 50, 33])
MaxPool2d output shape: 	 torch.Size([1, 64, 25, 16])
Dropout output shape: 	 torch.Size([1, 64, 25, 16])
Conv2d output shape: 	 torch.Size([1, 128, 22, 13])
Flatten output shape: 	 torch.Size([1, 36608])
Linear output shape: 	 torch.Size([1, 10])
Sigmoid output shape: 	 torch.Size([1, 10])
Linear output shape: 	 torch.Size([1, 1])
Sigmoid output shape: 	 torch.Size([1, 1])
========================================================================================== Layer (type:depth-idx) Output Shape Param # ========================================================================================== Sequential [1, 1] -- β”œβ”€Conv2d: 1-1 [1, 32, 114, 80] 8,224 β”œβ”€ReLU: 1-2 [1, 32, 114, 80] -- β”œβ”€MaxPool2d: 1-3 [1, 32, 57, 40] -- β”œβ”€Dropout: 1-4 [1, 32, 57, 40] -- β”œβ”€Conv2d: 1-5 [1, 64, 50, 33] 131,136 β”œβ”€ReLU: 1-6 [1, 64, 50, 33] -- β”œβ”€MaxPool2d: 1-7 [1, 64, 25, 16] -- β”œβ”€Dropout: 1-8 [1, 64, 25, 16] -- β”œβ”€Conv2d: 1-9 [1, 128, 22, 13] 131,200 β”œβ”€Flatten: 1-10 [1, 36608] -- β”œβ”€Linear: 1-11 [1, 10] 366,090 β”œβ”€Sigmoid: 1-12 [1, 10] -- β”œβ”€Linear: 1-13 [1, 1] 11 β”œβ”€Sigmoid: 1-14 [1, 1] -- ========================================================================================== Total params: 636,661 Trainable params: 636,661 Non-trainable params: 0 Total mult-adds (Units.MEGABYTES): 329.27 ========================================================================================== Input size (MB): 0.05 Forward/backward pass size (MB): 3.47 Params size (MB): 2.55 Estimated Total Size (MB): 6.07 ==========================================================================================

Two checks against the paper: the first convolution outputs feature maps of 114 x 80, exactly as stated, and the flattened vector entering the dense layers has 128 x 22 x 13 = 36,608 values, matching the β€œ36,608 neurons” in the supplementary material. When these numbers line up, the recoding is consistent with the published table.

Note that we do not train this network. The exercise here is translating a published architecture description into working code and verifying it against the paper’s reported shapes and parameter counts. Training it would require the paper’s dataset (years of continuous seismic and GPS data from Cascadia) and substantial compute, neither of which this course has, and neither of which is needed to learn the skill.

6. Tuning CNN networksΒΆ

There are many hyperparameters and model choices to make:

  • Training: learning rate, optimizer, batch size, loss function, regularization

  • Architecture: number of layers, number of channels (depth) per layer, kernel sizes, activation functions, batch normalization, dropout

Notebook 4.7 measures what the main ones do (starting weights, learning rate, batch size, width and depth, early stopping), one at a time.

SummaryΒΆ

  • A convolution slides a small kernel over the input; hand-designed kernels blur or detect edges, and a CNN learns its kernels from data.

  • A CNN block is convolution, activation, pooling; a classification head is one or more fully connected layers.

  • LeNet-5 in PyTorch is a dozen lines; a 1-D CNN earthquake detector is even smaller.

  • On a gridded climate field, a small 2-D CNN beats naive least-squares trend estimation tenfold β€” but only because it learned the generator’s confounding interannual mode; give the classical fit that mode as one regressor and the two match at ~0.01 Β°C/decade.

  • Measured on the same traces at comparable false-alarm rates, STA/LTA crosses 50% detection near SNR 5 and the CNN near 1.5; the band between is the entire case for the learned detector.

  • Scored unchanged on real miniPNW waveforms, the synthetic-trained detector falls from 87.9% to 46.8% balanced accuracy β€” chance β€” because real microseism-rich noise triggers it constantly. The synthetic-to-real gap is the measurement; synthetic-only validation is not validation.

  • A published architecture table plus torchinfo.summary shape checks is enough to recode a network you have no source code for.

Next: recurrent networks for sequential data in notebook 4.4.

ReferencesΒΆ
  1. Gibbons, S. J., & Ringdal, F. (2006). The detection of low magnitude seismic events using array-based waveform correlation. Geophysical Journal International, 165(1), 149–166. 10.1111/j.1365-246x.2006.02865.x
  2. Shelly, D. R., Beroza, G. C., & Ide, S. (2007). Non-volcanic tremor and low-frequency earthquake swarms. Nature, 446(7133), 305–307. 10.1038/nature05666
  3. Rouet‐Leduc, B., Hulbert, C., McBrearty, I. W., & Johnson, P. A. (2020). Probing Slow Earthquakes With Deep Learning. Geophysical Research Letters, 47(4). 10.1029/2019gl085870