Source

Module 5 · Neural networks and backpropagation

Time: about 7 hours with readings · Lab: python course/labs/lab05_mlp_backprop.py

You need: Module 1 §5 (layers and the ReLU bend, in words), Module 2 §3–§5 (matrices and the transpose, derivatives, the chain rule, gradient descent) and Module 4 §3–§4 (softmax regression and its "probability minus truth" gradient).

By the end you can:

  • prove that stacking linear layers is pointless without a non-linearity, and solve XOR by hand with two ReLU units;
  • draw a two-layer network and count its parameters;
  • run backpropagation by hand on a tiny network, check it by nudging, and read the matrix version;
  • explain why weights start random, and at what scale;
  • explain what Keras's model.fit does on every step.

Why this matters

In TrayCheck. The head is a two-layer neural network:

x = tf.keras.layers.Dense(96, activation="relu")(x)    # hidden layer: 1280 → 96
x = tf.keras.layers.Dropout(.25)(x)                    # regularisation (Module 6)
output = tf.keras.layers.Dense(4, activation="softmax")(x)

and MobileNetV2 is the same idea repeated about fifty times with convolutions. Every one of its 2.4 million parameters was set by the algorithm in this module, backpropagation: the head and the top layers on TrayCheck's photos, the rest originally on ImageNet.

In the internship. You won't derive backpropagation in this role. You should be able to say what it is in two sentences, because "how does the model learn?" is a common interview question:

Training measures how wrong the model is on a batch of examples (the loss), then works backwards through the network to find how much each parameter contributed to that error. Every parameter is then nudged a little in the direction that reduces the error, and this repeats thousands of times.

§1 and that summary are the essentials; §2 makes the summary concrete.


1. Why we need a hidden layer, and a non-linearity

What a linear model can't do: XOR

A linear classifier scores with a weighted sum, so its boundary between "yes" and "no" is a straight line (or, with more inputs, a flat plane). Many problems need a bent boundary. The classic example is XOR ("exclusive or"): the answer is 1 when exactly one of two inputs is 1.

x₁ x₂ XOR
0 0 0
1 0 1
0 1 1
1 1 0

Proof that no weighted sum works. Suppose output = a x₁ + b x₂ + c fits all four rows. Row 1 forces c = 0. Row 2 forces a = 1. Row 3 forces b = 1. Then row 4 gives 1 + 1 + 0 = 2, not 0. Contradiction: no choice of a, b, c fits. The same shape turns up with food: one clue on its own may point towards a dish, but the same clue next to another may point away from it. When what a clue means depends on what else is present, fixed weights can't capture it.

Stacking linear layers doesn't help

Add a second layer of weighted sums? A weighted sum of weighted sums is still a weighted sum: (x W₁) W₂ = x (W₁ W₂), and W₁ W₂ is just one matrix. Ten linear layers can do exactly what one can, no more.

The fix: a bend between layers

Put a non-linear activation function after each hidden unit. The standard one is ReLU (rectified linear unit):

\[\text{ReLU}(a) = \max(0, a)\]

Negative values become 0; positive values pass unchanged. That one bend is enough. XOR solved by hand with two hidden ReLU units:

  • h₁ = ReLU(x₁ + x₂) (counts how many inputs are on)
  • h₂ = ReLU(x₁ + x₂ − 1) (switches on only when both are on)
  • output = h₁ − 2 h₂
x₁ x₂ h₁ h₂ h₁ − 2h₂ XOR
0 0 0 0 0 0
1 0 1 0 1 1
0 1 1 0 1 1
1 1 2 1 0 0

All four correct. The hidden units computed new features (h₂ is an "both are on" detector, the same trick as Module 1 §5), and the output layer combined them linearly. That is the general pattern: hidden layers turn the input into features in which the problem becomes linear. Training finds weights like these automatically.

A two-layer network

A network with one hidden layer computes:

\[h = \text{ReLU}(xW_1 + b_1), \qquad p = \text{softmax}(hW_2 + b_2)\]

