Chapter 17 // Neural Networks

Backpropagation.

The network is wrong. Which of its thousands of weights should change, and by how much?

Reading time
19 min
Data

We have a network that produces outputs and a loss that says how wrong they are. This chapter supplies the missing piece that turns a network into something that learns. It is the most important algorithm in the book, and it is one idea you already know, used very carefully.

Who is to blame?

Gradient descent needs one thing: for every weight, the slope of the loss with respect to that weight. Given the slopes, the update is the familiar “step against the gradient”.

For a line with two parameters the slopes were easy to write down. A network is harder. A weight in the first layer affects the loss only indirectly: it changes a neuron’s output, which changes every neuron in the next layer, which changes the scores, which changes the loss. Working out its share of the blame looks daunting.

There is a brute-force way. Nudge one weight slightly, run the whole network again, and see how much the loss moved. That works, but it needs one full run of the network per weight. A network with a million weights would need a million runs to take a single step.

gets every slope from one run forward and one run backward. It is the reason neural networks are practical at all.

One neuron, forwards then backwards

Start with the smallest network there is: one input, one weight, one bias, a ReLU, and a squared-error loss. The input is 2 and the target is 5.

The forward pass computes values, left to right. The then computes gradients, right to left, using the chain rule from the toolkit chapter on derivatives: when calculations are chained, their rates multiply.

Figure

A forward pass and a backward pass

Round 1, step 0 of 7Start: an input, a weight, a bias and a target.

Target
5
Output this round
–
Loss this round
–
Loss in earlier rounds
–
Learning rate 0.05
The top number in each box is its value. The 'grad' line underneath is the slope of the loss with respect to that value. Try it: step through one whole round, reading the explanation at each step. Then apply the update and go round again, watching the loss.

Here is the first round, written out. Forward:

z=0.5×2+0.5=1.5a=ReLU(1.5)=1.5L=(1.5−5)2=12.25z = 0.5 \times 2 + 0.5 = 1.5 \qquad a = \text{ReLU}(1.5) = 1.5 \qquad L = (1.5 - 5)^2 = 12.25

Backward, one step at a time:

QuestionLocal slopeGradient so far
How does the loss change with the output aa?2(a−5)=−72(a - 5) = -7−7-7
How does aa change with zz?ReLU has slope 1, since z>0z > 0−7×1=−7-7 \times 1 = -7
How does zz change with the weight?The input, 2−7×2=−14-7 \times 2 = -14
How does zz change with the bias?1−7×1=−7-7 \times 1 = -7

Both gradients are negative, so both the weight and the bias should increase. With a learning rate of 0.05 the weight becomes 0.5+0.7=1.20.5 + 0.7 = 1.2 and the bias 0.850.85. The next forward pass gives a loss of 3.06, down from 12.25.

The rule at every step

Look at what each step of the backward pass did. It took the gradient arriving from the right, multiplied it by one local slope, and passed the result to the left. That is the whole method:

∂L∂ input  =  ∂L∂ output  ×  ∂ output∂ input\frac{\partial L}{\partial\,\text{input}} \;=\; \frac{\partial L}{\partial\,\text{output}} \;\times\; \frac{\partial\,\text{output}}{\partial\,\text{input}}

gradient passed back = gradient received × the local slope of this step

Each kind of step has its own simple local slope, and a network is built from only a few kinds.

StepWhat it does going forwardWhat it does going backward
Add a biasz=s+bz = s + bPasses the gradient through unchanged
Multiply by a weights=w xs = w\,xThe weight receives gradient × xx; the input receives gradient × ww
ReLUa=max⁡(0,z)a = \max(0, z)Passes the gradient where z>0z > 0, blocks it where z≤0z \le 0
Softmax with cross-entropyscores → lossStarts the whole process with probabilities − truth

Two details are worth pausing on. A weight’s gradient is proportional to its input: a weight attached to an input of zero receives no blame, because it had no effect on this example. And a ReLU that was off, with a negative input, blocks the gradient entirely. Nothing behind it learns from this example.

For a whole dense layer the same rules, written with matrices, are three lines:

∂L∂W=X⊤ ∂L∂Z∂L∂b=sum of ∂L∂Z over the batch∂L∂X=∂L∂Z W⊤\frac{\partial L}{\partial W} = X^\top \, \frac{\partial L}{\partial Z} \qquad \frac{\partial L}{\partial b} = \text{sum of } \frac{\partial L}{\partial Z} \text{ over the batch} \qquad \frac{\partial L}{\partial X} = \frac{\partial L}{\partial Z}\, W^\top

