Intermediate⏱ 30 min⚑ 100 XP🧩 5-question quiz

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 zz), then applies an activation function Ο†\varphi to produce its output aa:

z=w⊀x+b,a=Ο†(z)z = \mathbf{w}^\top \mathbf{x} + b, \qquad a = \varphi(z)

Without Ο†\varphi 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: a=Ο†(xW+b)\mathbf{a} = \varphi(\mathbf{x} W + \mathbf{b}), where WW 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: (xW1)W2=x(W1W2)(\mathbf{x} W_1) W_2 = \mathbf{x} (W_1 W_2). The product W1W2W_1 W_2 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

ActivationFormulaWhere you see it
SigmoidΟƒ(z)=11+eβˆ’z\sigma(z) = \frac{1}{1+e^{-z}}Binary output probabilities, gates inside LSTMs. Saturates for large positive or negative inputs, so gradients vanish.
Tanhtanh⁑(z)=ezβˆ’eβˆ’zez+eβˆ’z\tanh(z) = \frac{e^{z}-e^{-z}}{e^{z}+e^{-z}}Older RNNs. Zero-centred but also saturates.
ReLUmax⁑(0,z)\max(0, z)The default for CNNs and MLPs for a decade. Cheap, does not saturate for z>0z > 0. Units can "die".
GELUzβ‹…Ξ¦(z)z \cdot \Phi(z) (Ξ¦\Phi = Gaussian CDF)BERT, GPT-2 and many transformers. A smooth ReLU.
SiLU / Swishzβ‹…Οƒ(z)z \cdot \sigma(z)Inside the SwiGLU blocks of most current LLMs (Module 7, Transformers & LLMs).
Softmaxeziβˆ‘jezj\frac{e^{z_i}}{\sum_j e^{z_j}}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 KK 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 yy:

z1=xW1+b1,a1=ReLU(z1),z2=a1W2+b2,p=softmax(z2),L=βˆ’log⁑py\begin{aligned} \mathbf{z}_1 &= \mathbf{x} W_1 + \mathbf{b}_1, & \mathbf{a}_1 &= \mathrm{ReLU}(\mathbf{z}_1), \\ \mathbf{z}_2 &= \mathbf{a}_1 W_2 + \mathbf{b}_2, & \mathbf{p} &= \mathrm{softmax}(\mathbf{z}_2), \\ L &= -\log p_y \end{aligned}

