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:
Convolutions and kernels, on a simple synthetic seismogram (1-D) and a simple synthetic temperature map (2-D).
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.
A 2-D CNN regressing warming trends from a gridded synthetic climate field, against a least-squares baseline.
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.
How to translate a published architecture table into working code.
The same kind of detector on real seismograms (miniPNW) is the homework, Homework_DL.
import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torch.nn as nn
import torchinfo
from scipy.signal import convolve2d
from torch.utils.data import DataLoader, TensorDataset
# Device-agnostic setup: CUDA GPU, Apple silicon (MPS), or CPU.
device = torch.device("cuda" if torch.cuda.is_available()
else "mps" if torch.backends.mps.is_available()
else "cpu")
print(f"Using device: {device}")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:
where is the input, is the kernel of convolution, and is a dummy variable.

For discrete functions, you simply sum:
Deep-learning libraries compute the same sliding sum without flipping the kernel (a cross-correlation, ), 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.
fs = 100.0 # samples per second
t = np.arange(0, 20, 1 / fs)
rng = np.random.default_rng(0)
def burst(t, t0, f0=5.0, width=0.25):
"""A short wave packet of frequency f0 (Hz) centred on t0 (s)."""
return np.cos(2 * np.pi * f0 * (t - t0)) * np.exp(-((t - t0) / width) ** 2)
signal = (0.5 * np.sin(2 * np.pi * 0.05 * t) # slow drift
+ burst(t, 5.0) + 0.5 * burst(t, 13.0) # two arrivals
+ 0.2 * rng.standard_normal(t.size)) # noise
# the kernel: 0.8 s of the same wave packet (80 weights), with its mean removed so that it ignores the drift
tk = np.arange(0, 0.8, 1 / fs)
kernel = burst(tk, 0.4)
kernel -= kernel.mean()
fig, ax = plt.subplots(1, 2, figsize=(13, 3), gridspec_kw={"width_ratios": [4, 1]})
ax[0].plot(t, signal, color="0.4", lw=0.8)
ax[0].set_xlabel("time (s)"); ax[0].set_title("synthetic record", loc="left")
ax[1].plot(tk, kernel, "o-", color="tab:orange", ms=3)
ax[1].set_xlabel("time (s)"); ax[1].set_title(f"kernel: {kernel.size} weights", loc="left")
fig.tight_layout()
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.

