From a neuron to a network:
templates, logistic regression, layers

Session 21 · Mon Nov 16 and Wed Nov 18 · Book section 4.0

🧠

Today’s question

Deep learning starts with one neuron, and you have already used it twice.

What does one neuron compute, how are its weights set, and what does it miss?

Part 1, Monday: one neuron (4.0). Wednesday: Part 2, gradient descent (4.0), then Part 3, a network (4.1, 4.2).

Chapter 4: four canonical networks

The data choose the network, and each network must first beat a simpler method. Every row is built from one neuron: today.

One neuron: a weighted sum, then an activation

Score \(z = \sum_i w_i x_i + b\): each input times its weight, added up, plus a bias. The activation turns the score into the output.

The activation names the model

The same weighted sum gives three models you know. Only the last step differs.

Template matching 1: cut out a known earthquake

The template is 6 s of record around an earthquake we already know: 600 numbers. Is the same waveform anywhere else in the record?

Template matching 2: slide it, compute a score

One score at each position of the template: together they are the cross-correlation. The score is 0.61 at B, where an earthquake hides in the noise.

Template matching 3: aligned waveforms score high

Score = mean of record × template, sample by sample. Aligned, peaks meet peaks and the products are positive: 0.61. Shifted or on noise, they cancel: 0.09 and 0.12.

On ten years of records: 1.81 million earthquakes

🗂️ Catalog & compiled product 🪨 Solid Earth 📈 Seismology

Lecture 1: the same three steps, with the waveform of every known earthquake in Southern California as a template, found ten times more earthquakes than the catalog held.

Our figure from the open QTM catalog of Ross, Trugman, Hauksson & Shearer (2019), Science 364, 767–771 (figscripts/qtm_hidden_earthquakes.py).

Without a template: training finds the same waveform

From 800 windows labeled event or noise, training gives weights that draw the waveform of the event: correlation 0.99 with the template.

The 1958 rule: update the weights after each nonzero error

Error = prediction − observation: −1 for a missed event, +1 for a false alarm, 0 otherwise. From random weights the line stops moving after 48 updates.

On real events the rule never stops updating

📍 In-situ sensor 🪨 Solid Earth 📈 Seismology

Explosion or earthquake, Pacific Northwest: about 196 of 1,500 events still have a nonzero error at each epoch, and the test accuracy of the rule swings from 74.6% to 89.6%. Lowering the log-loss climbs steadily to 89.0%.

Why the rule cannot settle: the step gives no slope

With the step, the only measure is how many windows are wrong: flat, then a jump, so no direction to move. With the sigmoid, the log-loss has a slope everywhere and the boundary settles.

From the rule to the loss: the error becomes smooth

Replace the step by the sigmoid and the 1958 update becomes the gradient update on the log-loss of lecture 16. Every network in Chapter 4 is trained with this update.

In the literature: where do aftershocks occur?

🖥️ Model & simulation 🪨 Solid Earth 📈 Seismology

Input: stress change in a 5 km cell. Output: aftershocks there, yes or no. One neuron does about as well as a network of 13,451 weights: 53% against 55%.

Our rerun of the open release of DeVries et al. (2018), Nature 560, 632–634; Mignan & Broccardo (2019), Nature 574, E1–E3. Map: cartoon.

Open 4.0 (15 minutes)

  1. Section 4.2: the rule stops after 2 epochs
  2. Section 4.1: write the sigmoid, read the loss at each epoch
  3. Section 5: compare the fitted weights with the template
  4. Move the arrival by 0.1 s: what does the neuron detect now?

pixi run jupyter lab, then mlgeo_4.0_perceptrons.ipynb · Lab 3.8 due tonight · Chapter 6 quiz closes Wednesday · Classic ML project milestone (3.20) due Mon Nov 23

Part 2. How are the weights found? Start from random weights

Travel time against distance: the neuron predicts w × distance + b. Its weight w and bias b start as random numbers drawn with a seed, not as zeros.

Errors: prediction minus observation

Each sample has an error: its prediction minus its observation. With the starting weights every prediction is too short: −24.2 s at the farthest station.

The loss of each sample, and its mean over the batch

Loss of a sample: its error squared. In this batch of 16 samples it ranges from 14 to 608 s². The loss of the batch is their mean, 248 s².

The gradient of the loss: one number for each weight

Gradient of the loss for weight \(w_j\): the mean over the samples of 2 × error × input. Here −13.6: raising \(w\) lowers the loss.

Gradient of the loss = error part × slope × input

Gradient of one sample’s loss, for three activations. Their mean over the batch, times − learning rate, is the change of the weight (next slide).

The threshold logic unit today

Binarized and spiking networks keep the threshold logic unit for the prediction. To train them, the backward pass replaces its zero slope by a stand-in: Rosenblatt’s trick, made systematic.

The update: each weight moves against its own gradient

Change of a weight = − learning rate × its gradient. Both gradients are negative, so both values go up: w by 1.36, b by 2.99. The loss falls from 269 to 172 s².

Many updates: the path to the lowest loss

Each red dot is the weight and bias after one more update. The updates are long where the gradient is large and shrink near the lowest loss, where the gradient is zero.

