The perceptron is one neuron: it computes a weighted sum of its inputs, adds a bias, and passes the result through an activation function. It is the building block of neural networks. This notebook is about how its weights are found: gradient descent, the method of 3.6, written out one step at a time.
Build a neuron from scratch with NumPy.
Train it by gradient descent to fit travel times: random starting weights, predictions, errors, the loss of each sample, the mean loss, the gradient of the loss, the update of the weights, the loss at each epoch, batches.
Change the learning rate.
Use the same loop to separate seismic events from noise (sigmoid and log-loss, as in 3.6), and compare it with the perceptron rule of Rosenblatt (1958).
Give the neuron a waveform as input and compare its weights with a template.
Add a hidden layer and train the network by backpropagation: the errors sent back through the layers.
🖥️ Lecture slides, Session 21 (Mon Nov 16 and Wed Nov 18)
Notation. The same as in 3.6.
| Symbol | Name | In the code |
|---|---|---|
| input of sample | x | |
| observation for sample | y | |
| prediction of the neuron for sample | yhat | |
| error: prediction minus observation | error | |
| , | weight and bias | w, b |
| loss of sample | lossPerSample | |
| loss: the mean of over the samples of a batch | loss | |
| , | gradient of the loss | gradW, gradB |
| learning rate | learningRate |
A batch is the set of samples used for one update of the weights. An epoch is one pass through all the training samples.
Your turn cells. Eight cells ask for one line of code each. The hidden cell below each one holds the solution and checks your answer; if your answer is missing, it uses the solution so that the rest of the notebook still runs.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, LogisticRegression
import mlgeo_synth
from mlgeo_synth.seismic import synthetic_seismogram1. A neuron from scratch¶
A neuron with inputs , weights and bias computes the prediction
where is the activation function. We implement three activations: none (identity), sigmoid, and step.
The weights and the bias do not start at zero. They are drawn at random, with a seed so that the same numbers come out at every run. Section 2.1 explains why.


class simplePerceptron:
# Activation functions
def __none(x):
return x
def __sigmoid(x):
return 1 / (1 + np.exp(-x))
def __step(x):
return np.where(x >= 0, 1.0, 0.0)
possibleActivations = {
'none': __none,
'sigmoid': __sigmoid,
'step': __step
}
# Initialize: random starting weights and bias, drawn with a seed
def __init__(self, nInputs=1, activation='none', seed=0):
rng = np.random.default_rng(seed)
self.w = rng.normal(0, 1, nInputs)
self.b_w = rng.normal(0, 1)
if activation not in self.possibleActivations:
activation = 'none'
self.activation = activation
def setWs(self, w, b_w):
self.w = w
self.b_w = b_w
def predict(self, x):
# x should be an (n, p) array: each row is one sample
score = x @ np.asarray(self.w, dtype=float) + self.b_w # weighted sum plus the bias, for every sample
return self.possibleActivations[self.activation](score)1.1 Test the neuron¶
A new neuron holds random weights. With the weight set to 1, the bias to 0, and no activation, it should return its input unchanged.
ourPerceptron = simplePerceptron(nInputs=1, activation='none', seed=0)
print(f'Starting weight {ourPerceptron.w[0]:.3f}, starting bias {ourPerceptron.b_w:.3f} (seed 0)')
# A check of the code, not a starting value: with weight 1 and bias 0 the output equals the input
ourPerceptron.setWs([1], 0)
testInput = np.array([[100, -1, 0.1]]).T
ourPerceptron.predict(testInput)Starting weight 0.126, starting bias -0.132 (seed 0)
array([100. , -1. , 0.1])2. Gradient descent, one step at a time¶
The data. An earthquake is recorded at 100 stations. At each station we pick the arrival of the P wave and compute its travel time. In a crust of uniform velocity , the travel time grows with the distance to the epicenter as : a line, whose slope is the slowness .
The table below is synthetic (written in the next cell): a velocity of 6 km/s, a delay of 1 s, and 0.5 s of noise on each pick. Each station is one sample. The observation is the travel time in seconds. The input is the distance, standardized with the mean and the standard deviation of the training samples.
The model. One neuron with no activation: .
Training means finding the and for which the predictions are closest to the observations . For a line, least squares gives the answer in one formula (lecture 13). We use gradient descent here because it is the method that still works when the model is a network with thousands of weights, and on a line every one of its steps can be drawn.
# Synthetic: one earthquake, P-wave travel times picked at 100 stations
rng = np.random.default_rng(1)
nSamples = 100
distance = rng.uniform(5, 150, nSamples) # distance to the epicenter (km)
travelTime = 1.0 + distance / 6.0 + rng.normal(0, 0.5, nSamples) # travel time (s): 6 km/s, 1 s delay, 0.5 s of noise
# 80 samples to train, 20 kept for the test
trainDistance, testDistance = distance[:80], distance[80:]
y, yTest = travelTime[:80], travelTime[80:]
# Standardize the input with the mean and standard deviation of the training samples only
dMean, dStd = trainDistance.mean(), trainDistance.std()
x, xTest = (trainDistance - dMean) / dStd, (testDistance - dMean) / dStd
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.scatter(trainDistance, y, s=14, color='k', label='training samples (80)')
ax.scatter(testDistance, yTest, s=14, color='C1', label='test samples (20)')
ax.set_xlabel('Distance to the epicenter (km)')
ax.set_ylabel('P travel time (s)')
ax.set_title('Synthetic travel times: 6 km/s, noise 0.5 s')
ax.legend();
2.1 Start from random weights, with a seed¶
Gradient descent improves the weights step by step, so they need a starting value. We draw and at random from a normal distribution with mean 0 and standard deviation 1.
Why not zeros? In a network (4.1), hidden neurons that start with the same weights receive the same gradient at every update, so they stay copies of each other and the layer behaves like one neuron. Random starting weights make the neurons differ from the first step. One neuron alone would also train from zero, but we keep the habit that every network needs.
Why a seed? The random generator returns the same numbers for the same seed, so the run can be repeated exactly. Report the seed with the result.
seed = 0
rng = np.random.default_rng(seed)
w = rng.normal(0, 1) # starting weight
b = rng.normal(0, 1) # starting bias
print(f'seed {seed}: starting weight w = {w:.3f}, starting bias b = {b:.3f}')
# The line that three different seeds start from
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.scatter(x, y, s=14, color='k', label='training samples')
xLine = np.linspace(x.min(), x.max(), 50)
for s in (0, 1, 2):
r = np.random.default_rng(s)
ws, bs = r.normal(0, 1), r.normal(0, 1)
ax.plot(xLine, ws * xLine + bs, lw=2, label=f'seed {s}: w = {ws:.2f}, b = {bs:.2f}')
ax.set_xlabel('x: standardized distance')
ax.set_ylabel('Travel time (s)')
ax.set_title('Before training: predictions from random weights')
ax.legend();seed 0: starting weight w = 0.126, starting bias b = -0.132

2.2 Predictions and errors¶
With the current weights the neuron makes a prediction for each sample, . The error of sample is the difference between the prediction and the observation:
Here the error is in seconds. It is negative when the predicted travel time is too short.
Your turn (1): the errors¶
Compute error, the prediction minus the observation, for the 80 training samples.
Hint: yhat - y.
yhat = w * x + b # predictions with the starting weights
error = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
error = yhat - yprint('First five training samples:')
print(' distance (km) x observation y (s) prediction yhat (s) error (s)')
for i in range(5):
print(f' {trainDistance[i]:10.1f} {x[i]:6.2f} {y[i]:14.2f} {yhat[i]:17.2f} {error[i]:10.2f}')
fig, ax = plt.subplots(figsize=(6.5, 4))
ax.vlines(x, y, yhat, color='C3', lw=1, label='error of each sample')
ax.scatter(x, y, s=14, color='k', zorder=3, label='observations')
ax.plot(xLine, w * xLine + b, color='C0', lw=2, label='predictions (starting weights)')
ax.set_xlabel('x: standardized distance')
ax.set_ylabel('Travel time (s)')
ax.set_title('Errors: prediction minus observation')
ax.legend();First five training samples:
distance (km) x observation y (s) prediction yhat (s) error (s)
79.2 -0.09 14.37 -0.14 -14.51
142.8 1.43 24.48 0.05 -24.43
25.9 -1.37 5.75 -0.30 -6.05
142.6 1.43 24.70 0.05 -24.65
50.2 -0.79 9.70 -0.23 -9.93

