Neural Networks and Backpropagation
Build intuition for neurons, activations, forward passes and backpropagation, work a backward pass by hand, then train a small network from scratch in NumPy.
In Module 5 (Machine Learning) you fit models like logistic regression by minimizing a loss with gradient descent, and in Module 2 (Math for AI) you met the chain rule. A neural network is what you get when you combine those two ideas and keep stacking. Deep learning powers image recognition, speech transcription and the large language models you have been prompting, yet at its core there are only three ingredients: weighted sums, simple non-linear functions, and an efficient way to compute how every one of millions of weights should move. By the end of this lesson you will have done a backward pass by hand and trained a network from scratch with nothing but NumPy.
From linear models to neurons
A single neuron computes a weighted sum of its inputs plus a bias (the pre-activation ), then applies an activation function to produce its output :
Without this is just linear regression. With a step function it is the 1950s perceptron, which draws one straight boundary through input space. That is why a single perceptron cannot learn XOR: no single line separates XOR's positive and negative cases.
The fix is to arrange neurons into layers. A layer applies many neurons to the same input at once, which is a matrix multiply: , where has one column per neuron. A multi-layer perceptron (MLP) chains layers: the hidden layers build new features out of earlier ones, and the output layer turns the final features into predictions.
Why non-linearity is essential
Stack two linear layers: . The product is just another matrix, so the "deep" network is secretly a single linear layer. Any depth of purely linear layers collapses this way. The activation function breaks the collapse, letting each layer bend and fold the space so that later layers can separate classes that were tangled together at the input.
The universal approximation theorem says a network with one sufficiently wide hidden layer can approximate any continuous function on a bounded domain. That is reassuring but not very useful in practice: it says nothing about how many neurons you need or whether gradient descent will find the weights. Empirically, depth is far more parameter-efficient than width, because each layer can reuse features computed by the layer below.
Activation functions
| Activation | Formula | Where you see it |
|---|---|---|
| Sigmoid | Binary output probabilities, gates inside LSTMs. Saturates for large positive or negative inputs, so gradients vanish. | |
| Tanh | Older RNNs. Zero-centred but also saturates. | |
| ReLU | The default for CNNs and MLPs for a decade. Cheap, does not saturate for . Units can "die". | |
| GELU | ( = Gaussian CDF) | BERT, GPT-2 and many transformers. A smooth ReLU. |
| SiLU / Swish | Inside the SwiGLU blocks of most current LLMs (Module 7, Transformers & LLMs). | |
| Softmax | Output layer for multi-class classification and next-token prediction. |
The trend over time has been away from saturating functions (sigmoid, tanh), whose derivative is near zero across most of their range, towards functions whose derivative stays near 1 for positive inputs. The reason becomes clear once you see how gradients are computed.
The forward pass and the loss
For a two-layer classifier with classes the forward pass computes hidden pre-activations, hidden features, one logit per class, predicted probabilities, and the cross-entropy loss for the true class :
Cross-entropy punishes confident wrong answers heavily: predicting 0.01 for the true class costs , while 0.9 costs only about 0.1. A useful sanity check: an untrained classifier that outputs roughly uniform probabilities should have a loss near (about 1.10 for three classes). If your initial loss is far from that, something is wrong before training even starts.
Backpropagation: the chain rule, organized
Training needs for every parameter . Backpropagation (popularized by Rumelhart, Hinton and Williams in 1986) is simply the chain rule applied in a clever order: start at the loss and walk backwards through the computation, multiplying local derivatives as you go. Each node only needs to know two things: the gradient arriving from above (the "upstream" gradient) and its own local derivative.
The solid arrows are the forward pass that produces the loss. The dotted arrows are the backward pass: each node receives the gradient of the loss with respect to its output and turns it into gradients for its inputs and its own parameters.
The key local rules are short:
- Softmax + cross-entropy: the gradient with respect to the logits is the prediction minus the one-hot label. It is elegant and numerically stable, which is why frameworks fuse these two operations.
- Linear layer with upstream gradient : the weight gradient is , the bias gradient sums over the batch, and is passed further back.
- ReLU: multiply the upstream gradient elementwise by the indicator . The gradient passes through unchanged where the unit was active and is blocked where it was not.
Here is the one-hot vector for the true class and is elementwise multiplication. Why is the softmax-plus-cross-entropy gradient so clean? Because , so : the log cancels the exponential.
Why this is efficient
A network with a million parameters would need a million extra forward passes to estimate gradients by nudging each weight. Backprop gets all of them in one backward pass that costs roughly two forward passes, because every intermediate gradient is computed once and reused by everything below it. This is reverse-mode automatic differentiation, and it is what PyTorch's loss.backward() does for you (lesson 3).
A worked example by hand
Take one ReLU neuron with input , weight , bias , target , and squared-error loss .
| Step | Computation | Value |
|---|---|---|
| Forward | 0.5 | |
| Forward | 0.5 | |
| Forward | 0.125 | |
| Backward | -0.5 | |
| Backward | -0.5 | |
| Backward | -1.0 | |
| Backward | -0.5 |
With learning rate 0.1, gradient descent updates and . The new output is , and the loss drops from 0.125 to 0.031. Notice that the weight moved more than the bias because its gradient was scaled by the input : inputs with large magnitude produce large weight gradients, one reason we normalize features.
Now watch the same process across a whole network: the forward pass pulses activations left to right, and the backward pass sends gradients right to left.
Training a network from scratch in NumPy
The code below trains a two-layer MLP to classify three interleaved spirals, a dataset no linear model can separate. Read the backward section line by line against the rules above: it is exactly those three rules.
import numpy as np
rng = np.random.default_rng(0)
# --- 1. Data: three interleaved spirals (not linearly separable) ---
def make_spirals(n_per_class=100, n_classes=3):
X, y = [], []
for c in range(n_classes):
r = np.linspace(0.0, 1.0, n_per_class)
t = np.linspace(c * 4, (c + 1) * 4, n_per_class) + rng.normal(0, 0.2, n_per_class)
X.append(np.c_[r * np.sin(t), r * np.cos(t)])
y.append(np.full(n_per_class, c))
return np.vstack(X), np.concatenate(y)
X, y = make_spirals()
N, D, H, K = X.shape[0], 2, 64, 3
# --- 2. Parameters (He initialization for ReLU layers) ---
W1 = rng.normal(0, np.sqrt(2 / D), (D, H)); b1 = np.zeros(H)
W2 = rng.normal(0, np.sqrt(2 / H), (H, K)); b2 = np.zeros(K)
def forward(X):
z1 = X @ W1 + b1 # (N, H) pre-activations
a1 = np.maximum(0, z1) # ReLU
logits = a1 @ W2 + b2 # (N, K)
return z1, a1, logits
def softmax(z):
z = z - z.max(axis=1, keepdims=True) # subtract max for numerical stability
e = np.exp(z)
return e / e.sum(axis=1, keepdims=True)
lr = 1.0
for step in range(3001):
# forward
z1, a1, logits = forward(X)
p = softmax(logits)
loss = -np.log(p[np.arange(N), y]).mean()
# backward: apply the chain rule layer by layer, output to input
dlogits = p.copy()
dlogits[np.arange(N), y] -= 1 # dL/dlogits = p - onehot(y)
dlogits /= N # because the loss is a mean over N examples
dW2 = a1.T @ dlogits; db2 = dlogits.sum(axis=0)
da1 = dlogits @ W2.T
dz1 = da1 * (z1 > 0) # ReLU passes gradient only where z1 > 0
dW1 = X.T @ dz1; db1 = dz1.sum(axis=0)
# gradient descent update
W1 -= lr * dW1; b1 -= lr * db1
W2 -= lr * dW2; b2 -= lr * db2
if step % 1000 == 0:
acc = (logits.argmax(axis=1) == y).mean()
print(f"step {step:4d} loss {loss:.3f} train acc {acc:.2f}")
Expected output: the loss starts near and falls below 0.05, with training accuracy around 0.99. A logistic regression on the same data tops out near chance-plus-a-bit, because the decision boundary must curl around the spirals.
Always check your gradients
Hand-written backward passes are easy to get subtly wrong, and a wrong gradient often still trains, just badly. The standard defence is a gradient check: compare the analytic gradient to a centred finite difference:
The centred version has error proportional to , much smaller than the one-sided version's error proportional to .
def loss_fn():
_, _, logits = forward(X)
return -np.log(softmax(logits)[np.arange(N), y]).mean()
# recompute the analytic gradient at the current parameters
z1, a1, logits = forward(X)
dlogits = softmax(logits); dlogits[np.arange(N), y] -= 1; dlogits /= N
dz1 = (dlogits @ W2.T) * (z1 > 0)
dW1 = X.T @ dz1
eps = 1e-5
i, j = 0, 3 # check one entry of W1
W1[i, j] += eps; L_plus = loss_fn()
W1[i, j] -= 2 * eps; L_minus = loss_fn()
W1[i, j] += eps # restore
numeric = (L_plus - L_minus) / (2 * eps)
print(f"analytic {dW1[i, j]:.8f} numeric {numeric:.8f}")
The two numbers should agree to several significant digits. Frameworks do this for you, but the habit pays off whenever you write a custom operation or loss.
Why deep networks are hard to train (a preview)
The backward pass multiplies local derivatives layer after layer. If those factors are typically smaller than 1, gradients shrink exponentially with depth (vanishing gradients); if larger than 1, they explode. Sigmoid's derivative is at most 0.25, so ten sigmoid layers can shrink a gradient by a factor of about a million (). Three families of fixes made deep learning work, and the next lesson covers each:
- Better activations and initialization (ReLU with He init keeps activation variance roughly constant across layers).
- Normalization layers that re-centre and re-scale activations.
- Residual connections , which give gradients an identity path straight through the network.
Common pitfalls and misconceptions
- "Neurons work like brain cells." The inspiration is historical. Artificial neurons are differentiable functions, and their power comes from optimization at scale, not biological realism.
- Forgetting the batch reduction. If the loss is a mean, the gradient must be divided by
N. A gradient that is off by exactlyNis the giveaway. - Initializing all weights to zero. Every hidden unit then computes the same thing and receives the same gradient, so they never differentiate. Random initialization breaks this symmetry.
- Exploding loss to
nan. Usually a learning rate that is too high, or computingexpof large logits without subtracting the max first. - Dead ReLUs. A unit whose pre-activation is negative for every input gets zero gradient forever. Watch the fraction of zero activations.
Hands-on exercise
Work in a notebook with the NumPy code above.
- Linear collapse. Replace
np.maximum(0, z1)withz1(no activation) and the ReLU derivative with1. Train again. Expected outcome: accuracy stalls around 0.5, because the network is now a linear classifier. - Learning-rate sweep. Try
lrin{0.01, 0.1, 1.0, 10.0}. Record the loss after 3,000 steps. Expected outcome: 0.01 learns slowly, 1.0 works well, 10.0 oscillates or diverges. - Dead units. After training, compute
(a1 == 0).all(axis=0).mean(), the fraction of hidden units that are zero for every example. Then retrain withlr = 10.0and compare. - Gradient check everywhere. Extend the gradient check to a random entry of
W2,b1andb2. Introduce a deliberate bug (remove/= N) and confirm the check catches it. - Stretch: add a second hidden layer and derive its backward step on paper before coding it.
Key takeaways
- A neuron is a weighted sum plus a non-linearity; a layer is a matrix multiply plus a non-linearity; an MLP is a stack of layers.
- Without non-linear activations, any depth of linear layers collapses into one linear layer.
- Backpropagation is the chain rule applied from the loss backwards, reusing intermediate gradients so that all parameter gradients cost about as much as two forward passes.
- Three local rules cover a basic MLP: softmax plus cross-entropy gives , linear layers give and , ReLU masks the gradient.
- Sanity checks (initial loss near , gradient checking) catch most bugs before they waste training time.
- Multiplying many local derivatives makes gradients vanish or explode with depth, which motivates the techniques in the next lesson.
Next, in Training Deep Networks, you will learn the modern recipe that makes networks with hundreds of layers train reliably: AdamW, learning-rate warmup and cosine decay, normalization, residual connections, mixed precision, and how to read a loss curve like a diagnostic chart.
Further reading
- Rumelhart, Hinton and Williams, "Learning representations by back-propagating errors" (Nature, 1986): the paper that popularized backpropagation.
- Andrej Karpathy, micrograd (github.com/karpathy/micrograd) and the accompanying "Neural Networks: Zero to Hero" video lectures: build an autograd engine in about 100 lines.
- Michael Nielsen, Neural Networks and Deep Learning (neuralnetworksanddeeplearning.com), chapter 2 derives backprop carefully and readably.
- Goodfellow, Bengio and Courville, Deep Learning (MIT Press, 2016; deeplearningbook.org), chapter 6 on deep feedforward networks.
Save your progress and earn XP
Create a free account to take the quiz, track progress and unlock badges.