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

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

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.

  1. Build a neuron from scratch with NumPy.

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

  3. Change the learning rate.

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

  5. Give the neuron a waveform as input and compare its weights with a template.

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

SymbolNameIn the code
xix_iinput of sample iix
yiy_iobservation for sample iiy
y^i\hat{y}_iprediction of the neuron for sample iiyhat
ei=y^i−yie_i = \hat{y}_i - y_ierror: prediction minus observationerror
ww, bbweight and biasw, b
Li\mathcal{L}_iloss of sample iilossPerSample
L\mathcal{L}loss: the mean of Li\mathcal{L}_i over the samples of a batchloss
∂L/∂w\partial \mathcal{L} / \partial w, ∂L/∂b\partial \mathcal{L} / \partial bgradient of the lossgradW, gradB
α\alphalearning ratelearningRate

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.

1. A neuron from scratch

A neuron with inputs x1,…,xpx_1, \dots, x_p, weights w1,…,wpw_1, \dots, w_p and bias bb computes the prediction

y^=ϕ(∑jwjxj+b),\hat{y} = \phi\left(\sum_j w_j x_j + b\right),

where ϕ\phi 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.

One neuron: each input times its weight, added up with a bias, then an activation (lecture 21)The same weighted sum with three activations gives three models: linear regression, logistic regression, the threshold unit (lecture 21)

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.

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 vv, the travel time grows with the distance dd to the epicenter as t=t0+d/vt = t_0 + d / v: a line, whose slope is the slowness 1/v1/v.

The table below is synthetic (written in the next cell): a velocity of 6 km/s, a delay t0t_0 of 1 s, and 0.5 s of noise on each pick. Each station is one sample. The observation yiy_i is the travel time in seconds. The input xix_i is the distance, standardized with the mean and the standard deviation of the training samples.

The model. One neuron with no activation: y^i=wxi+b\hat{y}_i = w x_i + b.

Training means finding the ww and bb for which the predictions y^i\hat{y}_i are closest to the observations yiy_i. 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.

<Figure size 650x400 with 1 Axes>

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 ww and bb 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: starting weight w = 0.126, starting bias b = -0.132
<Figure size 650x400 with 1 Axes>

2.2 Predictions and errors

With the current weights the neuron makes a prediction for each sample, y^i=wxi+b\hat{y}_i = w x_i + b. The error of sample ii is the difference between the prediction and the observation:

ei=y^i−yi.e_i = \hat{y}_i - y_i .

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.

Answer below (click to open it).

Notebook Cell
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
<Figure size 650x400 with 1 Axes>

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,

Li=ei2=(y^i−yi)2,\mathcal{L}_i = e_i^2 = (\hat{y}_i - y_i)^2 ,

in s² here. The loss of a batch of nn samples is the mean of the losses of its samples (the mean squared error):

L=1n∑i=1nLi.\mathcal{L} = \frac{1}{n} \sum_{i=1}^{n} \mathcal{L}_i .

For now the batch is the whole training set, n=80n = 80.

Your turn (2): the mean loss

lossPerSample holds the 80 values Li\mathcal{L}_i. Compute loss, their mean.

Hint: lossPerSample.mean().

Answer below (click to open it).

Notebook Cell
Loss per sample: from 3.8 to 641.6 s². Mean (the loss): 269.1 s²
<Figure size 800x380 with 1 Axes>

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:

dCdA=dCdB×dBdA.\frac{dC}{dA} = \frac{dC}{dB} \times \frac{dB}{dA} .

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:

dvdz=dvdT×dTdz=(−0.0005)×25=−0.0125 km/s per km.\frac{dv}{dz} = \frac{dv}{dT} \times \frac{dT}{dz} = (-0.0005) \times 25 = -0.0125 \text{ km/s per km}.

The neuron. The weight changes the prediction, y^i=wxi+b\hat{y}_i = w x_i + b, and the prediction changes the loss of the sample, Li=(y^i−yi)2\mathcal{L}_i = (\hat{y}_i - y_i)^2. Two links:

∂Li∂w=∂Li∂y^i⏟2 ei×∂y^i∂w⏟xi=2 ei xi.\frac{\partial \mathcal{L}_i}{\partial w} = \underbrace{\frac{\partial \mathcal{L}_i}{\partial \hat{y}_i}}_{2\, e_i} \times \underbrace{\frac{\partial \hat{y}_i}{\partial w}}_{x_i} = 2\, e_i\, x_i .

The input xix_i is the link from the weight to the prediction: raising ww by a small amount raises the prediction by xix_i 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.

The chain rule: when A changes B and B changes C, the change of C with A is the product of the two links (lecture 21)
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: ∂L/∂w\partial \mathcal{L} / \partial w is positive if the loss increases when ww increases, and negative if the loss decreases when ww increases.

For one sample, with Li=(wxi+b−yi)2\mathcal{L}_i = (w x_i + b - y_i)^2, the chain rule gives