2.3 The loss of each sample, and its mean¶
The loss turns the errors into one number to make small. We use the squared error. Each sample has its own loss,
in s² here. The loss of a batch of samples is the mean of the losses of its samples (the mean squared error):
For now the batch is the whole training set, .
Your turn (2): the mean loss¶
lossPerSample holds the 80 values . Compute loss, their mean.
Hint: lossPerSample.mean().
lossPerSample = error ** 2 # one loss per sample
loss = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
loss = np.mean(lossPerSample)print(f'Loss per sample: from {lossPerSample.min():.1f} to {lossPerSample.max():.1f} s². Mean (the loss): {loss:.1f} s²')
# The losses of 16 samples, in order of distance
show = np.sort(np.arange(16))[np.argsort(trainDistance[:16])]
fig, ax = plt.subplots(figsize=(8, 3.8))
ax.bar(range(16), lossPerSample[show], color='C3')
ax.axhline(loss, color='k', ls='--', label=f'mean over the 80 samples: {loss:.0f} s²')
ax.set_xticks(range(16))
ax.set_xticklabels([f'{d:.0f}' for d in trainDistance[show]])
ax.set_xlabel('Distance of the station (km): 16 of the 80 samples')
ax.set_ylabel('Loss of the sample (s²)')
ax.set_title('The loss differs from sample to sample')
ax.legend();Loss per sample: from 3.8 to 641.6 s². Mean (the loss): 269.1 s²

With the starting weights, the far stations have the largest losses: the line is nearly flat, and their travel times are the longest. Because the error is squared, the samples with the largest errors count the most in the mean.
2.4 The gradient of the loss¶
The chain rule¶
When a quantity A changes a quantity B, and B changes C, the change of C with A is the product of the two changes:
A geoscience example. Along a borehole, temperature rises with depth, by about 25 °C per km, and P-wave velocity falls with temperature, by about 0.0005 km/s per °C (round values for the example). One km deeper is 25 °C warmer, and 25 °C warmer is 25 × 0.0005 = 0.0125 km/s slower:
The neuron. The weight changes the prediction, , and the prediction changes the loss of the sample, . Two links:
The input is the link from the weight to the prediction: raising by a small amount raises the prediction by times that amount. The error is the link from the prediction to the loss. The cell below computes both links for the farthest station and checks their product against a small change of the weight.

far = np.argmax(trainDistance) # the farthest training station
link1 = x[far] # d(prediction)/d(weight): the input
link2 = 2 * error[far] # d(loss of the sample)/d(prediction): 2 x error
print(f'Station at {trainDistance[far]:.0f} km: input {link1:.2f}, error {error[far]:.2f} s')
print(f'Chain rule: {link1:.2f} x ({link2:.2f}) = {link1 * link2:.2f}')
dw = 1e-4 # check: raise w a little and measure the loss of this sample
lossBefore = (w * x[far] + b - y[far]) ** 2
lossAfter = ((w + dw) * x[far] + b - y[far]) ** 2
print(f'Small change of w: {(lossAfter - lossBefore) / dw:.2f}')Station at 147 km: input 1.54, error -24.24 s
Chain rule: 1.54 x (-48.48) = -74.55
Small change of w: -74.55
From the chain rule to the gradient of the loss¶
The loss depends on the weight and on the bias, because the predictions do. The gradient says how the loss changes when each of them is raised a little. As in 3.6: is positive if the loss increases when increases, and negative if the loss decreases when increases.
For one sample, with , the chain rule gives
Each sample has its own gradient: its error times its input. The loss is the mean of the , so its gradient is the mean of the gradients of the samples:
There is one gradient value for each weight: here two numbers, one for and one for .
Your turn (3): the gradient for the bias¶
gradW is written for you. Compute gradB, the mean over the samples of .
Hint: np.mean(2 * error).
gradWPerSample = 2 * error * x # the gradient of each sample, for the weight
gradW = gradWPerSample.mean() # the gradient of the loss: their mean
gradB = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
gradB = np.mean(2 * error)print(f'Gradient of the loss: {gradW:.2f} for the weight, {gradB:.2f} for the bias')
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].bar(range(16), gradWPerSample[show], color='C0')
axes[0].axhline(gradW, color='k', ls='--', label=f'mean over the 80 samples: {gradW:.1f}')
axes[0].set_xticks(range(16))
axes[0].set_xticklabels([f'{d:.0f}' for d in trainDistance[show]])
axes[0].set_xlabel('Distance of the station (km): 16 of the 80 samples')
axes[0].set_ylabel('Gradient of the sample, for w')
axes[0].set_title('Each sample has its own gradient')
axes[0].legend()
wGrid = np.linspace(-4, 18, 200)
lossGrid = np.array([np.mean((wg * x + b - y) ** 2) for wg in wGrid])
axes[1].plot(wGrid, lossGrid, color='k', label='loss against w (b fixed)')
tangent = np.linspace(w - 3, w + 3, 2)
axes[1].plot(tangent, loss + gradW * (tangent - w), color='C3', lw=3, label=f'slope at the current w: {gradW:.1f}')
axes[1].scatter([w], [loss], color='C3', zorder=3)
axes[1].annotate('', xy=(w + 3.5, loss), xytext=(w + 0.3, loss), arrowprops=dict(arrowstyle='->', color='C2', lw=2.5))
axes[1].text(w + 3.8, loss, 'the update\ngoes this way', color='C2', va='center')
axes[1].set_xlabel('Weight w')
axes[1].set_ylabel('Loss (s²)')
axes[1].set_title('The gradient is the slope of the loss')
axes[1].legend(loc='upper center')
fig.tight_layout()Gradient of the loss: -13.58 for the weight, -29.85 for the bias