The first two are what the layer needs to update itself. The third is what it hands back to the layer before it, which uses it in exactly the same way. Each layer only needs to know its own inputs and the gradient arriving from the layer after it. That is why the method scales to networks of any depth.

Checkpoint

During a backward pass, a hidden ReLU neuron had a negative input on this example. What gradient do the weights feeding into it receive from this example?

ExampleA neuron that was switched off

Take the same tiny network, but start with a weight of −0.5. The input is 2, the bias is 0.5 and the target is 5.

Forward. z=−0.5×2+0.5=−0.5z = -0.5 \times 2 + 0.5 = -0.5. The ReLU turns that into a=0a = 0, and the loss is (0−5)2=25(0 - 5)^2 = 25.

Backward. The loss changes with aa at a rate of 2(0−5)=−102(0 - 5) = -10. Then comes the ReLU. Its input was negative, so its local slope is 0, and the gradient passed back is −10×0=0-10 \times 0 = 0. The weight and the bias both receive a gradient of 0.

The loss is large and the update is nothing. The neuron was off for this input, so no small change to its weight would alter the output, and backpropagation correctly reports that. If a neuron is off for every example in the data it can never recover. Such neurons are called dead, and they are one reason to keep starting weights small and learning rates moderate.

Trust, but check

Backward passes are easy to get subtly wrong, and a wrong gradient often still trains, just badly. Fortunately there is an independent way to find a gradient: the slow nudging method from the start of the chapter. Too slow for training, it is perfect for testing. Comparing the two is called a .

Figure

Backpropagation against brute force

Layer 1 weights
Layer 1 biases
Layer 2 weights
Layer 2 biases
From one backward pass
0.207647
By nudging w11 by 1e-3
0.207647
They differ by
5.9e-9
Loss of the network
1.7648
1e-3
21 learnable numbers: one backward pass gives all 21 gradients.
A tiny network with 21 learnable numbers. One backward pass produced a gradient for all of them. Try it: click different weights and compare the two numbers. Then make the nudge very large and watch the nudged estimate drift away.

The two agree to several decimal places for every weight. The nudge needs two runs of the network for each number checked; the backward pass produced all 21 at once. On a network with millions of weights, that difference is the difference between seconds and years.

Every network in this book is checked this way before it is used. So is the library that draws these figures.

The training loop

Everything is now in place. Training is four steps, repeated:

  1. Forward pass: run a batch through the network.
  2. Loss: measure how wrong the outputs are.
  3. Backward pass: find the gradient of the loss for every weight.
  4. Update: move every weight a small step against its gradient.

This cycle is the . One pass through all the training data is one .

For a real test we need data no straight line can handle. Here are 300 points in three classes, arranged in interleaved spiral arms. The network has 2 inputs, one hidden layer of 32 ReLU neurons, and 3 outputs: 195 learnable numbers.

Figure

A network learning the spiral

