Training neural networks

A network starts with random weights and knows nothing. Training nudges thousands of weights, a little at a time, until the network's answers match the data — or, in SciML (Scientific Machine Learning), the physics.

⏱ 35 minNeeds: Chapters 2, 11, 125 simulations, incl. a network playground
In plain words

Training needs three things. A loss: one number saying how wrong the network is. A gradient: for every weight, which way to change it to reduce the loss — computed by backpropagation, which is just the chain rule. And an optimiser: gradient descent or Adam (Adaptive Moment Estimation; Chapter 11), which takes the step. Repeat thousands of times.

You will learn
Level 1 · basicThe loss; the playground Level 2 · standardBackpropagation; universal approximation Level 3 · advancedVanishing gradients; generalisation
Simplest example first · learning one weight

The smallest possible "network" has one weight: $u = w\,x$. One training example says: input $x = 1$ should give $y = 2$. The loss is $L(w) = (w\cdot1 - 2)^2 = (w - 2)^2$ and its gradient is $L'(w) = 2(w - 2)$ — this one derivative is backpropagation for this network. Start from $w = 0$ with learning rate $0.25$: $$w: \ 0 \;\to\; 1 \;\to\; 1.5 \;\to\; 1.75 \;\to\; 1.875 \;\to \cdots \to 2.$$ The loss falls $4 \to 1 \to 0.25 \to 0.0625$: each step removes three quarters of it. Training a network with a million weights is the same loop, with a million such derivatives computed together.

1. The loss: measuring how wrong

Given training data $(\mathbf x_k, y_k)$, $k = 1,\dots,N$, and a network $u_\theta$ with parameters $\theta$:

Definition · Two standard losses

Mean squared error (regression — predicting numbers; also the PINN (Physics-Informed Neural Network) loss): $$L(\theta) = \frac1N\sum_{k=1}^N \big(u_\theta(\mathbf x_k) - y_k\big)^2.$$ Binary cross-entropy (classification — the output $p = u_\theta(\mathbf x)\in(0,1)$ is a sigmoid "probability of class 1"): $$L(\theta) = -\frac1N\sum_{k=1}^N \Big(y_k\ln p_k + (1-y_k)\ln(1-p_k)\Big).$$

Goodfellow, Bengio & Courville, Deep Learning, MIT Press (2016), sections 5.5 and 6.2; Bishop, Pattern Recognition and Machine Learning, Springer (2006), chapter 4.

Training means solving the optimisation problem $\min_\theta L(\theta)$ — Chapter 11's gradient descent, with $\theta$ in thousands or millions of dimensions.

2. Backpropagation, number by number

Want every step?

Chapter 14 explains forward and backward propagation with a single neuron, all numbers written out, an interactive graph you can step through, and why backward is so much cheaper than forward when there are many weights.