Left: the gradients of the samples differ in size, and in sign on either side of the mean distance (); the mean is the number used for the update. Right: the loss drawn against the weight, with the bias held fixed. The gradient is the slope of this curve at the current weight. It is negative: raising lowers the loss.
The same gradient for any activation. For a neuron with activation , the score is and the prediction . The chain rule gives, for one sample,
and the gradient of the loss is the mean of this over the samples of the batch.
| Activation | Loss of a sample | Slope | Gradient for one sample |
|---|---|---|---|
| none (this section) | squared error | 1 | : error × input |
| sigmoid (section 4.1) | log-loss | : error × input | |
| step (section 4.2) | any | 0 (undefined at ) | 0: no gradient, the weights never move |
The rule of 1958 sets the slope of the step to 1 by hand to get an update. Section 6 adds a hidden layer: the chain then has one more link per layer, each with the slope of an activation.
2.5 One update of the weights¶
The gradient answers two questions for each weight: which way should it move, and how far? Gradient descent moves each weight against its gradient, by an amount proportional to the gradient. This is the update of 3.6:
where is the learning rate and counts the updates.
The sign. The gradient is positive when raising the weight raises the loss. The minus sign then lowers the weight. When the gradient is negative, raising the weight lowers the loss, and the minus sign raises it. Either way the loss goes down.
The size. The change of the weight is times the gradient. Where the loss is steep the weight moves a lot; near the lowest point the gradient is close to zero and the weight hardly moves.
Each weight has its own gradient and moves by its own amount, at the same time as the others.
In numbers, with the gradients of 2.4 and :
| value now | gradient of the loss | change: gradient | value after the update | |
|---|---|---|---|---|
| weight | 0.126 | −13.58 | −0.1 × (−13.58) = +1.358 | 1.484 |
| bias | −0.132 | −29.85 | −0.1 × (−29.85) = +2.985 | 2.853 |
Both gradients are negative, so both values go up. The bias moves more than the weight because its gradient is larger. The cell after Your turn (4) draws this update on the curve of the loss.
Your turn (4): update the weight¶
bNew is written for you. Compute wNew.
Hint: w - learningRate * gradW.
learningRate = 0.1
bNew = b - learningRate * gradB
wNew = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
wNew = w - learningRate * gradWlossNew = np.mean((wNew * x + bNew - y) ** 2)
print(f'Before the update: w = {w:.3f}, b = {b:.3f}, loss = {loss:.1f} s²')
print(f'After one update: w = {wNew:.3f}, b = {bNew:.3f}, loss = {lossNew:.1f} s²')Before the update: w = 0.126, b = -0.132, loss = 269.1 s²
After one update: w = 1.484, b = 2.853, loss = 172.3 s²
Left: the loss against the weight, with the bias held at its current value. The weight starts at the red dot, where the slope of the loss (the gradient, dashed) is −13.58. The update moves it by gradient = +1.36, to the green dot, where the loss is lower and the slope is less steep. Right: the same for the bias, with its own gradient, −29.85, and its own change, +2.99. After both moves together, the loss is 172.3 s² (it was 269.1 s²).
fig, axes = plt.subplots(1, 2, figsize=(13, 4.5))
for ax, name, now, new, grad, lossOf in [
(axes[0], 'weight w', w, wNew, gradW, lambda v: np.mean((v * x + b - y) ** 2)),
(axes[1], 'bias b', b, bNew, gradB, lambda v: np.mean((w * x + v - y) ** 2))]:
grid = np.linspace(now - 2, now + 2.5 * (new - now) + 2, 200)
ax.plot(grid, [lossOf(v) for v in grid], color='k', label='loss')
tangent = np.array([now - 1.2, now + 1.2])
ax.plot(tangent, lossOf(now) + grad * (tangent - now), 'r--', lw=2, label=f'slope = gradient = {grad:.2f}')
ax.scatter([now], [lossOf(now)], s=80, color='r', zorder=3, label=f'now: {now:.3f}')
ax.scatter([new], [lossOf(new)], s=80, color='g', zorder=3, label=f'after the update: {new:.3f}')
ax.annotate('', xy=(new, lossOf(now)), xytext=(now, lossOf(now)), arrowprops=dict(arrowstyle='->', color='g', lw=2.5))
ax.text((now + new) / 2, lossOf(now) * 1.03, f'change = −{learningRate} × ({grad:.2f}) = {-learningRate * grad:+.2f}',
ha='center', va='bottom', color='g')
ax.set_xlabel(name)
ax.set_ylabel('Loss (s²)')
ax.set_title(f'One update of the {name}')
ax.legend(fontsize=8, loc='upper right')
fig.tight_layout()
2.6 Repeat: the loss at each epoch¶
One update lowers the loss a little. Training repeats the same five lines: predictions, errors, loss, gradient, update. Here each update uses all 80 training samples, so one update is one epoch. We store the loss at each epoch, and print it at a few of them.
rng = np.random.default_rng(seed)
w, b = rng.normal(0, 1), rng.normal(0, 1) # random starting weights, same seed as above
learningRate = 0.1
nEpochs = 60
history = {'loss': [], 'w': [], 'b': [], 'gradW': [], 'gradB': [], 'lossPerSample': []}
for epoch in range(nEpochs):
yhat = w * x + b # 1. predictions
error = yhat - y # 2. errors: prediction minus observation
lossPerSample = error ** 2 # 3. loss of each sample ...
loss = lossPerSample.mean() # ... and its mean over the samples
gradW = np.mean(2 * error * x) # 4. gradient of the loss, for each weight
gradB = np.mean(2 * error)
for key, value in zip(history, (loss, w, b, gradW, gradB, lossPerSample)):
history[key].append(value)
if epoch in (0, 1, 2, 5, 10, 20, 40, nEpochs - 1):
print(f'epoch {epoch:2d}: loss {loss:8.3f} s² gradient for w {gradW:8.3f}, for b {gradB:8.3f} w {w:6.3f}, b {b:6.3f}')
w = w - learningRate * gradW # 5. update: against the gradient
b = b - learningRate * gradBepoch 0: loss 269.099 s² gradient for w -13.581, for b -29.852 w 0.126, b -0.132
epoch 1: loss 172.298 s² gradient for w -10.865, for b -23.881 w 1.484, b 2.853
epoch 2: loss 110.345 s² gradient for w -8.692, for b -19.105 w 2.570, b 5.241
epoch 5: loss 29.079 s² gradient for w -4.450, for b -9.782 w 4.691, b 9.903
epoch 10: loss 3.308 s² gradient for w -1.458, for b -3.205 w 6.187, b 13.191
epoch 20: loss 0.243 s² gradient for w -0.157, for b -0.344 w 6.838, b 14.622
epoch 40: loss 0.207 s² gradient for w -0.002, for b -0.004 w 6.915, b 14.792
epoch 59: loss 0.207 s² gradient for w -0.000, for b -0.000 w 6.916, b 14.794
epochs = np.arange(nEpochs)
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
axes[0].semilogy(epochs, history['loss'], color='C3')
axes[0].axhline(0.25, color='gray', ls=':')
axes[0].text(nEpochs, 0.27, 'variance of the noise, 0.25 s²', ha='right', va='bottom', color='gray')
axes[0].set_ylabel('Loss (s²)')
axes[0].set_title('Loss at each epoch')
axes[1].plot(epochs, history['gradW'], label='for the weight w')
axes[1].plot(epochs, history['gradB'], label='for the bias b')
axes[1].set_ylabel('Gradient of the loss')
axes[1].set_title('Gradient at each epoch')
axes[1].legend()
axes[2].plot(epochs, history['w'], label='weight w')
axes[2].plot(epochs, history['b'], label='bias b')
axes[2].set_ylabel('Value')
axes[2].set_title('Weight and bias at each epoch')
axes[2].legend()
for ax in axes:
ax.set_xlabel('Epoch')
ax.grid(color='gray', linestyle='dashed', alpha=0.4)
fig.tight_layout()
order = np.argsort(trainDistance)
fig, axes = plt.subplots(1, 2, figsize=(13, 4))
axes[0].scatter(x, y, s=14, color='k')
for k, color in zip((0, 2, 5, nEpochs - 1), ('C0', 'C1', 'C2', 'C3')):
axes[0].plot(xLine, history['w'][k] * xLine + history['b'][k], color=color, lw=2, label=f'epoch {k}')
axes[1].semilogy(trainDistance[order], history['lossPerSample'][k][order], '.', color=color,
label=f'epoch {k}: mean {history["loss"][k]:.2f} s²')
axes[0].set_xlabel('x: standardized distance')
axes[0].set_ylabel('Travel time (s)')
axes[0].set_title('Predictions during training')
axes[0].legend()
axes[1].set_xlabel('Distance of the station (km)')
axes[1].set_ylabel('Loss of the sample (s²)')
axes[1].set_title('Loss of each of the 80 samples')
axes[1].legend(fontsize=8)
fig.tight_layout()

