Backpropagation by hand
Last updated
To train a network, you need the gradient of the loss with respect to every weight in it, including the hidden layer's, whose right answers nobody gives you. Backpropagation finds them all in one backward sweep, using nothing but the chain rule of lesson 1.7. This lesson derives every gradient of a two-layer network by hand, writes each one as a line of NumPy, and checks them against finite differences, the habit that catches the mistakes everyone makes.
By the end of this lesson you can
- Write a two-layer network’s loss as a chain of functions, and follow a gradient back through it
- Derive the gradients of the output layer and the hidden layer, and say why the hidden one uses Wᵀ
- Write the backward pass in NumPy, with every gradient the same shape as its parameter
- Check hand-derived gradients with finite differences
The loss as a chain of functions
The network: 2 inputs, a hidden layer of 3 ReLU units, and 3 outputs turned into probabilities by a softmax, for 3 classes. For one example with one-hot label , the forward pass is a chain:
This lesson works with one example as column vectors, as the maths is usually written; lesson 6.5 does a whole batch with rows.
The right answer is class 2, and the network gives it only 0.197, so the loss is . Hidden unit 1's sum is negative, , so ReLU switches it off.
Before the vectors, follow the idea on a network with one unit per layer, where every value is a single number. Step forward to compute each node, then backward: each node passes its gradient to its inputs, times the local derivative on the edge, the chain rule one link at a time.
Step 0 of 17. Nothing worked out yet. Press Step to start the forward pass.
Every gradient on the left is a product of the local derivatives along the path from the loss. Backpropagation is that, organised so that each product is computed once and reused.
The output layer’s gradient
Write : how the loss changes as each weighted sum in layer changes, called the layer's error. For a softmax followed by cross-entropy, lesson 3.11 worked it out:
The prediction minus the truth: here. Positive where the network said too much, negative for the right class, which it under-rated.
Now a weight. , so nudging changes by times the nudge, and nothing else. By the chain rule,
In words: a weight's gradient is the error at the neuron it feeds, times the input it multiplies. A weight on an input of 0 gets no gradient, which makes sense: it had no effect. is an outer product, column times row, np.outer(delta2, a1), and it's , the shape of .
The hidden layer’s gradient
Hidden unit feeds every output neuron, through weight to output . So its effect on the loss arrives along three paths, and the chain rule adds them up:
That's where the transpose comes from: going forward, row of collects output 's inputs; going back, column collects the errors unit contributed to. Then through the ReLU, which multiplies by its slope, 1 or 0, element by element ():
Follow the errors flowing back through the layers:
The softmax and cross-entropy give δ² = ŷ − y = (0.455, 0.348, −0.803): too high for classes 1 and 2, too low for class 3, the true one.
Every weight’s gradient
Layer 1's weights follow the same rule as layer 2's, with as the input:
That's all of it. For any number of layers, the same two lines repeat: send the error back, , and read off the weights' gradients, . Six lines of NumPy:
Hidden unit 1 was off, so and the first row of is all zeros (one shows as -0., a zero with a minus sign from multiplying by ): a unit that's off doesn't learn from this example. Every gradient has exactly the shape of its parameter, which is the first thing to check.
The cost is the striking part: the backward pass is about as much arithmetic as the forward pass, however many weights there are. Nudging each weight one at a time would need two forward passes per weight: millions, for a real network.
Check by finite differences
Hand-derived gradients are easy to get subtly wrong, so check them. Nudge each parameter up and down by a tiny , and see how the loss moves (lesson 1.6):
Every hand-derived gradient matches the nudged one to about . That's gradient checking: slow, so you'd never train with it, but the best way to know a backward pass is right. Do it every time you write one; lesson 6.7 will automate the backward pass, and you'll check that too.
Wrong way: one transpose missing
The commonest slip: writing W2 @ delta2 instead of W2.T @ delta2. Here is square, so both work without an error:
The shape of is right, . Nothing crashes. And the gradient is wrong by up to 0.6, larger than the gradients themselves. Training with it would still change the weights, and the loss might even fall for a while, but it would be following the wrong direction. Without the check, you might spend days wondering why the network learns badly.
Gradient checking caught it in one line. Shape checks are necessary but not enough; numbers have to match too.
Check what you learned
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- Rumelhart, Hinton and Williams, Learning representations by back-propagating errors, Nature 323, 1986: backpropagation through hidden layers
- Nielsen, Neural Networks and Deep Learning, chapter 2: How the backpropagation algorithm works: the δ notation and the four equations of backpropagation
- Goodfellow, Bengio and Courville, Deep Learning, section 6.5: Back-Propagation and Other Differentiation Algorithms: the general algorithm, and gradient checking