∂Li∂w=2 ei xi,∂Li∂b=2 ei.\frac{\partial \mathcal{L}_i}{\partial w} = 2\, e_i\, x_i , \qquad \frac{\partial \mathcal{L}_i}{\partial b} = 2\, e_i .

Each sample has its own gradient: its error times its input. The loss is the mean of the Li\mathcal{L}_i, so its gradient is the mean of the gradients of the samples:

∂L∂w=1n∑i=1n2 ei xi,∂L∂b=1n∑i=1n2 ei.\frac{\partial \mathcal{L}}{\partial w} = \frac{1}{n} \sum_{i=1}^{n} 2\, e_i\, x_i , \qquad \frac{\partial \mathcal{L}}{\partial b} = \frac{1}{n} \sum_{i=1}^{n} 2\, e_i .

There is one gradient value for each weight: here two numbers, one for ww and one for bb.

Your turn (3): the gradient for the bias

gradW is written for you. Compute gradB, the mean over the samples of 2ei2 e_i.

Hint: np.mean(2 * error).

Answer below (click to open it).

Notebook Cell
Gradient of the loss: -13.58 for the weight, -29.85 for the bias
<Figure size 1200x400 with 2 Axes>

Left: the gradients of the samples differ in size, and in sign on either side of the mean distance (x=0x = 0); 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 ww lowers the loss.

The same gradient for any activation. For a neuron with activation ϕ\phi, the score is zi=∑jwjxij+bz_i = \sum_j w_j x_{ij} + b and the prediction y^i=ϕ(zi)\hat{y}_i = \phi(z_i). The chain rule gives, for one sample,

∂Li∂wj=∂Li∂y^i⏟error part×ϕ′(zi)⏟slope of the activation×xij⏟input,\frac{\partial \mathcal{L}_i}{\partial w_j} = \underbrace{\frac{\partial \mathcal{L}_i}{\partial \hat{y}_i}}_{\text{error part}} \times \underbrace{\phi'(z_i)}_{\text{slope of the activation}} \times \underbrace{x_{ij}}_{\text{input}} ,

and the gradient of the loss is the mean of this over the samples of the batch.

ActivationLoss of a sampleSlope ϕ′(z)\phi'(z)Gradient for one sample
none (this section)squared error ei2e_i^212 ei xij2\, e_i\, x_{ij}: error × input
sigmoid (section 4.1)log-lossy^(1−y^)\hat{y}(1-\hat{y})y^i−yiy^i(1−y^i)×y^i(1−y^i)×xij=(y^i−yi) xij\frac{\hat{y}_i - y_i}{\hat{y}_i(1-\hat{y}_i)} \times \hat{y}_i(1-\hat{y}_i) \times x_{ij} = (\hat{y}_i - y_i)\, x_{ij}: error × input
step (section 4.2)any0 (undefined at z=0z = 0)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:

w(k+1)=w(k)−α∂L∂w,b(k+1)=b(k)−α∂L∂b,w^{(k+1)} = w^{(k)} - \alpha \frac{\partial \mathcal{L}}{\partial w} , \qquad b^{(k+1)} = b^{(k)} - \alpha \frac{\partial \mathcal{L}}{\partial b} ,

where α\alpha is the learning rate and kk 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 α\alpha 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 α=0.1\alpha = 0.1:

value nowgradient of the losschange: −α×-\alpha \times gradientvalue after the update
weight ww0.126−13.58−0.1 × (−13.58) = +1.3581.484
bias bb−0.132−29.85−0.1 × (−29.85) = +2.9852.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.

Answer below (click to open it).

Notebook Cell
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 −α×-\alpha \times 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²).

<Figure size 1300x450 with 2 Axes>

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.

epoch  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
<Figure size 1400x400 with 3 Axes>
<Figure size 1300x400 with 2 Axes>

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

  1. Shuffle the training samples.

  2. Cut them into batches, here of 16 samples: 80 / 16 = 5 batches.

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

Answer below (click to open it).

Notebook Cell
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²
<Figure size 700x400 with 1 Axes>

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

Least squares (OLS): w = 6.916, b = 14.794
<Figure size 650x400 with 1 Axes>

3. How the learning rate changes training

The learning rate α\alpha 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.

<Figure size 1000x700 with 4 Axes>

Read the four panels. At α=0.001\alpha = 0.001 the loss is still far from its lowest value after 200 epochs: the updates are too small. At α=0.01\alpha = 0.01 it is close after 200 epochs (0.29 s²). At α=0.1\alpha = 0.1 it gets there in about 30. At α=1.05\alpha = 1.05 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.

Loading...
Loading...
Loading...
Loading...
Loading...

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

     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
<Figure size 600x450 with 1 Axes>

We keep 1,500 windows to train and 500 to test, and standardize each feature with the training windows only.