Four things to read.
The loss goes down at every epoch, fast at first, and then flattens at 0.21 s². That is close to the variance of the noise in the picks (0.5 s squared, 0.25 s²): the line cannot predict the noise.
The gradients go to zero. At the lowest point of the loss the slope is zero, so the updates stop by themselves.
The weight and the bias settle. The bias is the mean travel time. The weight is the travel time added per standard deviation of distance.
The loss of each sample (last panel) goes down by orders of magnitude during training, and at the end it still differs from sample to sample: what is left is the noise of each pick.
The cell below converts the weight back to a velocity and computes the loss on the 20 test samples, which were never used for a gradient.
velocity = dStd / w # km/s: the weight is in s per standard deviation of distance
delay = b - w * dMean / dStd # s: the travel time at distance zero
testLoss = np.mean((w * xTest + b - yTest) ** 2)
print(f'Velocity {velocity:.2f} km/s (true 6), delay {delay:.2f} s (true 1)')
print(f'Loss on the training samples {history["loss"][-1]:.3f} s², on the test samples {testLoss:.3f} s²')Velocity 6.04 km/s (true 6), delay 1.04 s (true 1)
Loss on the training samples 0.207 s², on the test samples 0.400 s²
2.7 Batches¶
So far each update used every training sample. With a large dataset, the loss and its gradient are computed on a batch: a small set of samples. One epoch then holds several updates.
Shuffle the training samples.
Cut them into batches, here of 16 samples: 80 / 16 = 5 batches.
For each batch: predictions, errors, the mean of the loss over the 16 samples of the batch, the gradient of that mean, one update.
The loss of a batch is the mean over its own samples, so it differs from one batch to the next.
Your turn (5): the loss of a batch¶
Inside the loop, error holds the errors of the 16 samples of the current batch. Write batchMeanLoss, the mean of their squared errors.
Hint: np.mean(error ** 2).
def lossOfBatch(error):
batchMeanLoss = None # replace None with your expression
return batchMeanLossAnswer below (click to open it).
Notebook Cell
def lossOfBatch(error):
return np.mean(error ** 2)batchSize = 16
nEpochs = 20
rng = np.random.default_rng(seed)
w, b = rng.normal(0, 1), rng.normal(0, 1) # random starting weights
batchLoss, epochLoss = [], []
for epoch in range(nEpochs):
shuffled = rng.permutation(len(x)) # shuffle the samples at each epoch
lossesThisEpoch = []
for start in range(0, len(x), batchSize):
inBatch = shuffled[start:start + batchSize] # the 16 samples of this batch
yhat = w * x[inBatch] + b # 1. predictions
error = yhat - y[inBatch] # 2. errors
lossesThisEpoch.append(lossOfBatch(error)) # 3. loss: mean over the samples of the batch
gradW = np.mean(2 * error * x[inBatch]) # 4. gradient of that mean
gradB = np.mean(2 * error)
w = w - learningRate * gradW # 5. update, once per batch
b = b - learningRate * gradB
batchLoss.append(lossesThisEpoch)
epochLoss.append(np.mean(lossesThisEpoch))
if epoch in (0, 1, 2, nEpochs - 1):
print(f'epoch {epoch:2d}: loss of the 5 batches ' + ' '.join(f'{v:8.3f}' for v in lossesThisEpoch)
+ f' mean {epochLoss[-1]:8.3f} s²')
fig, ax = plt.subplots(figsize=(7, 4))
for k in range(nEpochs):
ax.semilogy([k] * len(batchLoss[k]), batchLoss[k], '.', color='C0', label='loss of each batch' if k == 0 else None)
ax.semilogy(range(nEpochs), epochLoss, color='C3', label='mean over the batches of the epoch')
ax.set_xlabel('Epoch')
ax.set_ylabel('Loss (s²)')
ax.set_title('Batches of 16 samples: 5 updates per epoch')
ax.legend();epoch 0: loss of the 5 batches 245.661 189.101 107.439 74.227 50.962 mean 133.478 s²
epoch 1: loss of the 5 batches 41.643 14.316 7.696 8.489 3.125 mean 15.054 s²
epoch 2: loss of the 5 batches 3.060 2.102 2.189 0.756 0.707 mean 1.763 s²
epoch 19: loss of the 5 batches 0.306 0.206 0.243 0.175 0.117 mean 0.210 s²

In the first epoch the loss falls from one batch to the next, because the weights are updated after each batch. Later the five batch losses still differ, between about 0.1 and 0.3 s², although the weights hardly move: each batch holds different samples with different noise. The loss of a batch is a noisy estimate of the loss of the whole training set, and so is its gradient. This is why a loss printed batch by batch jumps up and down, and why it is reported as a mean over the epoch.
In PyTorch (4.1) the same steps have these names: a DataLoader shuffles and cuts the batches, loss.backward() computes the gradient of the loss for every weight, and optimizer.step() updates the weights.
2.8 Other seeds, and the least-squares line¶
We wrap the loop of 2.6 in a function, then start it from three seeds. For one neuron and the squared error the loss has a single lowest point, so every seed arrives at the same weights. A network has many low points, and its result does depend on the seed (4.7).
def gradientDescent(x, y, learningRate, nEpochs, seed):
# The loop of 2.6: one update per epoch, on all the samples
rng = np.random.default_rng(seed)
w, b = rng.normal(0, 1), rng.normal(0, 1)
losses = []
for epoch in range(nEpochs):
error = w * x + b - y
loss = np.mean(error ** 2)
if not np.isfinite(loss) or loss > 1e12: # stop if the loss diverged
break
losses.append(loss)
w = w - learningRate * np.mean(2 * error * x)
b = b - learningRate * np.mean(2 * error)
return w, b, np.array(losses)
ols = LinearRegression().fit(x.reshape(-1, 1), y)
fig, ax = plt.subplots(figsize=(6.5, 4))
for s in (0, 1, 2):
ws, bs, losses = gradientDescent(x, y, 0.1, 60, seed=s)
ax.semilogy(losses, label=f'seed {s}: w = {ws:.3f}, b = {bs:.3f}')
ax.set_xlabel('Epoch')
ax.set_ylabel('Loss (s²)')
ax.set_title('Three seeds, one answer')
ax.legend()
print(f'Least squares (OLS): w = {ols.coef_[0]:.3f}, b = {ols.intercept_:.3f}')Least squares (OLS): w = 6.916, b = 14.794

3. How the learning rate changes training¶
The learning rate multiplies the gradient to give the size of each update. The grid below trains the same neuron from the same seed with four learning rates and plots the loss at each epoch.
learningRates = [0.001, 0.01, 0.1, 1.05]
fig, axes = plt.subplots(2, 2, figsize=(10, 7))
with np.errstate(over='ignore', invalid='ignore'):
for ax, lr in zip(axes.ravel(), learningRates):
_, _, losses = gradientDescent(x, y, lr, 200, seed=0)
ax.semilogy(losses, color='r', label=f'last loss = {losses[-1]:.3g} s²')
ax.set_xlabel('Epoch')
ax.set_ylabel('Loss (s²)')
ax.set_title(f'learning rate = {lr:g}')
ax.legend()
ax.grid(color='gray', linestyle='dashed', alpha=0.4)
fig.tight_layout()
Read the four panels. At the loss is still far from its lowest value after 200 epochs: the updates are too small. At it is close after 200 epochs (0.29 s²). At it gets there in about 30. At each update goes past the lowest point and lands further away than it started: the loss grows at every epoch and training diverges. Only the curve of the loss against the epoch shows which case you are in, so plot it every time you train.
3.1 Interactive explorer¶
Choose a learning rate, a number of epochs and a seed, then click Update to retrain and replot. Three things to try: a learning rate of 0.001 with 100 epochs (training has barely started), 0.1 with 100 epochs (it reaches the least-squares line), and 1.05 (it diverges).
Widgets do not run in the static rendered book: download and run this notebook in Jupyter to use it.
import ipywidgets as widgets
from IPython.display import display, clear_output
%matplotlib inlinestyle = {'description_width': '150px'}
learningRateSlider = widgets.FloatLogSlider(value=0.1, min=-3, max=0.25, step=0.05,
description='Learning rate:', style=style)
epochsDropdown = widgets.Dropdown(options=[1, 10, 100, 1000], value=100, description='Number of epochs:', style=style)
seedBox = widgets.BoundedIntText(value=0, min=0, max=9999, description='Seed (starting weights):', style=style)
updateBtn = widgets.Button(description="Update")
outputWidget = widgets.Output()
# Runs when the "Update" button is clicked, and once below so that a result shows at the start
def updateClick(_=None):
with outputWidget:
clear_output(wait=True)
with np.errstate(over='ignore', invalid='ignore'):
wFit, bFit, losses = gradientDescent(x, y, learningRateSlider.value, epochsDropdown.value, seedBox.value)
if len(losses) < epochsDropdown.value or losses[-1] > 1e6:
print(f'Diverged after {len(losses)} epochs: the learning rate is too large.')
return
print(f'{len(losses)} epochs: w = {wFit:.3f}, b = {bFit:.3f}, loss {losses[-1]:.4f} s². '
f'Least squares: w = {ols.coef_[0]:.3f}, b = {ols.intercept_:.3f}.')
fig, axes = plt.subplots(1, 2, figsize=(12, 4))
axes[0].scatter(x, y, s=12, color='k', label='training samples')
axes[0].plot(xLine, wFit * xLine + bFit, color='r', lw=2, label='gradient descent')
axes[0].plot(xLine, ols.predict(xLine.reshape(-1, 1)), color='b', ls='--', label='least squares')
axes[0].set_xlabel('x: standardized distance')
axes[0].set_ylabel('Travel time (s)')
axes[0].legend()
axes[1].semilogy(losses, color='r')
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('Loss (s²)')
display(fig)
plt.close(fig)
updateBtn.on_click(updateClick)
display(learningRateSlider, epochsDropdown, seedBox, updateBtn, outputWidget)
updateClick()4. The same loop for a classification: event or noise¶
Seismic detectors summarize short windows of a seismogram with a few features. The mlgeo_synth.detector_features table contains four such features per window: the STA/LTA ratio (sta_lta), the kurtosis of the waveform, the spectral centroid in Hz, and the dominant frequency in Hz. The observation is 1 for an earthquake window and 0 for a noise window, with balanced classes.
We use two features, sta_lta and spectral_centroid_hz. Events have impulsive arrivals (high STA/LTA) and more high-frequency energy (high spectral centroid) than background noise. The two clouds overlap, as they do for real detectors.
df = mlgeo_synth.detector_features(n=2000, event_fraction=0.5, seed=0)
print(df.head())
fig, ax = plt.subplots(figsize=(6, 4.5))
for lbl, name in [(0, 'noise'), (1, 'event')]:
part = df[df['label'] == lbl]
ax.scatter(part['sta_lta'], part['spectral_centroid_hz'], s=8, alpha=0.5, label=name)
ax.set_xlabel('STA/LTA')
ax.set_ylabel('Spectral centroid (Hz)')
ax.set_title('Detector features: all 2000 windows')
ax.legend(); sta_lta kurtosis spectral_centroid_hz dominant_freq_hz label
0 10.419133 22.113184 9.556484 7.786286 1
1 3.314406 2.773164 1.716694 1.009758 0
2 2.336543 4.639630 1.271397 0.251278 0
3 3.976867 13.591792 6.692700 4.682170 1
4 1.151811 3.131239 4.474578 1.426544 0