0, 00, 0.010, 0.020, 0.030, 0.040.04, 0.030.03, 0.050.04, 0.060.05, 0.070.08, 0.040.09, 0.040.11, 0.020.12, 0.030.1, 0.080.14, -0.020.14, 0.050.15, -0.050.17, -0.010.18, -0.020.19, 0.010.2, -0.030.2, -0.080.16, -0.150.22, -0.060.23, -0.090.22, -0.120.25, -0.070.16, -0.220.04, -0.28-0.03, -0.290.08, -0.290.04, -0.310.02, -0.32-0.08, -0.32-0.03, -0.34-0.1, -0.34-0.16, -0.330.04, -0.37-0.3, -0.24-0.22, -0.32-0.32, -0.25-0.05, -0.41-0.34, -0.25-0.26, -0.35-0.44, -0.07-0.31, -0.33-0.45, -0.12-0.46, 0.1-0.48, 0-0.49, -0.09-0.5, -0.07-0.51, -0.08-0.53, -0.01-0.53, -0.07-0.53, 0.12-0.56, -0.02-0.37, 0.43-0.4, 0.42-0.33, 0.48-0.27, 0.53-0.22, 0.57-0.29, 0.54-0.17, 0.6-0.23, 0.59-0.23, 0.6-0.03, 0.66-0.02, 0.670.32, 0.590.22, 0.650.14, 0.680.29, 0.650.62, 0.360.46, 0.560.35, 0.650.32, 0.670.71, 0.270.67, 0.380.78, 0.040.79, 0.020.79, 0.140.8, 0.140.81, 0.080.82, 0.070.82, 0.190.79, 0.30.84, 0.180.71, -0.50.88, 00.71, -0.530.49, -0.750.31, -0.860.89, -0.210.72, -0.590.46, -0.820.48, -0.82-0.06, -0.960.49, -0.830.46, -0.86-0.16, -0.98-0.36, -0.930, 00.01, -0.010.01, -0.010.02, -0.020.03, -0.020.04, -0.030.03, -0.050.04, -0.060.03, -0.070, -0.090.04, -0.090.05, -0.1-0.02, -0.12-0.07, -0.11-0.07, -0.12-0.01, -0.15-0.04, -0.16-0.07, -0.16-0.06, -0.17-0.15, -0.12-0.18, -0.1-0.12, -0.17-0.15, -0.17-0.21, -0.1-0.24, -0.06-0.25, -0.03-0.23, -0.13-0.26, -0.07-0.28, 0-0.29, -0.02-0.3, 0.06-0.31, 0.02-0.32, 0.06-0.24, 0.23-0.21, 0.27-0.31, 0.17-0.24, 0.27-0.32, 0.2-0.2, 0.32-0.19, 0.35-0.16, 0.37-0.02, 0.41-0.12, 0.41-0.17, 0.4-0.11, 0.43-0.05, 0.450.02, 0.460.04, 0.470.29, 0.390.27, 0.410.17, 0.480.4, 0.330.42, 0.310.33, 0.420.16, 0.520.5, 0.230.56, 0.090.47, 0.330.58, -0.070.59, -0.070.61, 00.61, 0.110.6, -0.160.59, -0.230.63, -0.150.64, -0.160.64, 0.20.67, -0.110.27, -0.630.4, -0.570.47, -0.520.44, -0.560.42, -0.590.29, -0.680.29, -0.69-0.1, -0.75-0.18, -0.75-0.04, -0.780.14, -0.77-0.4, -0.690.09, -0.8-0.46, -0.67-0.47, -0.68-0.69, -0.48-0.37, -0.76-0.77, -0.38-0.62, -0.61-0.6, -0.65-0.72, -0.53-0.85, -0.28-0.89, -0.16-0.83, -0.39-0.83, 0.41-0.93, 0.12-0.94, 0.16-0.91, 0.3-0.92, 0.31-0.93, 0.3-0.89, 0.43-0.99, 0.10, 0-0.01, 0-0.02, -0.01-0.03, 0-0.04, 0.01-0.05, -0.01-0.06, -0.01-0.07, 0-0.07, 0.04-0.03, 0.08-0.1, 0.03-0.11, 0.03-0.06, 0.11-0.12, 0.05-0.04, 0.14-0.1, 0.110.01, 0.160, 0.17-0.02, 0.18-0.03, 0.19-0.05, 0.20, 0.21-0.07, 0.21-0.03, 0.230.06, 0.23-0.01, 0.250.03, 0.260.15, 0.230, 0.280.18, 0.230.07, 0.290.24, 0.20.24, 0.220.32, 0.080.3, 0.170.35, 0.010.32, 0.170.37, 0.040.37, 0.090.39, -0.080.38, -0.140.4, -0.120.42, -0.060.42, -0.110.44, -0.080.09, -0.450.21, -0.410.42, -0.220.46, -0.160.27, -0.420.26, -0.430.05, -0.510.42, -0.320.03, -0.53-0.08, -0.540.22, -0.510.21, -0.53-0.29, -0.5-0.12, -0.57-0.41, -0.43-0.3, -0.53-0.27, -0.56-0.41, -0.47-0.49, -0.4-0.62, -0.18-0.58, -0.32-0.24, -0.62-0.68, 0.04-0.61, -0.32-0.7, -0.04-0.68, -0.18-0.71, 0.08-0.68, -0.26-0.74, -0.04-0.72, 0.19-0.72, 0.22-0.74, 0.22-0.49, 0.6-0.69, 0.39-0.39, 0.7-0.73, 0.34-0.68, 0.460.03, 0.83-0.45, 0.71-0.09, 0.84-0.21, 0.83-0.22, 0.84-0.44, 0.760.23, 0.86-0.39, 0.810.25, 0.870.22, 0.890.67, 0.650.32, 0.880.71, 0.630.83, 0.470.64, 0.730.34, 0.920.89, 0.430.76, 0.65
  • Class 1, and where the network predicts it
  • Class 2, and where the network predicts it
  • Class 3, and where the network predicts it