4.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: y^i=1/(1+e−zi)\hat{y}_i = 1 / (1 + e^{-z_i}) with zi=∑jwjxij+bz_i = \sum_j w_j x_{ij} + b.

  • Loss of a sample. The cross-entropy, or log-loss, of 3.6: Li=−(yilog⁡y^i+(1−yi)log⁡(1−y^i))\mathcal{L}_i = - \left( y_i \log \hat{y}_i + (1 - y_i) \log (1 - \hat{y}_i) \right). 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 ∂Li/∂wj=(y^i−yi) xij\partial \mathcal{L}_i / \partial w_j = (\hat{y}_i - y_i)\, x_{ij}: again the error times the input.

The loss is still the mean of Li\mathcal{L}_i over the samples, its gradient is still the mean of the gradients of the samples, and the update is still wj−α ∂L/∂wjw_j - \alpha\, \partial \mathcal{L} / \partial w_j.

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

Answer below (click to open it).

Notebook Cell
Starting weights [ 0.126 -0.132], bias 0.640: probabilities from 0.474 to 0.839
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
<Figure size 1500x400 with 3 Axes>

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 y^i\hat{y}_i 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

wj←wj−α (y^i−yi) xij,b←b−α (y^i−yi).w_j \leftarrow w_j - \alpha\, (\hat{y}_i - y_i)\, x_{ij} , \qquad b \leftarrow b - \alpha\, (\hat{y}_i - y_i) .

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 y^i−yi\hat{y}_i - y_i 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.

<Figure size 600x450 with 1 Axes>
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 w1x1+w2x2+b=0w_1 x_1 + w_2 x_2 + b = 0, which we can draw.

<Figure size 600x450 with 1 Axes>

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?

Now the rule on all the windows of 4.1, where the classes overlap, for 300 epochs.

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
<Figure size 1100x400 with 2 Axes>

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 y^i−yi\hat{y}_i - y_i 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.

Template matching as a weighted sum: aligned, peaks meet peaks and the products add up; shifted, they cancel (lecture 21)
<Figure size 900x550 with 3 Axes>

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

Answer below (click to open it).

Notebook Cell
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.

Correlation between the weights and the template: 0.986
Test accuracy of the neuron: 0.9975  (template matching: 0.9975)
<Figure size 900x450 with 2 Axes>

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.

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?

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 xx is the depth and the observation yy the temperature, both standardized.

The network: 1 input, 3 hidden neurons with the tanh activation, 1 output with no activation.

hj=tanh⁡(W1j x+b1j),j=1,2,3,y^=∑jW2j hj+b2.h_j = \tanh(W1_j\, x + b1_j), \quad j = 1, 2, 3, \qquad \hat{y} = \sum_j W2_j\, h_j + b2 .

That is 10 weights: 3 input weights W1jW1_j and 3 biases b1jb1_j in the hidden layer, 3 output weights W2jW2_j and 1 bias b2b2. All start as random numbers (seed 2).

A network: each hidden neuron is the same neuron with its own weights; the output neuron takes their outputs as inputs (lecture 21)
W1 [ 0.19 -0.52 -0.41]  b1 [-1.22  0.9   0.57]  W2 [-0.16  0.39  0.14]  b2 -0.28
<Figure size 400x500 with 1 Axes>

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: ei=y^i−yie_i = \hat{y}_i - y_i, and the loss is the mean of ei2e_i^2.

Forward pass for one sample: each hidden neuron computes tanh of its weighted input, the output adds them up, and the error follows (lecture 21)
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 ii, with loss ei2e_i^2:

Output layer. The output neuron is the neuron of section 2, with the hidden outputs hijh_{ij} as its inputs. Its gradients are again the error times the input:

∂Li∂W2j=2 ei hij,∂Li∂b2=2 ei.\frac{\partial \mathcal{L}_i}{\partial W2_j} = 2\, e_i\, h_{ij}, \qquad \frac{\partial \mathcal{L}_i}{\partial b2} = 2\, e_i .

The error sent back to hidden neuron jj. How much does the loss change if the hidden neuron’s score W1jxi+b1jW1_j x_i + b1_j changes a little? Three factors, multiplied:

δij=2 ei⏟error at the output×W2j⏟weight of the connection×(1−hij2)⏟slope of tanh.\delta_{ij} = \underbrace{2\, e_i}_{\text{error at the output}} \times \underbrace{W2_j}_{\text{weight of the connection}} \times \underbrace{(1 - h_{ij}^2)}_{\text{slope of tanh}} .
  • the error at the output: no error, nothing to correct;

  • the weight that connects neuron jj 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 1−tanh⁡21 - \tanh^2): 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.

∂Li∂W1j=δij xi,∂Li∂b1j=δij.\frac{\partial \mathcal{L}_i}{\partial W1_j} = \delta_{ij}\, x_i, \qquad \frac{\partial \mathcal{L}_i}{\partial b1_j} = \delta_{ij} .

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.

Backward pass: each hidden neuron receives the output error times its output weight times the slope of its tanh (lecture 21)

Answer below (click to open it).

Notebook Cell
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.

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
<Figure size 1100x450 with 2 Axes>

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 w−α ∂L/∂ww - \alpha\, \partial \mathcal{L} / \partial w.

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