We keep 1,500 windows to train and 500 to test, and standardize each feature with the training windows only.
features = df[['sta_lta', 'spectral_centroid_hz']].to_numpy()
labels = df['label'].to_numpy()
trainX, testX = features[:1500], features[1500:]
trainY, testY = labels[:1500], labels[1500:]
# Standardize with the mean and standard deviation of the training windows only
mu, sd = trainX.mean(axis=0), trainX.std(axis=0)
trainX, testX = (trainX - mu) / sd, (testX - mu) / sd4.1 Sigmoid and log-loss¶
Three things change from section 2, and the loop stays the same.
Prediction. The neuron uses the sigmoid, so that its prediction is a probability between 0 and 1: with .
Loss of a sample. The cross-entropy, or log-loss, of 3.6: . It is near 0 when the probability agrees with the observation, and large when the neuron is confident and wrong.
Gradient. For the sigmoid and the log-loss, the chain rule of 3.6 simplifies to : again the error times the input.
The loss is still the mean of over the samples, its gradient is still the mean of the gradients of the samples, and the update is still .
Your turn (6): the sigmoid¶
Take the starting weights wTry and bTry drawn below. Compute yhatTry, the probability that this neuron gives for each training window: the weighted sum of each row of trainX, plus the bias, passed through the sigmoid.
Hint: 1 / (1 + np.exp(-(trainX @ wTry + bTry))).
rng = np.random.default_rng(seed)
wTry, bTry = rng.normal(0, 1, 2), rng.normal(0, 1) # random starting weights: one per feature, and a bias
yhatTry = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
yhatTry = 1 / (1 + np.exp(-(trainX @ wTry + bTry)))print(f'Starting weights {wTry.round(3)}, bias {bTry:.3f}: probabilities from {yhatTry.min():.3f} to {yhatTry.max():.3f}')Starting weights [ 0.126 -0.132], bias 0.640: probabilities from 0.474 to 0.839
rng = np.random.default_rng(seed)
w, b = rng.normal(0, 1, 2), rng.normal(0, 1) # random starting weights
learningRate, nEpochs = 2.0, 300
logLoss, lossTestAccuracy, lossPerSampleAt = [], [], {}
for epoch in range(nEpochs):
yhat = 1 / (1 + np.exp(-(trainX @ w + b))) # 1. predictions: a probability for each window
error = yhat - trainY # 2. errors: prediction minus observation
yc = np.clip(yhat, 1e-7, 1 - 1e-7) # (keeps the logarithm finite)
lossPerSample = -(trainY * np.log(yc) + (1 - trainY) * np.log(1 - yc)) # 3. loss of each sample ...
logLoss.append(lossPerSample.mean()) # ... and its mean
if epoch in (0, nEpochs - 1):
lossPerSampleAt[epoch] = lossPerSample
gradW = trainX.T @ error / len(trainY) # 4. gradient: mean over the samples of error times input
gradB = error.mean()
w = w - learningRate * gradW # 5. update
b = b - learningRate * gradB
lossTestAccuracy.append((((testX @ w + b) >= 0) == testY).mean())
if epoch in (0, 1, 5, 20, 100, nEpochs - 1):
print(f'epoch {epoch:3d}: loss {logLoss[-1]:.4f} test accuracy {lossTestAccuracy[-1]:.3f}')
last = np.sort(lossPerSampleAt[nEpochs - 1])[::-1]
print(f'Last epoch: {np.sum(last > 0.5)} of {len(last)} windows have a loss above 0.5; '
f'the 150 windows with the largest loss hold {100 * last[:150].sum() / last.sum():.0f}% of the total')
fig, axes = plt.subplots(1, 3, figsize=(15, 4))
axes[0].semilogy(logLoss, color='C3')
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Loss (mean log-loss)')
axes[0].set_title('Loss at each epoch')
bins = np.logspace(-4, 1.2, 40)
axes[1].hist(lossPerSampleAt[0], bins=bins, alpha=0.6, label=f'epoch 0: mean {logLoss[0]:.2f}')
axes[1].hist(lossPerSampleAt[nEpochs - 1], bins=bins, alpha=0.6, label=f'epoch {nEpochs - 1}: mean {logLoss[-1]:.2f}')
axes[1].set_xscale('log')
axes[1].set_xlabel('Loss of the sample')
axes[1].set_ylabel('Number of training windows')
axes[1].set_title('Loss of each of the 1,500 samples')
axes[1].legend()
for lbl, name in [(0, 'noise'), (1, 'event')]:
axes[2].scatter(trainX[trainY == lbl, 0], trainX[trainY == lbl, 1], s=5, alpha=0.4, label=name)
x1 = np.linspace(trainX[:, 0].min(), trainX[:, 0].max(), 50)
axes[2].plot(x1, -(w[0] * x1 + b) / w[1], 'k--', label='probability 0.5')
axes[2].set_ylim(trainX[:, 1].min() - 0.3, trainX[:, 1].max() + 0.3)
axes[2].set_xlabel('STA/LTA (standardized)')
axes[2].set_ylabel('Spectral centroid (standardized)')
axes[2].set_title('Training windows and the fitted boundary')
axes[2].legend()
fig.tight_layout()epoch 0: loss 0.7569 test accuracy 0.916
epoch 1: loss 0.3794 test accuracy 0.900
epoch 5: loss 0.2286 test accuracy 0.890
epoch 20: loss 0.1738 test accuracy 0.902
epoch 100: loss 0.1348 test accuracy 0.926
epoch 299: loss 0.1220 test accuracy 0.938
Last epoch: 93 of 1500 windows have a loss above 0.5; the 150 windows with the largest loss hold 80% of the total