Steps
0
Loss
1.173
Right on the 300 shown
32%
Right on 300 new points
34%
Left: the three classes, and the region the network currently assigns to each. Right: the loss after each batch of training steps. Try it: press Step a few times to see single updates, then Train. Watch the coloured regions begin to follow the arms.

It works, and it is slow. After 2,000 steps the loss has fallen from 1.17 to about 0.79 and the network gets 62% of the points right, up from a third. The regions are starting to curl around the arms, but the loss spends long stretches barely moving.

The network is learning, driven by nothing but the four steps above. The slowness is not a flaw in backpropagation, which is giving exact gradients. It is a flaw in how we are using them: always the same step size, in whatever direction the gradient happens to point. The next chapter fixes that, and the same network will reach 99%.

Checkpoint

Put the four steps of the training loop in the right order.

In code

Each layer gains a backward method that mirrors its forward. The full file, code/ch17_backprop.py (run it in Colab), trains this network on spiral data.

class Layer_Dense:
    def forward(self, inputs):
        self.inputs = inputs                               # remembered for the backward pass
        self.output = inputs @ self.weights + self.biases

    def backward(self, dvalues):
        self.dweights = self.inputs.T @ dvalues            # each weight: its input times the gradient
        self.dbiases = np.sum(dvalues, axis=0, keepdims=True)
        self.dinputs = dvalues @ self.weights.T            # handed back to the previous layer

class Activation_ReLU:
    def backward(self, dvalues):
        self.dinputs = dvalues.copy()
        self.dinputs[self.inputs <= 0] = 0                 # blocked where the input was negative

for epoch in range(10001):
    dense1.forward(X)                                      # forward pass
    activation1.forward(dense1.output)
    dense2.forward(activation1.output)
    loss = loss_activation.forward(dense2.output, y)       # loss

    loss_activation.backward(y)                            # backward pass, last layer first
    dense2.backward(loss_activation.dinputs)
    activation1.backward(dense2.dinputs)
    dense1.backward(activation1.dinputs)

    optimizer.update_params(dense1)                        # update
    optimizer.update_params(dense2)

Run for 10,000 epochs with plain gradient descent, the Python version climbs from a loss of 1.099 and 36% accuracy to a loss of 0.134 and 95%.

Key Takeaways

  • Training needs the slope of the loss for every weight. Nudging each weight in turn is far too slow.
  • Backpropagation gets all the slopes from one forward pass and one backward pass.
  • At each step: gradient passed back = gradient received × local slope. That is the chain rule.
  • A weight’s gradient is proportional to its input, and a ReLU that was off blocks the gradient.
  • The training loop is forward, loss, backward, update. Check a new backward pass against nudging.
You can now
  • Carry out a forward and a backward pass through a small network by hand.
  • State the rule that every backward step follows.
  • Explain why a ReLU that was off passes no gradient.
  • Check a backward pass against nudging, and write the four steps of the training loop.

Exercises

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby hand

One neuron with a ReLU: the input is 3, the weight is 1, the bias is −1, and the target is 4. The loss is the squared error. Do the forward pass, then the backward pass, then update the weight and bias with a learning rate of 0.02. What is the loss after the update?

Hint

Forward: zz, then aa, then the loss. Backward: start with 2(a−4)2(a - 4) and multiply by each local slope in turn.

Solution

Forward. z=1×3−1=2z = 1 \times 3 - 1 = 2. The ReLU leaves it at a=2a = 2. The loss is (2−4)2=4(2 - 4)^2 = 4.

Backward. The loss changes with aa at 2(2−4)=−42(2 - 4) = -4. The ReLU was on, so its slope is 1 and the gradient stays −4-4. For the weight, multiply by the input: −4×3=−12-4 \times 3 = -12. For the bias, multiply by 1: −4-4.

Update. w=1+0.02×12=1.24w = 1 + 0.02 \times 12 = 1.24 and b=−1+0.02×4=−0.92b = -1 + 0.02 \times 4 = -0.92.

Check. The new output is 1.24×3−0.92=2.81.24 \times 3 - 0.92 = 2.8, and the loss is (2.8−4)2=1.44(2.8 - 4)^2 = 1.44, down from 4.

Exerciseby hand

