Skip to content

MLDay 30 of 50Deep Learning

Backpropagation by Hand

A network's prediction misses, and each of its weights played a part.

7 min read

A network's prediction misses, and each of its weights played a part. To learn, it needs each weight's share of the blame. Nudging one weight at a time costs extra runs for every weight. Backpropagation gets every share from one pass backward through the network.

The idea

A network is a chain of small steps (drawn as a computational graph, as below): a weight changes a hidden value, which changes the prediction, which changes the loss. Each step has a local slope: how much its output moves when its input moves by 1. The slope of the whole chain is the product of the local slopes along it.

Backpropagation walks the chain from the loss back to each weight, multiplying local slopes as it goes. The result is the weight's gradient, the slope of the loss with respect to that weight, which gradient descent uses to update it (D09). The slopes near the loss are shared by every weight, so each is computed once.

A tiny example

Take the smallest network with layers: one hidden neuron, one output neuron, no biases. The hidden neuron computes h=ReLU(w1x)h = \text{ReLU}(w_1 x), where ReLU (from D29) turns negative numbers into 0. The output is y^=w2h\hat{y} = w_2 h, and the loss is L=(y^−y)2L = (\hat{y} - y)^2. Use one example, x=3x = 3 and y=4y = 4, with w1=2w_1 = 2 and w2=0.5w_2 = 0.5.

Forward pass (left to right, keeping every value):

Step Calculation Value
the score z=w1xz = w_1 x 2×32 \times 3 6
hidden output h=ReLU(z)h = \text{ReLU}(z) zz is positive, so it passes 6
prediction y^=w2h\hat{y} = w_2 h 0.5×60.5 \times 6 3
loss L=(y^−y)2L = (\hat{y} - y)^2 (3−4)2(3 - 4)^2 1

Backward pass (right to left, one local slope per step):

Local slope Rule Value
loss vs. prediction 2(y^−y)=2(3−4)2(\hat{y} - y) = 2(3 - 4) −2
prediction vs. hh y^=w2h\hat{y} = w_2 h, so the slope is w2w_2 0.5
hh vs. zz ReLU's slope: 1, since z>0z > 0 1
zz vs. w1w_1 z=w1xz = w_1 x, so the slope is xx 3

Multiply them: the gradient for w1w_1 is (−2)(0.5)(1)(3)=−3(-2)(0.5)(1)(3) = -3. The chain for w2w_2 is shorter. The prediction moves with w2w_2 at rate h=6h = 6, so its gradient is (−2)(6)=−12(-2)(6) = -12. Both are negative, so raising either weight lowers the loss.

One update with learning rate η=0.01\eta = 0.01 gives w1=2−0.01×(−3)=2.03w_1 = 2 - 0.01 \times (-3) = 2.03 and w2=0.5−0.01×(−12)=0.62w_2 = 0.5 - 0.01 \times (-12) = 0.62.

The formula

The chain rule gives a weight's gradient as the product of the local slopes between it and the loss:

∂L∂w1=∂L∂y^⋅∂y^∂h⋅∂h∂w1\frac{\partial L}{\partial w_1} = \frac{\partial L}{\partial \hat{y}} \cdot \frac{\partial \hat{y}}{\partial h} \cdot \frac{\partial h}{\partial w_1}
Symbol Meaning
LL the loss, (y^−y)2(\hat{y} - y)^2
w1w_1 the hidden neuron's weight
hh the hidden output, ReLU(w1x)\text{ReLU}(w_1 x)
y^\hat{y} the prediction, w2hw_2 h
∂a/∂b\partial a / \partial b the slope of aa when only bb changes

Worked: ∂L∂w1=(−2)(0.5)(3)=−3\frac{\partial L}{\partial w_1} = (-2)(0.5)(3) = -3.

To check a hand-derived gradient, estimate it numerically: nudge the weight a tiny step each way and measure how the loss moves. This gradient check needs no calculus, so it catches mistakes in the backward pass:

