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.
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.
- loss functions for regression and classification;
- backpropagation, computed number by number on a tiny network — and checked;
- to train networks yourself in a playground and see what width, depth and learning rate do;
- the universal approximation theorem and its limits;
- vanishing gradients, overfitting, and practical advice for scientific problems.
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$:
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
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:
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".
3. The neural-network playground

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.
4. Why it can work: universal approximation
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.
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$.
6. Generalisation, overfitting, and good practice

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).
- Scale inputs and outputs to order one; networks handle $x\in[-1,1]$ far better than pressures of $10^7$ Pa.
- Initialise with variance $\approx 1/\text{fan-in}$ (Glorot) for tanh, $2/\text{fan-in}$ (He) for ReLU.
- Smooth activations (tanh, sine, softplus) whenever derivatives of the output enter the loss — as in PINNs.
- Start with Adam (learning rate around $10^{-3}$), plot the loss on a log scale, then optionally refine with L-BFGS.
- Check gradients against finite differences when you write your own code (Section 2).
- Compare with a classical solver on a problem with a known answer before trusting results.
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).
- Training minimises a loss: MSE for numbers (and PINNs), cross-entropy for classes.
- Backpropagation = chain rule backwards: $\boldsymbol\delta^{(\ell)} = (W^{(\ell+1)})^{\mathsf T}\boldsymbol\delta^{(\ell+1)}\odot\sigma'(\mathbf z^{(\ell)})$, gradient = $\delta\times a$.
- Width and depth control what a network can represent; the learning rate controls whether training works.
- Universal approximation guarantees existence, not trainability or generalisation.
- Vanishing gradients, overfitting and scaling are the everyday enemies; good practice beats them.
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
- I. Goodfellow, Y. Bengio & A. Courville, Deep Learning, MIT Press, 2016 — chapters 6–8.
- C. F. Higham & D. J. Higham, "Deep learning: an introduction for applied mathematicians", SIAM Review 61(4) (2019) 860–891.
- M. Nielsen, Neural Networks and Deep Learning, 2015 — chapter 2 (backpropagation) and chapter 5 (vanishing gradients), free online.
- X. Glorot & Y. Bengio, "Understanding the difficulty of training deep feedforward neural networks", AISTATS 2010, PMLR 9, 249–256.
- N. Rahaman et al., "On the spectral bias of neural networks", ICML 2019.