The loss goes down at each epoch and flattens. The middle panel shows how the loss is spread over the samples: after training most windows have a loss below 0.1, and a small number, those in the band where the two clouds overlap, keep a loss above 0.5. The line printed above gives their count, and the share of the total loss held by the tenth of the windows with the largest loss.
A neuron with a sigmoid, trained on the log-loss, is logistic regression. It returns a probability, so the threshold, the ROC curve and the calibration of lecture 16 all apply.
4.2 The perceptron rule of 1958¶
Rosenblatt (1958) trained the same neuron before gradient descent was used for it. His neuron has the step activation: the prediction is 0 or 1. The step is flat on both sides, so it has no gradient to follow. His rule takes the samples one at a time and updates
This has the form of the gradient update of 4.1 for a batch of one sample, with a prediction of 0 or 1 in place of a probability. The error is 0 for a window that is classified correctly (no update), -1 for an event predicted as noise, and +1 for a noise window predicted as an event.
The rule stops when one epoch passes with all errors equal to zero. That can only happen if the data are linearly separable: some line classifies every training sample correctly. To see it stop, we select a subset where this holds: we compute a score, sta_lta + spectral_centroid_hz, and drop the windows in the overlap band.
score = df['sta_lta'] + df['spectral_centroid_hz']
keep = ((df['label'] == 0) & (score < 5)) | ((df['label'] == 1) & (score > 9))
subset = df[keep]
# Balance the classes: 300 windows of each
rng = np.random.default_rng(42)
noise_idx = rng.choice(subset.index[subset['label'] == 0], 300, replace=False)
event_idx = rng.choice(subset.index[subset['label'] == 1], 300, replace=False)
subset = subset.loc[np.concatenate([noise_idx, event_idx])]
simpleInputs = subset[['sta_lta', 'spectral_centroid_hz']].to_numpy()
simpleOutputs = subset['label'].to_numpy()
# Shuffle the samples
p = rng.permutation(len(simpleInputs))
simpleInputs = simpleInputs[p, :]
simpleOutputs = simpleOutputs[p]
fig, ax = plt.subplots(figsize=(6, 4.5))
for lbl, name in [(0, 'noise'), (1, 'event')]:
m = simpleOutputs == lbl
ax.scatter(simpleInputs[m, 0], simpleInputs[m, 1], s=8, alpha=0.6, label=name)
ax.set_xlabel('STA/LTA')
ax.set_ylabel('Spectral centroid (Hz)')
ax.set_title('Balanced, near-linearly-separable subset (600 windows)')
ax.legend();
percept = simplePerceptron(nInputs=2, activation='step', seed=0) # random starting weights
learningRate = 0.1
maxEpochs = 200
errorsPerEpoch = []
for epoch in range(maxEpochs):
nonzeroErrors = 0
for i in range(len(simpleInputs)):
thisInput = simpleInputs[i:i + 1, :]
yhat_i = percept.predict(thisInput)[0] # prediction: 0 or 1
error = yhat_i - simpleOutputs[i] # error: -1, 0 or +1
if error != 0:
nonzeroErrors += 1
percept.setWs(percept.w - learningRate * error * thisInput[0],
percept.b_w - learningRate * error)
errorsPerEpoch.append(nonzeroErrors)
if nonzeroErrors == 0:
break
accuracy = (percept.predict(simpleInputs) == simpleOutputs).mean()
print(f'Stopped after {len(errorsPerEpoch)} epochs; nonzero errors per epoch: {errorsPerEpoch}')
print(f'Weights: {percept.w}, bias: {percept.b_w:.3f}, training accuracy: {accuracy:.3f}')Stopped after 2 epochs; nonzero errors per epoch: [48, 0]
Weights: [0.2780824 0.29210018], bias: -2.160, training accuracy: 1.000
The rule stops after a few epochs and classifies every training sample correctly. With two features, the decision boundary is the line , which we can draw.
fig, ax = plt.subplots(figsize=(6, 4.5))
for lbl, name in [(0, 'noise'), (1, 'event')]:
m = simpleOutputs == lbl
ax.scatter(simpleInputs[m, 0], simpleInputs[m, 1], s=8, alpha=0.6, label=name)
# Decision boundary: w1*x1 + w2*x2 + b = 0 -> x2 = -(w1*x1 + b) / w2
x1 = np.linspace(simpleInputs[:, 0].min(), simpleInputs[:, 0].max(), 100)
x2 = -(percept.w[0] * x1 + percept.b_w) / percept.w[1]
ax.plot(x1, x2, 'k--', label='decision boundary')
ax.set_xlabel('STA/LTA')
ax.set_ylabel('Spectral centroid (Hz)')
ax.set_ylim(-0.5, simpleInputs[:, 1].max() + 0.5)
ax.set_title('Perceptron decision boundary')
ax.legend();
Exercise. Swap spectral_centroid_hz for kurtosis in the subset-selection cell (keep the same score-based filter on the original features). Does the rule still stop within 200 epochs? Why or why not?
Solution
It usually does not stop. The score filter removed the overlap in the (STA/LTA, spectral centroid) plane, but the same windows can still overlap in the (STA/LTA, kurtosis) plane. When the classes overlap, no line classifies every sample correctly, so some errors are nonzero in every epoch and errorsPerEpoch never reaches zero. To make the rule stop you would need to select a subset that is separable in the new feature pair.
Now the rule on all the windows of 4.1, where the classes overlap, for 300 epochs.
rng = np.random.default_rng(seed)
w, b = rng.normal(0, 1, 2), rng.normal(0, 1) # random starting weights
ruleErrors, ruleTestAccuracy = [], []
for epoch in range(300):
nonzeroErrors = 0
for i in range(len(trainX)):
yhat_i = float(trainX[i] @ w + b >= 0) # step activation: 0 or 1
error = yhat_i - trainY[i] # -1, 0 or +1
if error != 0:
nonzeroErrors += 1
w = w - error * trainX[i]
b = b - error
ruleErrors.append(nonzeroErrors)
ruleTestAccuracy.append(((testX @ w + b >= 0) == testY).mean())
print(f'Nonzero errors in the last 5 epochs: {ruleErrors[-5:]} of {len(trainX)} windows')
print(f'Test accuracy over the last 100 epochs: {min(ruleTestAccuracy[-100:]):.3f} to {max(ruleTestAccuracy[-100:]):.3f}')
print(f'Gradient descent on the log-loss (4.1), last epoch: {lossTestAccuracy[-1]:.3f}')
fig, axes = plt.subplots(1, 2, figsize=(11, 4))
axes[0].plot(ruleErrors, color='C3')
axes[0].set_xlabel('Epoch')
axes[0].set_ylabel('Windows with a nonzero error')
axes[0].set_title('Perceptron rule on overlapping classes')
axes[0].set_ylim(0, None)
axes[1].plot(ruleTestAccuracy, color='C3', label='perceptron rule')
axes[1].plot(lossTestAccuracy, color='C2', lw=2.5, label='gradient descent on the log-loss')
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('Accuracy on the 500 test windows')
axes[1].set_title('Test accuracy')
axes[1].legend()
fig.tight_layout()Nonzero errors in the last 5 epochs: [96, 102, 96, 98, 96] of 1500 windows
Test accuracy over the last 100 epochs: 0.914 to 0.940
Gradient descent on the log-loss (4.1), last epoch: 0.938

The number of nonzero errors never reaches zero, because no line classifies every window. The rule keeps updating, so the weights and the test accuracy depend on the epoch at which we stop. Gradient descent on the log-loss has a loss to lower, and it settles.
Why the step cannot settle, and why it matters for networks. Training needs a number that says how wrong the neuron is, and the slope of that number for each weight: the gradient, which gives the direction and size of the update. With the step, the prediction is 0 or 1, and the only measure of how wrong the neuron is, is the count of windows with a nonzero error. That count is flat as a weight changes, then jumps by one when the line crosses a window: its slope is zero almost everywhere, so it gives no direction. The rule moves the weights by a fixed amount for each wrong window instead, and with overlapping classes some window is always wrong. With the sigmoid, the error varies smoothly, the mean log-loss has a slope at every point, and the slope shrinks to zero at its lowest point, so the updates shrink and training settles.
In a network, the gradient for a hidden weight is computed by the chain rule, which multiplies by the slope of each activation on the way back from the output. A step activation has slope zero, so no gradient would reach the hidden layer. This is why networks use smooth activations (sigmoid, tanh, ReLU). The other limit of one neuron, a straight-line boundary, does not depend on the activation; hidden layers remove it (4.1).
5. The weights as a template¶
A neuron can also take the record itself as input: one input per sample of the waveform, so one weight per sample. Template matching (lecture 1, section 2.9) computes this same weighted sum with the waveform of a known earthquake as the weights.
We build a case where that works: one source 20 km from the station, recorded many times in new noise, with a signal-to-noise ratio between 1.5 and 6. Each window is 6 s long (600 samples at 100 Hz), standardized, with the P wave 0.83 s after the start.