Two neurons in a chain, with no biases. The first computes h=ReLU(w1x)h = \text{ReLU}(w_1 x) and the second computes y=w2hy = w_2 h. With x=1x = 1, w1=2w_1 = 2, w2=3w_2 = 3 and a target of 0, the loss is y2y^2. Find the gradient for w2w_2, then for w1w_1.

Hint

Start with how the loss changes with yy, which is 2y2y. A weight’s local slope is the input it multiplies.

Solution

Forward. h=ReLU(2)=2h = \text{ReLU}(2) = 2, y=3×2=6y = 3 \times 2 = 6, and the loss is 36.

Backward. The loss changes with yy at 2y=122y = 12.

For w2w_2: its local slope is its input, h=2h = 2. The gradient is 12×2=2412 \times 2 = 24.

To go further back, find how the loss changes with hh: the local slope is w2=3w_2 = 3, so 12×3=3612 \times 3 = 36. The ReLU was on, so the gradient stays 36. For w1w_1 the local slope is its input, x=1x = 1, giving 36×1=3636 \times 1 = 36.

Both gradients are positive, so both weights should decrease, which makes sense: the output is 6 and the target is 0. Notice that the gradient for w1w_1 had to pass through w2w_2 on the way. That is why the old value of w2w_2 must be kept until the backward pass is finished.

Exercisethink

A network has 10,000 weights. To find the gradient by nudging each weight in turn, how many forward passes are needed for one update? How many passes does backpropagation need?

Hint

Nudging needs one extra forward pass for every weight.

Solution

Nudging needs one forward pass to measure the loss as it stands, and one more for each weight: 10,001 forward passes. If each weight is nudged both up and down for a better estimate, it is 20,000.

Backpropagation needs one forward pass and one backward pass, and the backward pass costs about as much as the forward one. That is a saving of several thousand times here. For a modern network with billions of weights, it is the difference between possible and impossible.

Exercisein code

Check the chapter’s worked example with code. The neuron computes a=ReLU(wx+b)a = \text{ReLU}(wx + b) with x=2x = 2, b=0.5b = 0.5 and a target of 5, and backpropagation gave a gradient of −14 for the weight at w=0.5w = 0.5. Estimate the same gradient by nudging.

Hint

Write the loss as a function of ww. Evaluate it just above and just below 0.5, subtract, and divide by the gap.

Solution
def loss(w, b=0.5, x=2, target=5):
    a = max(0, w * x + b)       # ReLU
    return (a - target) ** 2

h = 1e-5
estimate = (loss(0.5 + h) - loss(0.5 - h)) / (2 * h)
print(round(estimate, 4))       # -14.0

Nudging the weight up and down by a tiny amount and dividing gives −14, the same as the chain rule. When the two agree to several decimal places, the backward pass is right.

Exercisewith the figure

In the figure “Backpropagation against brute force”, pick a weight and compare the two numbers with a small nudge. Then make the nudge very large. Which number changes, and why is the other one unaffected?

Hint

Only one of the two methods uses the nudge at all.

Solution

With a small nudge the two numbers agree to several decimal places. With a very large nudge the nudged estimate drifts away, and the backpropagated gradient stays exactly where it was.

Backpropagation computes the slope at the point itself using the chain rule, and no nudge is involved. The nudging method measures the average slope across the gap it opened. For a small gap that is the same thing. For a large one, the loss curves within the gap and the average is no longer the slope at the point.

Going further

Why “backward”?

The gradient of the loss with respect to a layer’s output is needed by every weight in that layer and by everything before it. Starting at the loss and working backward computes each of these shared quantities exactly once and reuses it. Going forward from each weight would recompute the same later steps again and again.

Automatic differentiation

Libraries such as PyTorch and JAX do not ask you to write backward methods. They record every operation of the forward pass and replay the record backward, applying each step’s local slope automatically. It is the same algorithm as in this chapter, generalised to any calculation built from known pieces.

Vanishing gradients

The gradient reaching the first layer is a product of one local slope per layer. If those slopes are mostly smaller than 1, as they are for saturated sigmoids, the product shrinks toward zero and the early layers barely learn. This problem held deep networks back for years. ReLU, whose slope is exactly 1 when it is on, is a large part of what solved it.

References and further reading

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 17.1Who is to blame?
  3. 17.2One neuron, forwards then backwards
  4. 17.3The rule at every step
  5. 17.4Trust, but check
  6. 17.5The training loop
  7. 17.6In code
  8. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in