The same computation, by hand, at two positions: on the first arrival, and in the noise.
K = kernel.size
for k, where in [(int(4.6 * fs), "kernel centred on the first arrival"), (int(9.0 * fs), "in the noise")]:
window = signal[k:k + K]
products = kernel * window
print(f"position {k / fs:4.1f} s ({where}): sum of the {K} products = {products.sum():+.2f}")
# every position: one output per position ("valid": the kernel stays inside the record)
output = np.array([np.sum(kernel * signal[k:k + K]) for k in range(signal.size - K + 1)])
print("output length:", output.size, "= record length", signal.size, "- kernel length", K, "+ 1")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.
conv = nn.Conv1d(in_channels=1, out_channels=1, kernel_size=K, bias=False)
with torch.no_grad():
conv.weight[:] = torch.tensor(kernel, dtype=torch.float32).view(1, 1, K)
x = torch.tensor(signal, dtype=torch.float32).view(1, 1, -1) # (batch, channels, samples)
out_torch = conv(x).detach().numpy().ravel()
print("same as the loop:", np.allclose(out_torch, output, atol=1e-4))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.
x10 = np.array([0, 1, 2, 1, 0, 0, -1, -2, -1, 0])
kernel3 = np.array([1, 2, 1])
out = None # your line here
print(out)None
Answer below (click to open it).
Notebook Cell
out = [int(np.sum(kernel3 * x10[k:k + 3])) for k in range(len(x10) - 2)]
print(out)[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.
kernels = {
"1 s average": np.ones(100) / 100,
"difference, 0.05 s apart": np.r_[-1.0, np.zeros(4), 1.0],
"5 Hz wave packet": kernel,
}
fig, axes = plt.subplots(4, 1, figsize=(12, 7), sharex=True)
axes[0].plot(t, signal, color="0.4", lw=0.8); axes[0].set_title("record", loc="left")
for ax, (name, kern) in zip(axes[1:], kernels.items()):
out = np.correlate(signal, kern, mode="same")
ax.plot(t, out, lw=0.9)
ax.set_title(f"output of the kernel: {name}", loc="left")
axes[-1].set_xlabel("time (s)")
fig.tight_layout()
1.2 Two dimensions: a temperature mapΒΆ
Convolution extends to multiple dimensions: the kernel becomes a small square that slides along both directions.

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):
ny, nx = 60, 80
yy, xx = np.mgrid[0:ny, 0:nx] # row 0 is the north edge
front = 30 + 8 * np.sin(2 * np.pi * xx / 80) # latitude row of the front
temperature = (-5 + 10 * (1 + np.tanh((yy - front) / 1.5)) # cold north, warm south
+ 6 * np.exp(-((xx - 60) ** 2 + (yy - 12) ** 2) / (2 * 3 ** 2)) # warm anomaly
+ 0.8 * rng.standard_normal((ny, nx))) # noise
# Kernel size
filterDimension = 3
# Define a mean filter
mean_filter = np.ones((filterDimension, filterDimension)) / (filterDimension * filterDimension)
# Apply the mean filter to the map using convolution
filtered = convolve2d(temperature, mean_filter, mode='same', boundary='symm')
fig, ax = plt.subplots(1, 2, figsize=(11, 3.6))
for a, img, title in zip(ax, [temperature, filtered], ["synthetic temperature (Β°C)", f"mean filter, {filterDimension} x {filterDimension}"]):
im = a.imshow(img, cmap='RdYlBu_r', vmin=-8, vmax=20)
a.set_title(title, loc="left"); a.axis('off')
fig.colorbar(im, ax=ax, shrink=0.8);
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.
# Sobel filters
sobel_filter_horizontal = np.array([
[-1, -2, -1],
[0, 0, 0],
[1, 2, 1]
])
sobel_filter_vertical = np.array([
[-1, 0, 1],
[-2, 0, 2],
[-1, 0, 1]
])
# Apply the Sobel filters to the map
result_horizontal = convolve2d(temperature, sobel_filter_horizontal, mode='same', boundary='symm')
result_vertical = convolve2d(temperature, sobel_filter_vertical, mode='same', boundary='symm')
# Combine the two directions to get the size of the gradient
edges = np.sqrt(result_horizontal**2 + result_vertical**2)
# Thresholding to accentuate the edges
threshold = 8
edges[edges < threshold] = 0
fig, axes = plt.subplots(1, 4, figsize=(15, 3.2))
axes[0].imshow(temperature, cmap='RdYlBu_r')
axes[0].set_title('Temperature')
v = np.abs(result_horizontal).max()
axes[1].imshow(result_horizontal, cmap='PuOr_r', vmin=-v, vmax=v)
axes[1].set_title('Horizontal Sobel (north-south change)')
axes[2].imshow(result_vertical, cmap='PuOr_r', vmin=-v, vmax=v)
axes[2].set_title('Vertical Sobel (east-west change)')
axes[3].imshow(edges, cmap='gray_r')
axes[3].set_title('Combined edges (thresholded)')
for a in axes:
a.axis('off')
fig.tight_layout()
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.

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?
Solution
A 15 x 15 mean filter averages over a much larger neighborhood: the front becomes a broad gradual change instead of a sharp one, and the warm anomaly (about 6 cells across) is smeared out and loses most of its amplitude. The kernel size sets the spatial scale of the features a convolution responds to; anything smaller than the kernel is averaged away.
2. Assembling a CNNΒΆ
The architecture of a CNN classically comprises:
A convolutional layer
An activation layer
A pooling layer
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.

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?
# pytorch version
torch.nn.Conv2d(in_channels=3, out_channels=64, kernel_size=6)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 , the stride and the padding : . Four filters on our 20 s record:
x = torch.tensor(signal, dtype=torch.float32).view(1, 1, -1) # (batch 1, channel 1, 2000 samples)
for k, s, p in [(7, 1, 0), (7, 1, 3), (7, 2, 3)]:
layer = nn.Conv1d(in_channels=1, out_channels=4, kernel_size=k, stride=s, padding=p)
n_w = sum(q.numel() for q in layer.parameters())
print(f"kernel {k}, stride {s}, padding {p}: {tuple(x.shape)} -> {tuple(layer(x).shape)} ({n_w} weights)")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 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:
z = torch.linspace(-5, 5, 201)
activations = {
"ReLU": torch.relu(z),
"leaky ReLU (0.1)": nn.functional.leaky_relu(z, 0.1),
"sigmoid": torch.sigmoid(z),
"tanh": torch.tanh(z),
"GELU": nn.functional.gelu(z),
}
fig, axes = plt.subplots(1, 5, figsize=(16, 3), sharey=True)
for ax, (name, a) in zip(axes, activations.items()):
ax.plot(z, a, lw=2.5)
ax.axhline(0, color="k", lw=0.5); ax.axvline(0, color="k", lw=0.5)
ax.set_title(name); ax.set_xlabel("input z"); ax.grid(ls="--", lw=0.5)
axes[0].set_ylabel("output")
fig.tight_layout()
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.
feature_map = np.correlate(signal, kernel, mode="same")
relu_map = np.maximum(feature_map, 0)
fig, ax = plt.subplots(2, 1, figsize=(12, 4), sharex=True)
ax[0].plot(t, feature_map, lw=0.8); ax[0].set_title("feature map (output of the 5 Hz kernel)", loc="left")
ax[1].plot(t, relu_map, lw=0.8, color="tab:green"); ax[1].set_title("after ReLU: negative values set to zero", loc="left")
ax[1].set_xlabel("time (s)")
fig.tight_layout()
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 by 10 on the ReLU feature map: 2000 values become 200.
fm = torch.tensor(relu_map, dtype=torch.float32).view(1, 1, -1)
max_pooled = nn.MaxPool1d(kernel_size=10)(fm).numpy().ravel()
avg_pooled = nn.AvgPool1d(kernel_size=10)(fm).numpy().ravel()
t_pooled = t[::10] + 0.05
fig, ax = plt.subplots(figsize=(12, 3))
ax.plot(t, relu_map, color="0.7", lw=0.8, label=f"after ReLU ({relu_map.size} values)")
ax.step(t_pooled, max_pooled, where="mid", lw=2, label=f"max pooling by 10 ({max_pooled.size} values)")
ax.step(t_pooled, avg_pooled, where="mid", lw=2, label=f"average pooling by 10 ({avg_pooled.size} values)")
ax.set_xlabel("time (s)"); ax.legend(fontsize=9)
fig.tight_layout()
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.

