A neural network learns by adjusting thousands of weights. To do that, it needs to know how each weight affects the error. Backpropagation works this out in one backward sweep through the network using the chain rule. In this lesson you will do it by hand for a tiny network, check it with a numerical test, and then train a small network on a problem a straight line cannot solve.
In this lesson you will learn
- What the forward pass and the backward pass do
- How the chain rule passes the error back through each layer
- How to check gradients with a numerical test
- How to train a two-layer network on XOR in NumPy
- Why starting weights can decide whether training succeeds
You should know neural network basics and gradient descent. Some idea of a derivative helps but is not required.
The Idea: Blame Flows Backwards
Think of a factory line with three workers. The final product is faulty. To fix it, you trace back: how much did the last worker add to the fault, then the worker before, and so on. Each worker’s share depends on what happened after them.
A network is the same. The forward pass pushes an input through the layers to get a prediction and a loss. The backward pass starts at the loss and moves back, layer by layer, working out each weight’s share of the error. That share is the gradient. Gradient descent then nudges each weight against it.
The Chain Rule on a Tiny Network
Our network has one input, one hidden neuron and one output neuron, both using the sigmoid function. We want the output to be 1.
import numpy as np
def sigmoid(z):
return 1 / (1 + np.exp(-z))
# One input, one hidden neuron, one output neuron
x, target = 2.0, 1.0
w1, b1, w2, b2 = 0.5, 0.0, -1.0, 0.0
# Forward pass: compute and remember every middle value
z1 = w1 * x + b1; h = sigmoid(z1)
z2 = w2 * h + b2; out = sigmoid(z2)
loss = (out - target) ** 2
print(f"h={h:.4f} out={out:.4f} loss={loss:.4f}")
# Backward pass: chain rule, from the loss back to each weight
d_out = 2 * (out - target) # d loss / d out
d_z2 = d_out * out * (1 - out) # sigmoid'(z) = s(1 - s)
d_w2 = d_z2 * h
d_h = d_z2 * w2
d_z1 = d_h * h * (1 - h)
d_w1 = d_z1 * x
print(f"backprop : dL/dw1={d_w1:.6f} dL/dw2={d_w2:.6f}")
# Gradient check: nudge each weight a tiny bit and watch the loss
def loss_with(w1, w2):
o = sigmoid(w2 * sigmoid(w1 * x + b1) + b2)
return (o - target) ** 2
eps = 1e-6
num_w1 = (loss_with(w1 + eps, w2) - loss_with(w1 - eps, w2)) / (2 * eps)
num_w2 = (loss_with(w1, w2 + eps) - loss_with(w1, w2 - eps)) / (2 * eps)
print(f"numerical: dL/dw1={num_w1:.6f} dL/dw2={num_w2:.6f}")
Output
h=0.7311 out=0.3250 loss=0.4557
backprop : dL/dw1=0.116455 dL/dw2=-0.216507
numerical: dL/dw1=0.116455 dL/dw2=-0.216507
- The forward pass gives an output of 0.325, far from the target of 1. The loss is 0.4557.
- Going back, each line multiplies the gradient so far by one more local slope. This is the chain rule: a change in
w1changesz1, which changesh, which changesz2, which changes the output and the loss. You multiply the slopes of each link. - The slope of the sigmoid is
s × (1 − s). We storedhandoutin the forward pass, so the backward pass reuses them instead of recomputing. dL/dw2is negative, so raisingw2lowers the loss.dL/dw1is positive, sow1should go down. That makes sense:w2is −1, so a largerhcurrently pushes the output the wrong way.
Gradient Checking
Backprop code is easy to get subtly wrong. The bottom of bp1.py checks it. We nudge one weight up by a tiny amount, then down, and measure how much the loss changes. This numerical slope is slow but hard to get wrong. Both methods agree to six decimal places, so our backward pass is correct.
Training a Network on XOR
XOR outputs 1 when exactly one of two inputs is 1. You cannot draw one straight line that separates the 1s from the 0s, so logistic regression fails. A hidden layer fixes this. We use 4 hidden neurons with tanh and one sigmoid output, and we process all four rows at once with matrices.
import numpy as np
# XOR: output is 1 when exactly one input is 1. No straight line separates it.
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=float)
y = np.array([[0], [1], [1], [0]], dtype=float)
rng = np.random.default_rng(1)
W1 = rng.normal(0, 1, (2, 4)); b1 = np.zeros(4) # 2 inputs -> 4 hidden
W2 = rng.normal(0, 1, (4, 1)); b2 = np.zeros(1) # 4 hidden -> 1 output
sigmoid = lambda z: 1 / (1 + np.exp(-z))
lr = 1.0
for epoch in range(1, 5001):
# forward
H = np.tanh(X @ W1 + b1)
P = sigmoid(H @ W2 + b2)
loss = -np.mean(y * np.log(P) + (1 - y) * np.log(1 - P)) # log loss
# backward (log loss + sigmoid gives the simple error P - y)
dZ2 = (P - y) / len(X)
dW2 = H.T @ dZ2; db2 = dZ2.sum(axis=0)
dZ1 = (dZ2 @ W2.T) * (1 - H ** 2) # tanh' = 1 - tanh^2
dW1 = X.T @ dZ1; db1 = dZ1.sum(axis=0)
# update
W2 -= lr * dW2; b2 -= lr * db2
W1 -= lr * dW1; b1 -= lr * db1
if epoch in (1, 100, 1000, 5000):
print(f"epoch {epoch:4}: loss {loss:.4f}")
print("predictions:", P.ravel().round(3))
print("rounded :", (P.ravel() > 0.5).astype(int), " target:", y.ravel().astype(int))
Output
epoch 1: loss 0.6712
epoch 100: loss 0.0385
epoch 1000: loss 0.0024
epoch 5000: loss 0.0005
predictions: [0. 0.999 0.999 0.001]
rounded : [0 1 1 0] target: [0 1 1 0]
- The loss falls from 0.67 to 0.0005, and all four predictions round to the right answer.
- With log loss and a sigmoid output, the output gradient simplifies to
P − y. That is why the backward pass starts so simply. dZ2 @ W2.Tsends the error back through the output weights to each hidden neuron. Multiplying by1 − H², the slope oftanh, finishes the trip through the hidden layer.- Each weight gradient is “input to the layer, transposed” times “error at the layer”:
H.T @ dZ2andX.T @ dZ1.
| Activation | Value | Slope used in backprop |
|---|---|---|
| Sigmoid | 1 / (1 + e−z) | s × (1 − s) |
| tanh | tanh(z) | 1 − tanh² |
| ReLU | max(0, z) | 1 if z > 0, else 0 |
Starting weights matter
With default_rng(0) instead of default_rng(1), this same network gets stuck. Its loss stays near 0.35, and for two of the four rows it can only answer 0.5, a pure guess. Some random starts land in a poor valley of the loss surface. Libraries reduce this with careful starting weights, more hidden neurons and better optimisers such as Adam.
Common Mistakes
- Mixing up shapes. A weight gradient must have the same shape as the weight. Print shapes when in doubt.
- Using the wrong activation slope. Each layer needs the slope of its own activation.
- Skipping the gradient check. A wrong sign or a missing term may still let the loss fall slowly, which hides the bug.
- Starting all weights at zero. Every hidden neuron then gets the same gradient and they stay identical forever. Use small random values.
Practice Exercises
Exercise 1. In bp1.py, add the gradient for b2 and check it numerically.
Show answer
Since z2 = w2·h + b2, the slope of z2 with respect to b2 is 1, so d_b2 = d_z2. For the check, write a loss function that takes b2 and nudge it by ±1e-6 as before. Both should give about −0.296.
Exercise 2. Replace tanh in bp2.py with ReLU. Which two lines change?
Show answer
H = np.maximum(0, X @ W1 + b1)
dZ1 = (dZ2 @ W2.T) * (H > 0)
The forward line uses ReLU, and the backward line uses its slope: 1 where the neuron was active, 0 elsewhere.
Frequently Asked Questions
Is backpropagation the same as gradient descent?
No. Backpropagation computes the gradients. Gradient descent, or an optimiser like Adam, uses those gradients to update the weights. Training needs both.
Do I need to write backprop myself in practice?
No. PyTorch, TensorFlow and JAX compute gradients automatically. Writing it once helps you understand vanishing gradients, activation choices and shape errors when they happen.
Summary
- The forward pass computes the prediction and stores middle values.
- The backward pass applies the chain rule from the loss back to every weight.
- A numerical gradient check catches backprop bugs.
- A hidden layer lets a network solve XOR, which no straight line can.
Next: t-SNE in Python.