∂L∂w≈L(w+ε)−L(w−ε)2ε\frac{\partial L}{\partial w} \approx \frac{L(w + \varepsilon) - L(w - \varepsilon)}{2\varepsilon}
Symbol Meaning
ww the weight being checked; all others stay fixed
ε\varepsilon a tiny step, such as 0.001
L(w±ε)L(w \pm \varepsilon) the loss from a forward pass with the weight nudged up or down

Worked, for w1=2w_1 = 2 and ε=0.001\varepsilon = 0.001: 0.997002−1.0030020.002=−3\frac{0.997002 - 1.003002}{0.002} = -3, the same as backpropagation.

Try it

Step through backprop

One example: x = 3, y = 4. Change a weight and watch every number update, or take steps downhill.

forward z = w1·x6
h = ReLU(z)6
ŷ = w2·h3
loss (ŷ − y)²1
∂L/∂ŷ = 2(ŷ − y)-2
∂ŷ/∂h = w20.5
∂h/∂z (ReLU slope)1
∂z/∂w1 = x3

∂L/∂w1 = (-2)·(0.5)·(1)·(3) = -3

∂L/∂w2 = (-2)·(h = 6) = -12

Each step: w ← w − η·gradient

Check the slopes against the tables above, then click Take a step a few times. The prediction climbs from 3 toward 4, and the gradients shrink toward 0 as the miss disappears. Then press Reset and drag the weights: push w2w_2 to 1 and watch the gradient for w1w_1 flip sign, or pull w1w_1 below 0 and watch ReLU cut it off.

In code

The backward pass is three lines, and the gradient check referees it:

# script_id: day_030_backpropagation_by_hand/backprop
x, y = 3.0, 4.0


def loss(w1: float, w2: float) -> float:
    return (w2 * max(w1 * x, 0.0) - y) ** 2


def backprop(w1: float, w2: float) -> tuple[float, float]:
    z = w1 * x                                # forward pass, keeping each value
    h = max(z, 0.0)                           # ReLU
    y_hat = w2 * h
    d_yhat = 2 * (y_hat - y)                  # backward: slope of the loss
    d_w1 = d_yhat * w2 * (1.0 if z > 0 else 0.0) * x  # times the slopes of w2*h, ReLU, w1*x
    return d_w1, d_yhat * h                   # dL/dw1, dL/dw2


g1, g2 = backprop(2.0, 0.5)
eps = 1e-3
n1 = (loss(2.0 + eps, 0.5) - loss(2.0 - eps, 0.5)) / (2 * eps)
n2 = (loss(2.0, 0.5 + eps) - loss(2.0, 0.5 - eps)) / (2 * eps)
print(f"dL/dw1: backprop {g1:+.6f}, numeric {n1:+.6f}")
print(f"dL/dw2: backprop {g2:+.6f}, numeric {n2:+.6f}")
w1, w2 = 2.0 - 0.01 * g1, 0.5 - 0.01 * g2
print(f"after one step: w1 = {w1:.2f}, w2 = {w2:.2f}, loss = {loss(w1, w2):.4f}")
dL/dw1: backprop -3.000000, numeric -3.000000
dL/dw2: backprop -12.000000, numeric -12.000000
after one step: w1 = 2.03, w2 = 0.62, loss = 0.0503

One step cuts the loss from 1 to 0.0503.

Quick check

Quick check

1. Keep x = 3, y = 4 and w1 = 2, but set w2 = 1. What is dL/dw1?

2. With x = 3 and w1 = -1, what gradient does w1 get?

3. Backprop says -1.5, but the gradient check says -3.000000. What is most likely?

Next

In D31: PyTorch Basics: Tensors and Autograd, PyTorch runs this backward pass for you: one call to .backward() fills in every gradient.

Next · Day 31 · 6 minPyTorch Basics: Tensors and Autograd← Previous: Day 29 · From Neurons to a Multilayer Perceptron
Not tapped yet