Check both properties on our record, moved 3 s later.
shift = int(3 * fs)
shifted = np.roll(signal, shift)
fm_shifted = np.maximum(np.correlate(shifted, kernel, mode="same"), 0)
print("equivariance: the shifted map is the map shifted by 3 s:",
np.allclose(fm_shifted[shift + K:-K], relu_map[K:-shift - K]))
print(f"invariance after global max pooling: {relu_map.max():.3f} before the shift, {fm_shifted.max():.3f} after")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 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.
def receptive_field(model):
"""Span of input samples that reaches one unit of the last layer."""
rf, step = 1, 1
for layer in model.modules():
if isinstance(layer, nn.Conv1d):
rf += (layer.kernel_size[0] - 1) * step * layer.dilation[0]
step *= layer.stride[0]
elif isinstance(layer, (nn.MaxPool1d, nn.AvgPool1d)):
rf += (layer.kernel_size - 1) * step
step *= layer.stride
return rf
def block(c_in, c_out, k, pool):
return [nn.Conv1d(c_in, c_out, k, padding=k // 2), nn.ReLU(), nn.MaxPool1d(pool)]
wide_shallow = nn.Sequential(*block(1, 128, 31, 4))
funnel = nn.Sequential(*block(1, 8, 7, 4), *block(8, 16, 7, 4), *block(16, 32, 7, 4)) # the detector of section 4
long_skinny = nn.Sequential(*block(1, 8, 7, 2), *[m for _ in range(7) for m in block(8, 8, 7, 2)])
x = torch.zeros(1, 1, 3000)
rows = []
for name, net in [("wide and shallow: 1 layer, 128 filters", wide_shallow),
("funnel: 3 layers, 8-16-32 filters", funnel),
("long and skinny: 8 layers, 8 filters", long_skinny)]:
out = net(x)
rf = receptive_field(net)
rows.append({"network": name, "weights": sum(q.numel() for q in net.parameters()),
"output shape (channels, length)": tuple(out.shape[1:]),
"receptive field (samples)": rf, "receptive field (s)": rf / fs})
pd.DataFrame(rows).set_index("network")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.

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?
Solution
The block adds 64 x 32 x 7 + 64 = 14,400 weights, three times the whole funnel. The receptive field grows from 190 to 190 + 6 x 64 + 3 x 64 = 766 samples, 7.7 s: long enough for the S β P time out to about 65 km, not 80 km. Each extra block costs more weights than the last, which is why networks for long records use dilated convolutions or attention instead.
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:
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.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.The softmax turns the scores into probabilities that are positive and sum to 1: . The predicted class is the one with the highest probability.
Two records through the funnel, for two classes (noise, event):
torch.manual_seed(0) # random starting weights, drawn with a seed
records = torch.randn(2, 1, 3000) # a batch of 2 records, 1 channel, 3000 samples
maps = funnel(records)
print("feature maps: ", tuple(maps.shape), "(batch, channels, length)")
# option A: flatten every value
head_flatten = nn.Sequential(nn.Flatten(), nn.Linear(maps.shape[1] * maps.shape[2], 2))
print("A. flatten: ", tuple(nn.Flatten()(maps).shape),
f"-> linear with {sum(q.numel() for q in head_flatten.parameters()):,} weights")
# option B: global average pooling, then flatten
head_gap = nn.Sequential(nn.AdaptiveAvgPool1d(1), nn.Flatten(), nn.Linear(maps.shape[1], 2))
print("B. global average, flatten:", tuple(nn.Flatten()(nn.AdaptiveAvgPool1d(1)(maps)).shape),
f"-> linear with {sum(q.numel() for q in head_gap.parameters()):,} weights")
logits = head_gap(maps)
print("\nlogits (one score per class):\n", logits.detach().numpy().round(3))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:
z = logits.detach()
p_by_hand = torch.exp(z) / torch.exp(z).sum(dim=1, keepdim=True)
p_torch = torch.softmax(z, dim=1)
print("probabilities (noise, event):\n", p_by_hand.numpy().round(3))
print("same as torch.softmax:", torch.allclose(p_by_hand, p_torch))
print("each row sums to 1:", p_by_hand.sum(dim=1).numpy().round(6))
print("predicted class (0 noise, 1 event):", p_by_hand.argmax(dim=1).numpy())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.CrossEntropyLossapplies the softmax itself (in a numerically safer form) before taking the negative log of the probability of the right class. Calltorch.softmaxonly 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?
Solution
head_gap works: global average pooling returns 32 numbers whatever the length. head_flatten fails with a shape error: the flattened vector now has 32 x 31 = 992 values, while its linear layer was built for 32 x 46 = 1,472 inputs.
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.
import mlgeo_synth
n_fields, n_years, patch = 24, 30, 8
rng_f = np.random.default_rng(0)
true_trends = rng_f.uniform(0.05, 0.5, n_fields) # one global trend per field, deg C / decade
X_patches, y_trend, field_id = [], [], []
for fi, trend in enumerate(true_trends):
field, truth = mlgeo_synth.climate_field(n_lat=40, n_lon=80, n_months=12 * n_years,
trend_c_per_decade=float(trend), seed=100 + fi)
annual = field.reshape(n_years, 12, 40, 80).mean(axis=1) # (30, 40, 80) annual means
# the generator amplifies the trend poleward in the north:
# local trend = global trend x (1 + 1.5 * max(latitude in radians, 0))
amp = 1.0 + 1.5 * np.clip(np.deg2rad(truth["lat"]), 0, None)
local_trend = trend * amp
for r in range(0, 40, patch):
for c in range(0, 80, patch):
X_patches.append(annual[:, r:r + patch, c:c + patch])
y_trend.append(local_trend[r:r + patch].mean())
field_id.append(fi)
X_patches = np.array(X_patches, dtype=np.float32)
y_trend = np.array(y_trend, dtype=np.float32)
field_id = np.array(field_id)
print("patches:", X_patches.shape,
f"| true local trends {y_trend.min():.2f} to {y_trend.max():.2f} C/decade")
train_mask = field_id < 18 # grouped split: fields 0-17 train, 18-23 test
Xc_train, yc_train = X_patches[train_mask], y_trend[train_mask]
Xc_test, yc_test = X_patches[~train_mask], y_trend[~train_mask]
print(f"train: {len(Xc_train)} patches from 18 fields | test: {len(Xc_test)} patches from 6 fields")
# Classical baseline: least-squares slope of the patch-mean annual series
years = np.arange(n_years)
def lsq_trend(patches):
"""Least-squares warming trend (deg C / decade) of each patch's spatial-mean series."""
series = patches.mean(axis=(2, 3)) # (n, 30)
slopes = np.polyfit(years, series.T, 1)[0] # deg C / year
return slopes * 10.0
mae_lsq = np.abs(lsq_trend(Xc_test) - yc_test).mean()
print(f"least-squares baseline, test MAE: {mae_lsq:.3f} C/decade")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
torch.manual_seed(0)
model_clim = nn.Sequential(
nn.Conv2d(n_years, 32, kernel_size=3, padding=1), nn.ReLU(),
nn.Conv2d(32, 32, kernel_size=3, padding=1), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(),
nn.Linear(32, 1),
)
print(f"parameters: {sum(p.numel() for p in model_clim.parameters()):,}")
clim_loader = DataLoader(TensorDataset(torch.from_numpy(Xc_train), torch.from_numpy(yc_train)),
batch_size=64, shuffle=True)
model_clim.to(device)
opt = torch.optim.Adam(model_clim.parameters(), lr=1e-3)
mse = nn.MSELoss()
for epoch in range(30):
model_clim.train()
running = 0.0
for xb, yb in clim_loader:
xb, yb = xb.to(device), yb.to(device)
opt.zero_grad()
loss = mse(model_clim(xb).squeeze(1), yb)
loss.backward()
opt.step()
running += loss.item() * len(xb)
if (epoch + 1) % 10 == 0:
print(f"epoch {epoch + 1:2d}: train MSE {running / len(Xc_train):.4f} (C/decade)^2")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
model_clim.eval()
with torch.no_grad():
pred_cnn = model_clim(torch.from_numpy(Xc_test).to(device)).squeeze(1).cpu().numpy()
pred_lsq = lsq_trend(Xc_test)
mae_cnn = np.abs(pred_cnn - yc_test).mean()
# A fairer classical opponent: the generator's slow interannual mode (a 5-year cycle,
# identical in every field) aliases into a straight-line fit. Adding that known mode
# as one extra regressor is all it takes.
zon_annual = np.sin(2 * np.pi * np.arange(12 * n_years) / 60.0).reshape(n_years, 12).mean(axis=1)
G = np.column_stack([np.ones(n_years), years, zon_annual])
def lsq_trend_modeaware(patches):
"""Trend (deg C / decade) with the known interannual mode as a co-regressor."""
series = patches.mean(axis=(2, 3))
coef, *_ = np.linalg.lstsq(G, series.T, rcond=None)
return coef[1] * 10.0
pred_lsq2 = lsq_trend_modeaware(Xc_test)
mae_lsq2 = np.abs(pred_lsq2 - yc_test).mean()
lims = [0, 1.05 * max(yc_test.max(), pred_cnn.max(), pred_lsq.max())]
fig, ax = plt.subplots(1, 3, figsize=(12, 4), sharex=True, sharey=True)
for a, pred, name, mae in [(ax[0], pred_lsq, 'Least squares', mae_lsq),
(ax[1], pred_lsq2, 'Least squares + known mode', mae_lsq2),
(ax[2], pred_cnn, '2-D CNN', mae_cnn)]:
a.scatter(yc_test, pred, s=12, alpha=0.6)
a.plot(lims, lims, 'k--', lw=1, label='1:1')
a.set_xlabel('True local trend (C/decade)')
a.set_title(f'{name}\ntest MAE {mae:.3f} C/decade')
a.legend(loc='upper left')
a.grid(alpha=0.3)
ax[0].set_ylabel('Estimated trend (C/decade)')
fig.tight_layout()
print(f"test MAE (C/decade) naive least squares: {mae_lsq:.3f} "
f"+ known mode: {mae_lsq2:.3f} 2-D CNN: {mae_cnn:.3f}")test MAE (C/decade) naive least squares: 0.083 + known mode: 0.009 2-D CNN: 0.008

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ΒΆ
import mlgeo_synth
fs = 100.0 # sampling rate (Hz)
X_seis, y_seis, metas = mlgeo_synth.seismogram_dataset(n_events=800, n_noise=800, fs=fs,
duration_s=30.0, seed=0,
noise_color_range=(0.5, 2.0), f0_range=(2.0, 8.0))
print("X:", X_seis.shape, "- y:", y_seis.shape)
print("Class balance: %d events, %d noise" % ((y_seis == 1).sum(), (y_seis == 0).sum()))
print("Example event metadata:", {k: round(float(v), 2) for k, v in metas[0].items()})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}
t = np.arange(X_seis.shape[1]) / fs
fig, axes = plt.subplots(4, 1, figsize=(9, 7), sharex=True)
# three events with their P and S arrival times
event_idx = [0, 1, 2]
for ax, i in zip(axes[:3], event_idx):
ax.plot(t, X_seis[i], color='tab:gray', linewidth=0.8)
ax.axvline(metas[i]['t_p'], color='tab:blue', linestyle='--', label='P arrival')
ax.axvline(metas[i]['t_s'], color='tab:red', linestyle='--', label='S arrival')
ax.set_ylabel('Amplitude')
ax.set_title(f"Event, SNR = {metas[i]['snr']:.1f}", fontsize=10, loc='left')
axes[0].legend(loc='upper right')
# one noise-only window
noise_idx = np.where(y_seis == 0)[0][0]
axes[3].plot(t, X_seis[noise_idx], color='tab:gray', linewidth=0.8)
axes[3].set_title('Noise window', fontsize=10, loc='left')
axes[3].set_ylabel('Amplitude')
axes[3].set_xlabel('Time (s)')
fig.tight_layout()
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.
from sklearn.model_selection import train_test_split
def standardize(X):
"""Per-trace standardization: zero mean, unit standard deviation."""
X = X - X.mean(axis=1, keepdims=True)
return X / (X.std(axis=1, keepdims=True) + 1e-10)
Xn = standardize(X_seis).astype(np.float32)
# 70% train, 15% validation, 15% test
X_train, X_tmp, y_train, y_tmp = train_test_split(Xn, y_seis, test_size=0.3,
random_state=42, stratify=y_seis)
X_val, X_test, y_val, y_test = train_test_split(X_tmp, y_tmp, test_size=0.5,
random_state=42, stratify=y_tmp)
def make_loader(X, y, batch_size, shuffle):
# unsqueeze(1) adds the channel dimension: (batch, 1, n_samples)
ds = TensorDataset(torch.from_numpy(X).unsqueeze(1), torch.from_numpy(y).long())
return DataLoader(ds, batch_size=batch_size, shuffle=shuffle)
train_loader = make_loader(X_train, y_train, 64, shuffle=True)
val_loader = make_loader(X_val, y_val, 256, shuffle=False)
test_loader = make_loader(X_test, y_test, 256, shuffle=False)
print(f"train {len(X_train)}, val {len(X_val)}, test {len(X_test)}")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.
torch.manual_seed(1)
model_seis = nn.Sequential(
nn.Conv1d(1, 8, kernel_size=7, padding=3), nn.ReLU(), nn.MaxPool1d(4),
nn.Conv1d(8, 16, kernel_size=7, padding=3), nn.ReLU(), nn.MaxPool1d(4),
nn.Conv1d(16, 32, kernel_size=7, padding=3), nn.ReLU(), nn.MaxPool1d(4),
nn.AdaptiveAvgPool1d(1),
nn.Flatten(),
nn.Linear(32, 2),
)
torchinfo.summary(model_seis, input_size=(1, 1, 3000))==========================================================================================
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.
n_first = None # your line hereAnswer below (click to open it).
Notebook Cell
n_first = 8 * (1 * 7 + 1)
print(n_first, "weights in the first layer")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.
def train_model(model, train_loader, val_loader, n_epochs=2, learning_rate=1e-3, device=device):
"""Train a classifier, record per-epoch metrics, and restore the best-validation checkpoint."""
model.to(device)
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
history = {"train_loss": [], "val_loss": [], "val_acc": []}
best_acc, best_state = -1.0, None
for epoch in range(n_epochs):
# --- training pass ---
model.train()
running_loss = 0.0
for inputs, labels in train_loader:
inputs = inputs.float().to(device)
labels = labels.long().to(device)
optimizer.zero_grad()
loss = criterion(model(inputs), labels)
loss.backward()
optimizer.step()
running_loss += loss.item()
history["train_loss"].append(running_loss / len(train_loader))
# --- validation pass (no gradients) ---
model.eval()
val_loss, correct, total = 0.0, 0, 0
with torch.no_grad():
for inputs, labels in val_loader:
inputs = inputs.float().to(device)
labels = labels.long().to(device)
outputs = model(inputs)
val_loss += criterion(outputs, labels).item()
correct += (outputs.argmax(dim=1) == labels).sum().item()
total += labels.size(0)
history["val_loss"].append(val_loss / len(val_loader))
history["val_acc"].append(100 * correct / total)
print(f"[Epoch {epoch + 1}] train loss: {history['train_loss'][-1]:.3f} - "
f"val loss: {history['val_loss'][-1]:.3f} - val accuracy: {history['val_acc'][-1]:.1f}%")
# checkpoint: remember the weights of the best epoch so far
if history["val_acc"][-1] > best_acc:
best_acc = history["val_acc"][-1]
best_state = {k: v.detach().clone() for k, v in model.state_dict().items()}
model.load_state_dict(best_state)
print(f"Restored checkpoint with best validation accuracy: {best_acc:.1f}%")
return historytorch.manual_seed(1)
history_seis = train_model(model_seis, train_loader, val_loader, n_epochs=12, learning_rate=2e-3)[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%
epochs = np.arange(1, len(history_seis["train_loss"]) + 1)
fig, ax = plt.subplots(1, 2, figsize=(9, 3.2))
ax[0].plot(epochs, history_seis["train_loss"], marker='o', label='train loss')
ax[0].plot(epochs, history_seis["val_loss"], marker='s', label='validation loss')
ax[0].set_xlabel('Epoch')
ax[0].set_ylabel('Cross-entropy loss')
ax[0].legend()
ax[1].plot(epochs, history_seis["val_acc"], marker='o', color='tab:green', label='validation accuracy')
ax[1].set_xlabel('Epoch')
ax[1].set_ylabel('Accuracy (%)')
ax[1].legend()
fig.suptitle('1-D CNN detector on synthetic seismograms')
fig.tight_layout()
def predict(model, X, device=device):
"""Predicted class (0 noise, 1 event) for an array of standardized traces."""
model.eval()
with torch.no_grad():
xb = torch.from_numpy(X.astype(np.float32)).unsqueeze(1).to(device)
return model(xb).argmax(dim=1).cpu().numpy()
test_pred = predict(model_seis, X_test)
test_acc = (test_pred == y_test).mean()
print(f"Test accuracy: {100 * test_acc:.1f}%")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.
from obspy.signal.trigger import classic_sta_lta
snrs = np.logspace(-0.5, 1.3, 10) # ~0.32 to ~20
n_per = 60
rng = np.random.default_rng(42)
nsta, nlta = int(1.0 * fs), int(5.0 * fs) # 1 s / 5 s: arrivals sit 6-28 s into the window
def peak_stalta(trace):
"""Peak STA/LTA ratio, ignoring the first LTA window (not yet filled)."""
cft = classic_sta_lta(trace, nsta, nlta)
return cft[nlta:].max()
def wilson_interval(k, n, z=1.0):
"""Wilson score interval for a binomial proportion (z=1: roughly 68% coverage)."""
p = k / n
denom = 1 + z**2 / n
center = (p + z**2 / (2 * n)) / denom
half = z * np.sqrt(p * (1 - p) / n + z**2 / (4 * n**2)) / denom
return center - half, center + half
detect_prob = np.zeros(len(snrs)) # CNN: fraction of events flagged as events
false_alarm = np.zeros(len(snrs)) # CNN: fraction of noise windows flagged as events
stalta_ev_peaks, stalta_no_peaks = [], []
for i, snr in enumerate(snrs):
# events at this SNR, with varied magnitude, distance, and noise realization
traces = []
for k in range(n_per):
mag = rng.uniform(1, 4)
dist = rng.uniform(5, 80)
_, trace, _ = mlgeo_synth.synthetic_seismogram(magnitude=mag, distance_km=dist,
snr=float(snr), seed=int(10000 * i + k),
noise_color=rng.uniform(0.5, 2.0),
f0=rng.uniform(2.0, 8.0))
traces.append(trace)
traces = np.array(traces)
# matched noise-only windows
X_no, _, _ = mlgeo_synth.seismogram_dataset(n_events=0, n_noise=n_per, seed=7000 + i,
noise_color_range=(0.5, 2.0))
pred_ev = predict(model_seis, standardize(traces))
pred_no = predict(model_seis, standardize(X_no))
detect_prob[i] = pred_ev.mean()
false_alarm[i] = pred_no.mean()
# STA/LTA peaks on the very same traces (the ratio is amplitude-invariant)
stalta_ev_peaks.append(np.array([peak_stalta(tr) for tr in traces]))
stalta_no_peaks.append(np.array([peak_stalta(tr) for tr in X_no]))
# STA/LTA threshold from noise alone: 99th percentile of 600 noise windows -> 1% false alarms
stalta_thresh = np.quantile(np.concatenate(stalta_no_peaks), 0.99)
stalta_prob = np.array([(pk >= stalta_thresh).mean() for pk in stalta_ev_peaks])
stalta_fa = np.array([(pk >= stalta_thresh).mean() for pk in stalta_no_peaks])
print(f"STA/LTA threshold (99th percentile of noise-only peaks): {stalta_thresh:.2f}")
print(" SNR CNN detect CNN false alarm STA/LTA detect")
for snr, d, f, sd in zip(snrs, detect_prob, false_alarm, stalta_prob):
print(f"{snr:6.2f} {d:10.2f} {f:15.2f} {sd:14.2f}")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
def binom_err(p, n):
"""Asymmetric Wilson error bars for an array of proportions."""
lo, hi = np.array([wilson_interval(int(round(pi * n)), n) for pi in p]).T
return p - lo, hi - p
cnn_lo, cnn_hi = binom_err(detect_prob, n_per)
sta_lo, sta_hi = binom_err(stalta_prob, n_per)
fig, ax = plt.subplots(figsize=(7, 4.2))
ax.errorbar(snrs, detect_prob, yerr=[cnn_lo, cnn_hi], marker='o', capsize=3,
label='CNN detection probability')
ax.errorbar(snrs, stalta_prob, yerr=[sta_lo, sta_hi], marker='s', capsize=3,
color='tab:orange', label='STA/LTA detection probability (1% false alarms)')
ax.plot(snrs, false_alarm, color='tab:red', ls='--', lw=1, marker='^', ms=4,
label='CNN false alarm rate')
ax.plot(snrs, stalta_fa, color='tab:brown', ls=':', lw=1, marker='v', ms=4,
label='STA/LTA false alarm rate')
ax.set_xscale('log')
ax.set_xlabel('SNR (peak signal amplitude / noise standard deviation)')
ax.set_ylabel('Fraction of windows')
ax.set_ylim(-0.05, 1.05)
ax.set_title('Detection floor: 1-D CNN vs STA/LTA, same traces')
ax.legend(loc='center left', fontsize=9)
ax.grid(alpha=0.3, which='both')
fig.tight_layout()
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?
Solution
Read the crossings off the printed table or the plot (you can interpolate with np.interp(0.5, detect_prob, snrs) since the curves are roughly monotonic); the CNN crosses at a lower SNR than the classical trigger. With only 2 training epochs the network is undertrained: its transition shifts to higher SNR and its top plateau may sit below 1.0, so its detection floor rises. The STA/LTA curve does not move at all β it has no parameters to undertrain, which is exactly what makes it a stable baseline. Training longer, adding data, or augmenting with low-SNR examples pushes the CNNβs floor down, up to the limit set by the noise itself.
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:
model_tremor = torch.nn.Sequential(
nn.Conv2d(in_channels=1, out_channels=32, kernel_size=16),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
nn.Dropout(0.05),
nn.Conv2d(in_channels=32, out_channels=64, kernel_size=8),
nn.ReLU(),
nn.MaxPool2d(kernel_size=2),
nn.Dropout(0.05),
nn.Conv2d(in_channels=64, out_channels=128, kernel_size=4),
nn.Flatten(),
nn.Linear(36608, 10),
nn.Sigmoid(),
nn.Linear(10, 1),
nn.Sigmoid(),
)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:
Xd = torch.randn(1, 1, 129, 95)
print('Input shape: \t\t', Xd.shape)
for layer in model_tremor:
Xd = layer(Xd)
print(layer.__class__.__name__, 'output shape: \t', Xd.shape)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])
torchinfo.summary(model_tremor, input_size=(1, 1, 129, 95))==========================================================================================
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.summaryshape checks is enough to recode a network you have no source code for.
Next: recurrent networks for sequential data in notebook 4.4.
- 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
- 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
- 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