Gradient descent needs $\partial L/\partial w$ for every weight. For a network $u = f^{(L)}\circ\dots\circ f^{(1)}$, the chain rule (Chapter 2) gives a beautifully efficient recipe. Define the error signal of each neuron, $\delta = \partial \ell/\partial z$ (how much the loss changes if that neuron's weighted sum changes). Then:

Algorithm · Backpropagation

1. Forward pass: compute and store all $\mathbf z^{(\ell)}$ and $\mathbf a^{(\ell)}$.
2. Output error: $\boldsymbol\delta^{(L)} = \partial\ell/\partial\mathbf z^{(L)}$; for squared error with a linear output, $\delta^{(L)} = 2(u - y)$; for cross-entropy with a sigmoid output, $\delta^{(L)} = p - y$.
3. Backward pass, for $\ell = L-1, \dots, 1$: $$\boldsymbol\delta^{(\ell)} = \big(W^{(\ell+1)}\big)^{\!\mathsf T}\boldsymbol\delta^{(\ell+1)} \odot \sigma'\big(\mathbf z^{(\ell)}\big).$$ 4. Gradients: $\dfrac{\partial\ell}{\partial W^{(\ell)}} = \boldsymbol\delta^{(\ell)}\big(\mathbf a^{(\ell-1)}\big)^{\!\mathsf T}$, $\quad\dfrac{\partial\ell}{\partial\mathbf b^{(\ell)}} = \boldsymbol\delta^{(\ell)}$.

($\odot$ is entry-wise multiplication.) The cost is about twice that of one forward pass, whatever the number of parameters.

Rumelhart, Hinton & Williams, Nature 323 (1986) 533–536; Higham & Higham, SIAM Review 61(4) (2019) 860–891, section 5; Baydin et al., JMLR 18(153) (2018).

In words: the error at the output is sent backwards along the same connections, scaled by the weights, and multiplied at each neuron by the slope of its activation. Each weight's gradient is "error arriving at its end × signal leaving its start".

Backpropagation on a tiny network1 input → 2 tanh neurons → 1 linear output; one training example (x, y)
The table lists every parameter's gradient from backpropagation next to a finite-difference check $\frac{\ell(\theta + \epsilon) - \ell(\theta - \epsilon)}{2\epsilon}$ (Chapter 2). They agree to many digits — the standard way to test a backpropagation code. Press "One gradient step" repeatedly and watch the loss fall.

3. The neural-network playground

Animation: a network curve bends towards noisy training points as the loss falls.
Watch: Iteration by iteration, gradient descent bends the network towards the data; the loss (right) falls by orders of magnitude.

Now train real networks. Each point is a training example; colour is its class. The background shows the network's prediction everywhere — its decision regions. On the right, the live network: line thickness is $|w|$, blue positive, orange negative.

Train a classifier — in your browsertanh hidden layers, sigmoid output, cross-entropy loss, Adam
Press ▶ Train.
Things to try: (1) XOR (exclusive OR) with 0 hidden layers — a single neuron, it fails; then 1 layer of 2–4 neurons. (2) Circle with 1 layer of 2 neurons (too few: underfitting), then 4. (3) Spiral needs depth: try 2–3 layers of 8. (4) A learning rate of 0.3 — training becomes erratic. (5) Sigmoid with 3 layers trains much more slowly — vanishing gradients (Section 5).

4. Why it can work: universal approximation

Theorem · Universal approximation (one hidden layer)

Let $\sigma$ be continuous and not a polynomial. For every continuous $f$ on a compact set $K\subset\mathbb R^n$ and every $\varepsilon > 0$ there are $N$ and parameters $v_j, \mathbf w_j, b_j$ such that $$\Big|\, f(\mathbf x) - \sum_{j=1}^{N} v_j\,\sigma(\mathbf w_j\cdot\mathbf x + b_j)\Big| < \varepsilon \quad\text{for all } \mathbf x \in K.$$

Cybenko, Math. Control Signals Systems 2 (1989) 303–314; Hornik, Stinchcombe & White, Neural Networks 2 (1989) 359–366; Leshno, Lin, Pinkus & Schocken, Neural Networks 6 (1993) 861–867.

Read it carefully. It guarantees that a good network exists. It does not say how many neurons are needed, that gradient descent will find the weights, or that the network will predict well away from the data. Those three gaps — size, optimisation, generalisation — are what the rest of this chapter and most of deep-learning research are about. The simulation shows the theorem at work: each faint curve is one neuron $v_j\tanh(w_jx + b_j)$; their sum (orange) is the network.

Fit a curve — see the neurons add upone hidden layer of tanh neurons, Adam
training datanetwork outputindividual neuronsvalidation points
Press ▶ Train.
Notice spectral bias with "sin(2x) + 0.3 sin(10x)": the smooth part is learned first, the fast wiggle much later (Rahaman et al., ICML 2019). With "noisy samples" and 40 neurons, train for a long time and watch validation error rise — overfitting.

5. Deep networks and vanishing gradients

In a deep network, the backward pass multiplies by $W^{\mathsf T}$ and $\sigma'$ once per layer. If those factors are typically below 1, the error signal shrinks exponentially on its way back, and early layers barely learn. The sigmoid is the worst offender: $\sigma' \le \tfrac14$.

Gradient size, layer by layer, at initialisation10 hidden layers of 10 neurons, random weights
Each bar is the average $|\partial L/\partial w|$ in one layer (log scale). Sigmoid: gradients in the first layers are orders of magnitude smaller than in the last. Increase the weight scale and they can explode instead. This is why careful initialisation (Glorot & Bengio, AISTATS 2010; He et al., ICCV 2015), ReLU, and residual connections matter.

6. Generalisation, overfitting, and good practice

Animation: polynomial fits of increasing degree; training error keeps falling while test error rises after a point.
Watch: Underfit → good fit → overfit. Train error (blue) always falls; test error (green) tells the truth. More in Chapter 15.

The goal is not a small training loss but good predictions on new inputs. Split data into a training set (to fit), a validation set (to choose hyperparameters and decide when to stop) and a test set (touched once, for an honest final number). When training loss falls but validation loss rises, the model is overfitting. Remedies: more data, a smaller model, early stopping, weight penalties ($L + \lambda\|\theta\|^2$) — and, in SciML, physics constraints, which tell the network what to do between data points (Chapter 9).

A practical checklist for scientific problems

7. Try it in Python

A complete network with backpropagation in NumPy — the code of Section 2, written for a whole data set.

import numpy as np
import matplotlib.pyplot as plt

rng = np.random.default_rng(0)
x = np.linspace(-1, 1, 60); y = np.sin(3 * x)              # data
n = 10                                                    # hidden neurons
w, b = rng.normal(0, 2, n), rng.normal(0, 1, n)
v, c = rng.normal(0, 1 / np.sqrt(n), n), 0.0
lr = 0.05

for step in range(5001):
    h = np.tanh(np.outer(x, w) + b)                       # forward: hidden layer (60, n)
    u = h @ v + c                                         # forward: output
    e = u - y
    if step % 1000 == 0: print(f"step {step:5d}   loss {np.mean(e**2):.2e}")
    delta_out = 2 * e / len(x)                            # backward: output error signal
    delta_h = delta_out[:, None] * v * (1 - h**2)          # backward: hidden error signals
    v -= lr * (h.T @ delta_out); c -= lr * delta_out.sum()
    w -= lr * (delta_h * x[:, None]).sum(0); b -= lr * delta_h.sum(0)

plt.plot(x, y, "o", ms=3, label="data"); plt.plot(x, u, label="network")
plt.legend(); plt.grid(alpha=.3); plt.show()

In PyTorch, loss.backward() does all of the backward pass for you:

import torch
torch.manual_seed(0)
x = torch.linspace(-1, 1, 60).reshape(-1, 1); y = torch.sin(3 * x)
net = torch.nn.Sequential(torch.nn.Linear(1, 10), torch.nn.Tanh(), torch.nn.Linear(10, 1))
opt = torch.optim.Adam(net.parameters(), lr=1e-2)
for step in range(3001):
    loss = ((net(x) - y) ** 2).mean()
    opt.zero_grad(); loss.backward(); opt.step()          # backpropagation + Adam
    if step % 500 == 0: print(step, loss.item())

In backpropagation, the gradient of a weight $w_{ij}$ (from neuron $j$ to neuron $i$) equals…

Right: $\partial\ell/\partial W^{(\ell)} = \boldsymbol\delta^{(\ell)}(\mathbf a^{(\ell-1)})^{\mathsf T}$.

Training loss is $10^{-6}$ and validation loss is $10^{-1}$ and rising. What should you do first?

Right — the network is memorising the training set (overfitting).

Key takeaways
Next: from neural networks to PINNs

Everything here — a network, a loss, backpropagation, Adam (Adaptive Moment Estimation) — carries straight over to physics-informed neural networks. What changes is the loss: instead of (or as well as) matching data, the network must satisfy a differential equation. Chapter 16 starts by showing, side by side, a data-only network failing and a PINN succeeding on the same oscillator. Go to Chapter 16 →

Further reading