Backpropagation is how neural networks learn. It uses the chain rule from calculus to compute how much each weight contributed to the error, then gradient descent adjusts every weight a little in the right direction.
What You Will Learn
- Forward pass and backward pass
- The chain rule applied layer by layer
- Train a network on XOR from scratch in NumPy
- Verify gradients numerically
- What frameworks automate
Prerequisites
Activation Functions, Loss Functions.
The Four Steps
- Forward pass: compute predictions layer by layer.
- Loss: measure the error.
- Backward pass: from the output backwards, compute the gradient of the loss with respect to every weight using the chain rule.
- Update: w ← w − learning_rate × gradient. Repeat.
A Network That Learns XOR
XOR cannot be solved by a single straight line, so it needs a hidden layer – the classic test for backpropagation.
import numpy as np
rng = np.random.default_rng(1)
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]], float)
y = np.array([[0], [1], [1], [0]], float)
W1, b1 = rng.normal(0, 1, (2, 4)), np.zeros((1, 4)) # 2 inputs -> 4 hidden
W2, b2 = rng.normal(0, 1, (4, 1)), np.zeros((1, 1)) # 4 hidden -> 1 output
sigmoid = lambda z: 1 / (1 + np.exp(-z))
lr = 1.0
for epoch in range(5001):
# forward
h = np.tanh(X @ W1 + b1)
out = sigmoid(h @ W2 + b2)
loss = -np.mean(y * np.log(out) + (1 - y) * np.log(1 - out))
# backward (chain rule)
d_out = (out - y) / len(X) # dLoss/dz2 for sigmoid + cross-entropy
dW2, db2 = h.T @ d_out, d_out.sum(0, keepdims=True)
d_h = (d_out @ W2.T) * (1 - h ** 2) # back through tanh
dW1, db1 = X.T @ d_h, d_h.sum(0, keepdims=True)
# update
W2 -= lr * dW2; b2 -= lr * db2; W1 -= lr * dW1; b1 -= lr * db1
if epoch % 1000 == 0:
print(epoch, round(loss, 4))
print(out.round(3).ravel())
0 0.6712 1000 0.0024 2000 0.0012 3000 0.0008 4000 0.0006 5000 0.0005 [0. 0.999 0.999 0.001]
Explanation: Loss falls from 0.67 (random guessing) to 0.0005, and the outputs match XOR: 0, 1, 1, 0. Key lines: for sigmoid + cross-entropy the output gradient simplifies to out − y; the gradient flows back through W2 and is multiplied by tanh’s derivative 1 − h²; each weight gradient is “input to the layer” transposed times “gradient arriving at the layer”.
Check the Gradient Numerically
rng = np.random.default_rng(1)
W1, b1 = rng.normal(0, 1, (2, 4)), np.zeros((1, 4))
W2, b2 = rng.normal(0, 1, (4, 1)), np.zeros((1, 1))
def loss_fn(W2):
out = sigmoid(np.tanh(X @ W1 + b1) @ W2 + b2)
return -np.mean(y * np.log(out) + (1 - y) * np.log(1 - out))
h = np.tanh(X @ W1 + b1); out = sigmoid(h @ W2 + b2)
analytic = (h.T @ ((out - y) / len(X)))[0, 0]
E = np.zeros_like(W2); E[0, 0] = 1e-5
numeric = (loss_fn(W2 + E) - loss_fn(W2 - E)) / 2e-5
print(round(analytic, 6), round(numeric, 6))
0.01166 0.01166
Explanation: The backprop formula and a finite-difference estimate agree, proving the derivation is correct. Gradient checking is a standard way to debug hand-written backward passes.
What Frameworks Do
import torch
x = torch.tensor(2.0, requires_grad=True)
y = x ** 3 + 2 * x
y.backward() # automatic differentiation
print(x.grad) # 3x² + 2 = 14
Explanation: PyTorch and TensorFlow build a computation graph during the forward pass and run backpropagation automatically (autodiff). You only define the forward pass and the loss.
Common Problems
| Problem | Cause | Fix |
|---|---|---|
| Vanishing gradients | Saturating activations, deep nets | ReLU/GELU, residual connections, normalisation |
| Exploding gradients | Large weights, long RNN chains | Gradient clipping, lower learning rate, good initialisation |
| Loss not decreasing | Learning rate too high/low, bug | Tune lr, gradient check, overfit a tiny batch first |
Series
Deep learning series: Intro to DL · ANN · Activation Functions · Loss Functions · Backpropagation · Optimizers · Dropout & BatchNorm · CNN · RNN · LSTM & GRU · Transfer Learning · Autoencoders · GANs · PyTorch vs TensorFlow
Interview Questions
Q: What is backpropagation?
An algorithm that applies the chain rule backwards through the network to compute the gradient of the loss with respect to each weight.
Q: Why does the output gradient become out − y?
The derivative of cross-entropy combined with sigmoid (or softmax) simplifies to prediction minus target.
Q: What is gradient checking?
Comparing analytic gradients with numerical finite-difference estimates to find bugs.
Practice Exercises
- Change the hidden activation to ReLU and update the backward pass.
- Try 2 hidden units and different seeds – does it always learn XOR?
Summary
Forward pass → loss → backward pass with the chain rule → gradient-descent update. Frameworks automate the backward pass, but understanding it helps you debug training.
Machine Learning Tutorials, Courses and Certifications