Repeat: the loss at each epoch

60 epochs: the loss falls from 269 s² to 0.21 s², close to the variance of the noise in the picks. The fitted line gives 6.04 km/s.

Batches: several updates in one epoch

Batches of 16 samples: 5 updates per epoch. At the last epoch the five batch losses still range from 0.12 to 0.31 s². The loss of the epoch is their mean.

The learning rate sets the size of the update

Same seed, 200 epochs. Learning rate 0.001 ends at 121 s², 0.01 at 0.29 s², 0.1 at 0.21 s². At 1.05 the loss grows at every epoch.

Open 4.0, section 2 (25 minutes)

  1. Sections 2.1 to 2.5: write the error, the loss, the gradient, the update
  2. Section 2.6: read the loss printed at each epoch
  3. Section 2.7: write the loss of a batch, compare the five batches
  4. Section 3: find a learning rate at which the loss diverges

pixi run jupyter lab, then mlgeo_4.0_perceptrons.ipynb · Each “Your turn” cell is one line; the hidden cell below it checks your answer

Part 3. A network: neurons that feed neurons

Each hidden neuron is the same neuron, with its own weights. The output neurons take the hidden outputs as their inputs.

A simple example: temperature against depth in the ocean

🖥️ Model & simulation 🌊 Ocean 🌊 Oceanography

One neuron predicts a straight line: 2.4 °C per 100 m, error 1.0 °C. It cannot bend at the two thermoclines. Synthetic profile, 60 samples.

Forward pass: three hidden neurons, added up

Each hidden neuron makes one smooth step in depth. Scaled by its output weight and summed, the three steps build the profile: 10 weights in all.

The loss of the network: the same mean of squared errors

Each red bar is the error of one sample, prediction minus observation. The loss is the mean of the squared errors; its square root here is 0.68 °C.

Backpropagation for one neuron

Backward, from the error: × 2 × slope gives the gradient for b (−48.5), then × input the gradient for w (−74.5).

Backpropagation 1: the forward pass gives the error

One sample at 142 m: depth in, each hidden neuron computes tanh of its weighted input, the output sums them. Prediction minus observation: error −0.51, or −2.0 °C.

Backpropagation 2: the error goes back

Each hidden neuron receives the output error × the weight that links it to the output × the slope of its tanh. The gradient of any weight is the error at its end × the value at its start.

Training the network: the same loop, 10 weights

From random weights (seed 2) the root of the loss falls from 3.8 °C to 0.31 °C in 20,000 updates, with a long plateau near 0.7 °C before the network finds the second thermocline.

In the literature: glacier mass balance, French Alps

🖥️ Model & simulation 🧊 Cryosphere 🧊 Glaciology

Bolibar et al. (2020), The Cryosphere 14, 565–584, Figs. 6 and 3. doi:10.5194/tc-14-565-2020. CC BY 4.0.

On glaciers left out of training, the error falls from 0.74 m of water per year for the linear model (b) to 0.51 for the network (c).

In the literature: snow and ocean nutrients

📍 In-situ sensor 💧 Land water 💧 Hydrology & land-surface modeling

Ntokas et al. (2021), Hydrol. Earth Syst. Sci. 25, 3017–3040, Fig. 15. doi:10.5194/hess-25-3017-2021. CC BY 4.0.

📍 In-situ sensor 🌊 Ocean 🌊 Oceanography

Sauzède et al. (2017), Front. Mar. Sci. 4, 128, Fig. 2. doi:10.3389/fmars.2017.00128. CC BY.

Snow water from snow depth: one hidden layer, R² 0.97 against 0.88 for regression formulas. Ocean nitrate: two hidden layers, error 1.04 µmol/kg.

Four seismic source types: what the hidden layer adds

📍 In-situ sensor 🪨 Solid Earth 📈 Seismology

On 61 features, a hidden layer of 32 neurons adds 0.4 points to logistic regression: 3 of 800 test events, inside one standard error.

From Chapter 3 to Chapter 4

Earlier in the course In Chapter 4 Example from these two days
template matching a neuron’s weights correlation 0.99 with the event
logistic regression a neuron trained on a loss 89.0%, explosion or earthquake
gradient descent (3.6) the training loop: loss, gradient, update 269 s² to 0.21 s² in 60 epochs
baseline the model with no hidden layer 86.8% against 87.1%
new layers, trained by backpropagation ocean profile: 3.8 °C to 0.31 °C

Open 4.0 section 6, then 4.1

  1. 4.0 section 6: write the error sent back to the hidden layer
  2. 4.1: find the forward pass, the loss, loss.backward(), the update
  3. Read the learning curves: where do training and validation part?
  4. 4.2: retrain with p_drop=0.0 and compare the curves

PyTorch names: nn.Module, nn.Linear, nn.ReLU, nn.CrossEntropyLoss, Adam, DataLoader · Chapter 6 quiz closes today · Classic ML project milestone (3.20) due Mon Nov 23 · Friday: convolution (4.3)

Chapter 4: the neuron inside every network

Each row is today’s neuron, repeated and connected in a different way, and trained by the same gradient descent.