Cross-entropy punishes confident wrong answers heavily: predicting 0.01 for the true class costs βˆ’ln⁑0.01β‰ˆ4.6-\ln 0.01 \approx 4.6, 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 ln⁑K\ln K (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 βˆ‚L/βˆ‚ΞΈ\partial L / \partial \theta for every parameter ΞΈ\theta. 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.

Rendering diagram…

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 z=aW+b\mathbf{z} = \mathbf{a} W + \mathbf{b} with upstream gradient g=βˆ‚L/βˆ‚z\mathbf{g} = \partial L / \partial \mathbf{z}: the weight gradient is a⊀g\mathbf{a}^\top \mathbf{g}, the bias gradient sums g\mathbf{g} over the batch, and gW⊀\mathbf{g} W^\top is passed further back.
  • ReLU: multiply the upstream gradient elementwise by the indicator 1[z>0]\mathbb{1}[z > 0]. The gradient passes through unchanged where the unit was active and is blocked where it was not.
βˆ‚Lβˆ‚z2=pβˆ’ey,βˆ‚Lβˆ‚W=a⊀g,βˆ‚Lβˆ‚a=gW⊀,βˆ‚Lβˆ‚z1=βˆ‚Lβˆ‚a1βŠ™1[z1>0]\frac{\partial L}{\partial \mathbf{z}_2} = \mathbf{p} - \mathbf{e}_y, \qquad \frac{\partial L}{\partial W} = \mathbf{a}^\top \mathbf{g}, \qquad \frac{\partial L}{\partial \mathbf{a}} = \mathbf{g} W^\top, \qquad \frac{\partial L}{\partial \mathbf{z}_1} = \frac{\partial L}{\partial \mathbf{a}_1} \odot \mathbb{1}[\mathbf{z}_1 > 0]

Here ey\mathbf{e}_y is the one-hot vector for the true class and βŠ™\odot is elementwise multiplication. Why is the softmax-plus-cross-entropy gradient so clean? Because L=βˆ’zy+logβ‘βˆ‘jezjL = -z_y + \log \sum_j e^{z_j}, so βˆ‚L/βˆ‚zi=piβˆ’1[i=y]\partial L / \partial z_i = p_i - \mathbb{1}[i = y]: 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 x=2x = 2, weight w=0.5w = 0.5, bias b=βˆ’0.5b = -0.5, target t=1t = 1, and squared-error loss L=12(aβˆ’t)2L = \tfrac{1}{2}(a - t)^2.

StepComputationValue
Forwardz=wx+b=1.0βˆ’0.5z = w x + b = 1.0 - 0.50.5
Forwarda=ReLU(z)a = \mathrm{ReLU}(z)0.5
ForwardL=12(0.5βˆ’1)2L = \tfrac{1}{2}(0.5 - 1)^20.125
Backwardβˆ‚L/βˆ‚a=aβˆ’t\partial L/\partial a = a - t-0.5
Backwardβˆ‚L/βˆ‚z=βˆ‚L/βˆ‚aβ‹…1[z>0]\partial L/\partial z = \partial L/\partial a \cdot \mathbb{1}[z > 0]-0.5
Backwardβˆ‚L/βˆ‚w=βˆ‚L/βˆ‚zβ‹…x\partial L/\partial w = \partial L/\partial z \cdot x-1.0
Backwardβˆ‚L/βˆ‚b=βˆ‚L/βˆ‚z\partial L/\partial b = \partial L/\partial z-0.5

With learning rate 0.1, gradient descent updates w←0.5βˆ’0.1Γ—(βˆ’1.0)=0.6w \leftarrow 0.5 - 0.1 \times (-1.0) = 0.6 and bβ†βˆ’0.5βˆ’0.1Γ—(βˆ’0.5)=βˆ’0.45b \leftarrow -0.5 - 0.1 \times (-0.5) = -0.45. The new output is z=1.2βˆ’0.45=0.75z = 1.2 - 0.45 = 0.75, 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 x=2x = 2: 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 ln⁑3β‰ˆ1.10\ln 3 \approx 1.10 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:

βˆ‚Lβˆ‚ΞΈβ‰ˆL(ΞΈ+Ξ΅)βˆ’L(ΞΈβˆ’Ξ΅)2Ξ΅\frac{\partial L}{\partial \theta} \approx \frac{L(\theta + \varepsilon) - L(\theta - \varepsilon)}{2\varepsilon}

The centred version has error proportional to Ξ΅2\varepsilon^2, much smaller than the one-sided version's error proportional to Ξ΅\varepsilon.

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 (0.2510β‰ˆ10βˆ’60.25^{10} \approx 10^{-6}). Three families of fixes made deep learning work, and the next lesson covers each:

  1. Better activations and initialization (ReLU with He init keeps activation variance roughly constant across layers).
  2. Normalization layers that re-centre and re-scale activations.
  3. Residual connections x+f(x)\mathbf{x} + f(\mathbf{x}), 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 exactly N is 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 computing exp of 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.

  1. Linear collapse. Replace np.maximum(0, z1) with z1 (no activation) and the ReLU derivative with 1. Train again. Expected outcome: accuracy stalls around 0.5, because the network is now a linear classifier.
  2. Learning-rate sweep. Try lr in {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.
  3. Dead units. After training, compute (a1 == 0).all(axis=0).mean(), the fraction of hidden units that are zero for every example. Then retrain with lr = 10.0 and compare.
  4. Gradient check everywhere. Extend the gradient check to a random entry of W2, b1 and b2. Introduce a deliberate bug (remove /= N) and confirm the check catches it.
  5. 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 pβˆ’ey\mathbf{p} - \mathbf{e}_y, linear layers give a⊀g\mathbf{a}^\top \mathbf{g} and gW⊀\mathbf{g} W^\top, ReLU masks the gradient.
  • Sanity checks (initial loss near ln⁑K\ln K, 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.