Each hidden unit is a little detector that switches on in some region of input space; the output layer combines them. With enough hidden units, such a network can approximate essentially any reasonable function: each unit contributes one bend, and enough bends can trace any curve. This is the universal approximation result. Depth (many layers) lets networks build features out of features, which is far more efficient for images than one enormous hidden layer (Module 7).

Counting parameters

Each dense layer has (inputs × outputs) weights plus one bias per output (Module 2 §3). Lab 5's network is 64 → 64 → 10: W1 64 × 64 + b1 64 + W2 64 × 10 + b2 10 = 4,810. TrayCheck's head: 1280 × 96 + 96 = 122,976, then 96 × 4 + 4 = 388.


2. Backpropagation

Training needs the slope of the loss with respect to every parameter. Backpropagation computes all of them in one sweep backwards from the loss, applying the chain rule (Module 2 §4) one step at a time and reusing each result for the step before it.

By hand, on the smallest possible network

One input, one hidden ReLU unit, one output, and squared error against a target:

x ──(w1, b1)──► a ──ReLU──► h ──(w2, b2)──► z ──► loss L = (z − y)²

Take x = 2, target y = 1, and starting values w₁ = 0.5, b₁ = 0, w₂ = 1.5, b₂ = 0.

Forward pass (compute and keep every intermediate value):

Step Computation Value
a = w₁x + b₁ 0.5 × 2 + 0 1.0
h = ReLU(a) max(0, 1.0) 1.0
z = w₂h + b₂ 1.5 × 1.0 + 0 1.5
L = (z − y)² (1.5 − 1)² 0.25

Backward pass. Start at the loss and ask, at each step, "if this value moved by a little, how much would the loss move?" Each answer is the previous answer times one local slope:

Slope of L with respect to Chain rule Value
z slope of (z − y)² is 2(z − y) 2 × 0.5 = 1.0
w₂ (slope at z) × h, since z moves by h when w₂ moves by 1 1.0 × 1.0 = 1.0
b₂ (slope at z) × 1 1.0
h (slope at z) × w₂, since z moves by w₂ when h moves by 1 1.0 × 1.5 = 1.5
a (slope at h) × (ReLU's slope: 1 because a > 0) 1.5 × 1 = 1.5
w₁ (slope at a) × x 1.5 × 2 = 3.0
b₁ (slope at a) × 1 1.5

Check by nudging. Raise w₁ from 0.5 to 0.501 and run forward again: a = 1.002, h = 1.002, z = 1.503, L = 0.253009. The loss rose by 0.003009 for a nudge of 0.001: a slope of about 3.0, matching the table.

One step of gradient descent with learning rate 0.05 (new value = old − 0.05 × slope): w₁ = 0.35, b₁ = −0.075, w₂ = 1.45, b₂ = −0.05. Forward again: z = 0.856 and the loss falls from 0.25 to 0.021. (With learning rate 0.1 the step overshoots and the loss rises to 0.56, the Module 2 §5 lesson again.)

Three rules that make it mechanical

The table used only three kinds of local step, and every layer of every network is built from them:

  1. Through a weight: going backwards through "multiply by w" multiplies the slope by w (h's slope was z's slope × w₂).
  2. Into a weight: a weight's own slope is (slope arriving at its output) × (the value that came into it on the forward pass) (w₂'s slope was 1.0 × h; w₁'s was 1.5 × x). This is Module 4's "error × input" again.
  3. Through ReLU: the slope passes unchanged where the unit was active (a > 0) and is blocked (multiplied by 0) where it wasn't.

The loss at the end supplies the first slope: 2(z − y) for squared error, or p − one-hot for softmax with cross-entropy (Module 4 §4).

The same thing with matrices

A real layer has many units, and a batch has many examples, so the same three rules are written with matrices. For the two-layer classifier in §1, with a batch of n examples as the rows of X:

Forward pass (keep the intermediate values):

Z1 = X @ W1 + b1        # (n, hidden) values before the bend
H  = relu(Z1)           # (n, hidden) hidden features
Z2 = H @ W2 + b2        # (n, 10)     scores
P  = softmax(Z2)        # (n, 10)     probabilities
L  = mean(-log P[i, y_i])

Backward pass (each line is one of the three rules):

dZ2 = (P - onehot(y)) / n        # the loss supplies the first slope (Module 4)
dW2 = H.T @ dZ2                  # rule 2: slope arriving × value that came in
db2 = dZ2.sum(axis=0)
dH  = dZ2 @ W2.T                 # rule 1: back through the weights
dZ1 = dH * (Z1 > 0)              # rule 3: ReLU passes or blocks
dW1 = X.T @ dZ1                  # rule 2 again
db1 = dZ1.sum(axis=0)

Why the transposes? On the forward pass, each hidden unit sends its value to every output, one weight per output (a row of W₂). On the backward pass it must collect slope from every output it fed, each weighted by the same connecting weight. Collecting along a row is multiplying by the transpose, W₂ᵀ (Module 2 §3). Likewise H.T @ dZ2 pairs every hidden value with every output's slope, summed over the batch.

Why backpropagation made deep learning possible

  • It's cheap. The backward pass costs about the same as the forward pass, however many parameters there are. Getting each slope by nudging would need one extra forward pass per parameter: 2.4 million forward passes for TrayCheck, per step.
  • It needs the forward values. dW2 needs H, dZ1 needs Z1. This is why training uses more memory than prediction: every intermediate value must be kept until the backward pass uses it.
  • It's automatic. Frameworks record the forward operations and replay them backwards with these rules (automatic differentiation). That's what model.fit does on every batch.

The lab's gradient check

W1[6, 12]: backprop  0.0054858  nudging  0.0054858  rel. error 2.7e-10
b1[2]:     backprop  0.0403313  nudging  0.0403313  rel. error 1.1e-11
W2[3, 7]:  backprop  0.0011766  nudging  0.0011766  rel. error 1.3e-08
b2[0]:     backprop  0.0665234  nudging  0.0665234  rel. error 7.1e-11

Every backprop slope matches nudging to 8 or more significant figures, the same check as the w₁ = 0.501 nudge above.


3. Training: mini-batch stochastic gradient descent

Mini-batches

Computing the exact gradient needs the loss on every training example: one full pass per step. Mini-batch stochastic gradient descent (SGD) instead estimates it from a small random batch and takes a step:

for each epoch:                       # one pass over the training data
    shuffle the training examples
    for each batch of 32:
        forward pass  → loss
        backward pass → gradients
        update every parameter: p -= lr * gradient

A batch gradient is an estimate of the full gradient, in the same sense that a sample proportion estimates a true rate (Module 2 §10): noisy, but right on average. Using batches of 32 from 400 photos gives 13 updates per pass instead of 1, so training moves far faster for the same computation. The noise is tolerable and often seems to help the model generalise. Lab 5 and TrayCheck both use batches of 32.

How weights start

Weights start random. Two questions: why random, and how big?

  • Why not all zero (or all equal)? Then every hidden unit computes the same value, receives the same slope, and gets the same update. They stay identical forever, and 96 hidden units behave like one. Random starting values break that symmetry.
  • How big? Each unit adds up n inputs × weights. If the weights are too large, each layer's outputs are larger than its inputs, and after many layers the numbers explode; too small, and they shrink towards nothing (and so do the slopes on the way back). The fix is to scale the random weights by the number of inputs. He initialisation, designed for ReLU networks, draws weights with a spread (variance) of 2 / (number of inputs): the "number of inputs" keeps the sum's size steady, and the 2 compensates for ReLU zeroing about half the values. Lab 5 uses it; Keras applies sensible defaults automatically, and TrayCheck's backbone starts from pre-trained weights anyway.

Worked example: the lab, run

epoch  10  train loss 0.1862  val loss 0.2152  train acc 0.956  val acc 0.944
epoch  20  train loss 0.1085  val loss 0.1442  train acc 0.977  val acc 0.967
epoch  40  train loss 0.0623  val loss 0.1126  train acc 0.991  val acc 0.975
parameters: 4,810
test accuracy: 0.964

An honest observation: on this tiny dataset the neural network (96.4% test) does not beat Module 4's linear model (96.9%). Clean, centred 8 × 8 digits are almost linearly separable already, so extra flexibility buys nothing. Hidden layers pay off when the raw input is far from separable, like photos of food. Always compare against the simple baseline.


Check your understanding

1. Why is a network of three Dense layers with no activations no better than one Dense layer?

A composition of linear functions is linear: x W₁ W₂ W₃ = x (W₁W₂W₃), one matrix. Without non-linear activations the network can only draw straight decision boundaries.

2. In the XOR solution, what does h₂ = ReLU(x₁ + x₂ − 1) detect, and why is it needed?

It switches on only when both inputs are on. The output needs to subtract evidence exactly in that case, which no fixed weighting of x₁ and x₂ can do; with h₂ as a feature, a plain weighted sum (h₁ − 2h₂) solves it.

3. In the tiny network, change the starting w₁ to −0.5. What is the slope of the loss with respect to w₁, and why?

Zero. Now a = −1, so ReLU outputs 0 and its slope is 0: the unit is inactive, and rule 3 blocks the slope. No change to w₁ (by a small nudge) changes the loss. (A unit stuck like this for every input is called a "dead" ReLU.)

4. Why is backpropagation so much faster than computing each slope by nudging?

Nudging needs a separate forward pass per parameter (millions of passes). Backprop gets all slopes in one backward pass costing about as much as one forward pass, by reusing the intermediate results via the chain rule.

5. Why must hidden weights not all start at zero?

Every hidden unit would compute the same thing, get the same slope and the same update, and stay identical forever, so the layer would act like a single unit.

6. TrayCheck's head is Dense(96, ReLU) → Dropout → Dense(4). How many trainable parameters, if the backbone outputs 1280 features?

1280 × 96 + 96 = 122,976 and 96 × 4 + 4 = 388, so 123,364. Dropout has none.

7. The lab's neural network didn't beat the linear model. Does that mean neural networks are overrated?

No. It means this problem doesn't need the extra flexibility. On raw photos a linear model on pixels would fail badly. The lesson is to compare against a simple baseline before reaching for complexity.


Go deeper

The module above is self-contained. These give the same ideas visually or at more depth.

Recommended (free)

  • 3Blue1Brown, Neural networks series, chapters 1–4: what a network is, gradient descent, what backprop is doing, and backprop calculus. The best visual introduction there is. 3blue1brown.com
  • Michael Nielsen, Neural Networks and Deep Learning, Chapter 1 (networks on handwritten digits) and Chapter 2, How the backpropagation algorithm works. neuralnetworksanddeeplearning.com
  • Andrej Karpathy, Neural Networks: Zero to Hero, lecture 1, "The spelled-out intro to neural networks and backpropagation: building micrograd": §2's by-hand table, turned into about 100 lines of Python. karpathy.ai/zero-to-hero.html

Optional

  • Stanford CS231n notes: Backpropagation, Intuitions and Neural Networks Part 1.
  • Dive into Deep Learning, chapter Multilayer Perceptrons: Forward Propagation, Backward Propagation, and Computational Graphs and Numerical Stability and Initialization. d2l.ai
  • Prince, Understanding Deep Learning, Chapters 3–4 (shallow and deep networks) and Chapter 7 (gradients and initialisation). Free PDF at udlbook.github.io/udlbook.
  • Goodfellow et al., Deep Learning, §6.1 (XOR) and §6.5 (back-propagation).
  • Nielsen, Chapter 4: a visual proof that neural networks can compute any function.
  • Papers: Rumelhart, Hinton & Williams, Learning representations by back-propagating errors, Nature 1986; He et al., Delving Deep into Rectifiers, ICCV 2015 (He initialisation).

Interview angle

"The head is a small two-layer network: 1280 features to 96 ReLU units to 4 softmax outputs. The ReLU is what makes depth useful; without it, stacked layers collapse into one. Training uses backpropagation, which is the chain rule applied from the loss backwards: each layer passes the slope back through its weights, and each weight's slope is the incoming slope times the value that flowed into it. That gives every gradient for roughly the cost of one forward pass. I've done it by hand and checked it by nudging, so I know what Keras does inside model.fit."