fs = 100.0
i0, i1 = int(7.5 * fs), int(13.5 * fs) # 6 s window; P arrives at 8.33 s, S at 10.71 s
def makeWindow(event, snr, seed, shift=0):
# One standardized window. shift > 0 moves the arrival later in the window, in samples.
if event:
_, trace, _ = synthetic_seismogram(magnitude=2.0, distance_km=20.0, snr=snr, seed=seed)
else:
_, trace, _ = synthetic_seismogram(magnitude=-10, distance_km=20.0, snr=1e-12, seed=seed)
win = trace[i0 - shift:i1 - shift]
return (win - win.mean()) / win.std()
def makeWindows(n, seed, shift=0):
# n windows, alternating noise (label 0) and event (label 1)
rng = np.random.default_rng(seed)
X, t = [], []
for k in range(n):
snr = float(np.exp(rng.uniform(np.log(1.5), np.log(6.0))))
X.append(makeWindow(k % 2, snr, int(rng.integers(2**31)), shift))
t.append(k % 2)
return np.array(X), np.array(t)
# The template: the same event with no noise
_, clean, _ = synthetic_seismogram(magnitude=2.0, distance_km=20.0, snr=1e9, seed=0)
template = clean[i0:i1]
template = (template - template.mean()) / template.std()
waveTrainX, waveTrainY = makeWindows(800, seed=10)
waveTestX, waveTestY = makeWindows(400, seed=20)
tWin = np.arange(i1 - i0) / fs
fig, axes = plt.subplots(3, 1, figsize=(9, 5.5), sharex=True)
axes[0].plot(tWin, template, color='k'); axes[0].set_title('Template: the event with no noise (P, then S)')
axes[1].plot(tWin, waveTestX[1], color='C1'); axes[1].set_title('An event window')
axes[2].plot(tWin, waveTestX[0], color='C0'); axes[2].set_title('A noise window')
axes[2].set_xlabel('Time in the window (s)')
fig.tight_layout()
Your turn (7): template matching as a weighted sum¶
Compute templateScore, the score of every test window when the weights are the template: the sum over samples of window times template, divided by the number of samples. For standardized windows this is the correlation coefficient at zero lag.
Hint: waveTestX @ template / len(template).
templateScore = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
templateScore = waveTestX @ template / len(template)# Threshold: the score exceeded by 1% of the noise windows of the training set
threshold = np.quantile((waveTrainX @ template / len(template))[waveTrainY == 0], 0.99)
templateAccuracy = ((templateScore > threshold) == waveTestY).mean()
print(f'Template matching: threshold {threshold:.3f}, test accuracy {templateAccuracy:.4f}')Template matching: threshold 0.161, test accuracy 0.9975
Now give a neuron the same 600 inputs and only the observations (event or noise). We fit it with scikit-learn’s logistic regression, which lowers the same log-loss as section 4.1 with a faster method than plain gradient descent, and with a penalty that keeps the weights small (C=0.001; a smaller C is a stronger penalty). scikit-learn starts this fit from weights of zero, not from random weights. For one neuron that does not change the result: its loss has a single lowest point, so every start reaches the same weights (section 2.8). For a network it would, which is why the networks of 4.1 start from random weights.
neuron = LogisticRegression(C=0.001, max_iter=5000).fit(waveTrainX, waveTrainY)
weights = neuron.coef_[0]
fig, axes = plt.subplots(2, 1, figsize=(9, 4.5), sharex=True)
axes[0].plot(tWin, template, color='k'); axes[0].set_title('Template: the event with no noise')
axes[1].plot(tWin, weights, color='C2'); axes[1].set_title('Weights of the neuron, fitted from 800 labeled windows')
axes[1].set_xlabel('Time in the window (s): one weight per sample')
fig.tight_layout()
print(f'Correlation between the weights and the template: {np.corrcoef(weights, template)[0, 1]:.3f}')
print(f'Test accuracy of the neuron: {neuron.score(waveTestX, waveTestY):.4f} (template matching: {templateAccuracy:.4f})')Correlation between the weights and the template: 0.986
Test accuracy of the neuron: 0.9975 (template matching: 0.9975)

The neuron was never given the waveform of the event; it recovered it from the labeled windows. A neuron’s weights are the input pattern it responds to most strongly.
Move the arrival. Each weight multiplies one position in the window. makeWindows(400, seed=30, shift=10) returns 400 new windows in which the event arrives 10 samples (0.1 s) later. The cell below computes the fraction of the event windows that the neuron still classifies as events.
shiftedX, shiftedY = makeWindows(400, seed=30, shift=10)
shiftedDetected = neuron.predict(shiftedX)[shiftedY == 1].mean()
print(f'Events detected with the arrival at its training position: {neuron.predict(waveTestX)[waveTestY == 1].mean():.3f}')
print(f'Events detected with the arrival 0.1 s later: {shiftedDetected:.3f}')Events detected with the arrival at its training position: 0.995
Events detected with the arrival 0.1 s later: 0.000
Exercise. Why does a shift of 0.1 s remove the detections, when the windows still contain the same event? What does template matching do that this neuron does not?
Solution
The S wave of this source oscillates at 3 Hz and the P wave at 5 Hz, so 0.1 s is a third to a half of a period: the peaks of the shifted waveform now meet weights of the opposite sign, and the weighted sum falls below zero. Template matching computes the weighted sum at every lag (the cross-correlation), so it finds the event wherever it sits in the record. A neuron has one weight per input position and computes one sum. Sliding one small set of weights along the record is the idea of the convolutional layer in 4.3.
6. A network: the errors go back through the layers (backpropagation)¶
One neuron draws a straight line. To fit a curve, we put a hidden layer between the input and the output: several neurons that all read the input, each with its own weights, whose outputs are summed by an output neuron. Training does not change: predictions, errors, loss, gradient, update. The only new question is how to get the gradient for the weights of the hidden layer, which do not touch the output directly. The answer is backpropagation: the error at the output is sent back through the network, along the same connections, and each hidden neuron receives its share of it.
The data (synthetic, the example of the lecture, Part 3): temperature against depth in the upper ocean, with a mixed layer, a seasonal thermocline near 60 m and a main thermocline near 300 m. 60 samples between 0 and 600 m, with 0.3 °C of noise. The input is the depth and the observation the temperature, both standardized.
The network: 1 input, 3 hidden neurons with the tanh activation, 1 output with no activation.
That is 10 weights: 3 input weights and 3 biases in the hidden layer, 3 output weights and 1 bias . All start as random numbers (seed 2).

def profile(depth):
# Synthetic temperature profile (°C): 4 °C deep water, two thermoclines
return 4 + 6 / (1 + np.exp((depth - 60) / 15)) + 8 / (1 + np.exp((depth - 300) / 50))
rng = np.random.default_rng(3)
depthOcean = np.sort(rng.uniform(0, 600, 60))
tempOcean = profile(depthOcean) + rng.normal(0, 0.3, 60)
tMean, tStd = tempOcean.mean(), tempOcean.std()
xOcean = (depthOcean - 300) / 300 # standardized input
yOcean = (tempOcean - tMean) / tStd # standardized observation
# Random starting weights for all 10 weights, seed 2
rng = np.random.default_rng(2)
W1, b1 = rng.normal(0, 1.0, 3), rng.normal(0, 0.5, 3) # hidden layer
W2, b2 = rng.normal(0, 0.5, 3), rng.normal(0, 0.5) # output layer
print('W1', W1.round(2), ' b1', b1.round(2), ' W2', W2.round(2), ' b2', round(b2, 2))
fig, ax = plt.subplots(figsize=(4, 5))
ax.scatter(tempOcean, depthOcean, s=14, color='C0')
ax.set_ylim(600, 0)
ax.set_xlabel('Temperature (°C)')
ax.set_ylabel('Depth (m)')
ax.set_title('Synthetic ocean profile');W1 [ 0.19 -0.52 -0.41] b1 [-1.22 0.9 0.57] W2 [-0.16 0.39 0.14] b2 -0.28

6.1 Forward pass: predictions and errors¶
The forward pass computes the outputs of the hidden neurons, then the prediction, for every sample. The error and the loss are as in section 2: , and the loss is the mean of .

H = np.tanh(np.outer(xOcean, W1) + b1) # outputs of the 3 hidden neurons: one column per neuron, one row per sample
yhat = H @ W2 + b2 # predictions
error = yhat - yOcean # errors: prediction minus observation
loss = np.mean(error ** 2)
print(f'Loss with the starting weights: {loss:.3f}')
i = np.argmin(np.abs(depthOcean - 150)) # follow one sample, near 150 m
print(f'Sample at {depthOcean[i]:.0f} m: hidden outputs {H[i].round(2)}, prediction {yhat[i]:.2f}, '
f'observation {yOcean[i]:.2f}, error {error[i]:+.2f} ({error[i] * tStd:+.1f} °C)')Loss with the starting weights: 0.893
Sample at 142 m: hidden outputs [-0.87 0.83 0.66], prediction 0.28, observation 0.79, error -0.51 (-2.0 °C)
6.2 Backward pass: the error goes back¶
We need the gradient of the loss for each of the 10 weights. The chain rule gives it layer by layer, starting from the output. For one sample , with loss :
Output layer. The output neuron is the neuron of section 2, with the hidden outputs as its inputs. Its gradients are again the error times the input:
The error sent back to hidden neuron . How much does the loss change if the hidden neuron’s score changes a little? Three factors, multiplied:
the error at the output: no error, nothing to correct;
the weight that connects neuron to the output: a neuron with a small output weight contributed little to the prediction, so it receives little of the error;
the slope of its activation (the derivative of tanh is ): if the neuron sits on a flat part of tanh, changing its score barely changes its output, so it receives little of the error.
Hidden layer. With its share of the error, each hidden neuron is again a single neuron: its gradients are its error times its input.
As in section 2, the gradient of the loss is the mean of these over the samples of the batch.
Your turn (8): the error sent back to the hidden layer¶
gradW2 and gradB2 are written for you. Compute backError, an array with one row per sample and one column per hidden neuron: 2 * error (one value per sample) times W2 (one value per neuron) times the slope of tanh, 1 - H ** 2.
Hint: 2 * error[:, None] * W2 * (1 - H ** 2). The [:, None] turns the errors into a column, so that each row is multiplied by the error of its sample.

gradW2 = np.mean(2 * error[:, None] * H, axis=0) # output weights: error times hidden output, mean over samples
gradB2 = np.mean(2 * error)
backError = None # replace None with your expressionAnswer below (click to open it).
Notebook Cell
backError = 2 * error[:, None] * W2 * (1 - H ** 2)gradW1 = np.mean(backError * xOcean[:, None], axis=0) # hidden weights: their error times their input
gradB1 = np.mean(backError, axis=0)
print(f'Sample at {depthOcean[i]:.0f} m: error {error[i]:+.3f}, error sent back to the 3 hidden neurons {backError[i].round(3)}')
print('Gradient of the loss (mean over the 60 samples):')
print(' output weights W2', gradW2.round(3), ' output bias b2', round(gradB2, 3))
print(' input weights W1', gradW1.round(3), ' hidden biases b1', gradB1.round(3))Sample at 142 m: error -0.510, error sent back to the 3 hidden neurons [ 0.041 -0.126 -0.081]
Gradient of the loss (mean over the 60 samples):
output weights W2 [-0.275 0.034 -0.083] output bias b2 0.391
input weights W1 [-0.046 0.188 0.096] hidden biases b1 [-0.033 0.202 0.08 ]
Backpropagation gives the same gradient as changing the weight a little and measuring the loss, but it gets all 10 gradients from one forward and one backward pass. A network with a million weights needs the same two passes.
The error reaches a hidden neuron only through the slope of its activation. With the step function of section 4.2 that slope is zero, so no error would reach the hidden layer and its weights would never change. This is why networks use smooth activations such as tanh, the sigmoid and ReLU.
6.3 Training: the same loop, with a backward pass¶
Each epoch: forward pass, errors, loss, backward pass, update of all 10 weights against their gradients.
rng = np.random.default_rng(2)
W1, b1 = rng.normal(0, 1.0, 3), rng.normal(0, 0.5, 3) # random starting weights, seed 2
W2, b2 = rng.normal(0, 0.5, 3), rng.normal(0, 0.5)
learningRate, nEpochs = 0.3, 20000
networkLoss = []
for epoch in range(nEpochs):
H = np.tanh(np.outer(xOcean, W1) + b1) # 1. forward pass
error = H @ W2 + b2 - yOcean # 2. errors
networkLoss.append(np.mean(error ** 2)) # 3. loss: mean over the samples
backError = 2 * error[:, None] * W2 * (1 - H ** 2) # 4. backward pass: error sent back to the hidden layer
gradW2, gradB2 = np.mean(2 * error[:, None] * H, axis=0), np.mean(2 * error)
gradW1, gradB1 = np.mean(backError * xOcean[:, None], axis=0), np.mean(backError, axis=0)
W2, b2 = W2 - learningRate * gradW2, b2 - learningRate * gradB2 # 5. update every weight
W1, b1 = W1 - learningRate * gradW1, b1 - learningRate * gradB1
if epoch in (0, 5, 100, 1000, 5000, nEpochs - 1):
print(f'epoch {epoch:5d}: loss {networkLoss[-1]:.4f}, root of the loss {np.sqrt(networkLoss[-1]) * tStd:.2f} °C')
depthGrid = np.linspace(0, 600, 300)
xGrid = (depthGrid - 300) / 300
fit = (np.tanh(np.outer(xGrid, W1) + b1) @ W2 + b2) * tStd + tMean
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5))
axes[0].scatter(tempOcean, depthOcean, s=14, color='C0', label='observations')
axes[0].plot(fit, depthGrid, color='k', lw=2, label='network after training')
axes[0].set_ylim(600, 0)
axes[0].set_xlabel('Temperature (°C)')
axes[0].set_ylabel('Depth (m)')
axes[0].legend()
axes[1].loglog(np.arange(1, nEpochs + 1), np.sqrt(networkLoss) * tStd, color='C3')
axes[1].axhline(0.3, color='gray', ls=':')
axes[1].set_xlabel('Epoch')
axes[1].set_ylabel('Root of the loss (°C)')
axes[1].set_title('Loss at each epoch')
fig.tight_layout()epoch 0: loss 0.8930, root of the loss 3.76 °C
epoch 5: loss 0.4588, root of the loss 2.69 °C
epoch 100: loss 0.0345, root of the loss 0.74 °C
epoch 1000: loss 0.0290, root of the loss 0.68 °C
epoch 5000: loss 0.0087, root of the loss 0.37 °C
epoch 19999: loss 0.0063, root of the loss 0.31 °C

The loss falls fast, stays on a plateau for about a thousand epochs while one hidden neuron finds its place, then falls to the noise level (0.3 °C). In PyTorch (4.1) the same steps are written outputs = model(inputs) (forward pass), loss = criterion(outputs, targets) (the mean loss over the batch), loss.backward() (the backward pass: every gradient, by the chain rule, as above) and optimizer.step() (the update).
Summary¶
A perceptron is one neuron: a weighted sum plus a bias, passed through an activation function.
Its weights start from random numbers drawn with a seed, and are found by gradient descent: predictions, errors (prediction minus observation), the loss of each sample, the mean loss over the batch, the gradient of that mean for each weight, the update .
The loss differs from sample to sample and from batch to batch. Its mean over an epoch, plotted against the epoch, shows whether training works: going down, flat, or diverging.
The gradient is the slope of the loss for each weight. It gives the direction and the size of the update, and it goes to zero at the lowest point of the loss.
The learning rate sets the size of the updates: too small and training is slow, too large and the loss diverges.
With a sigmoid and the log-loss, the same loop classifies events and noise: this is logistic regression. The perceptron rule of 1958 has the same form with a step activation, and stops only when a line separates the classes.
A network with a hidden layer is trained by the same loop. Backpropagation gets the gradient of every weight: the error at the output is sent back along each connection, multiplied by the weight of the connection and the slope of the activation, and the gradient of a weight is the error at its end times the value at its start.
With the samples of a waveform as inputs, the fitted weights reproduce the waveform of the event: the neuron learns a template. Its weights are tied to positions in the window, so it loses an arrival that moves by 0.1 s.
Next: 4.1 Neural Networks stacks neurons into layers and trains them with this same loop, written in PyTorch. 4.3 slides a small set of weights along the record, so that a pattern is found wherever it occurs.