Skip to content

Module 07

Anurag Prasad edited this page Nov 8, 2026 · 10 revisions

Module 07 — Feedforward Neural Networks and Backpropagation

⬅️ Module 06 · 🗺️ Curriculum · 🏠 Home · Module 08 ➡️

Level: Intermediate · Prerequisites: Modules 02, 05, 06 · Time: about 8–10 hours

On this page: Overview and learning goals · Beginner: the big picture · Core concepts and derivations · Worked example · Implementation · Advanced topics · Pitfalls and best practices · Conceptual questions and answers · Sources and further reading


Overview and learning goals

A feedforward network (multilayer perceptron, MLP) alternates affine maps and nonlinearities. Backpropagation is reverse-mode autodiff (Module 02) specialised to this layered structure: it computes the gradient of the loss with respect to every weight in time comparable to one forward pass. Everything later — CNNs, RNNs, Transformers — reuses these ideas.

After this module you should be able to:

  • write the forward pass in scalar and vectorised batch form and count parameters;
  • derive the backprop recursion and the gradients for weights, biases and activations;
  • explain how hidden layers solve XOR and pick output layers/losses;
  • implement and gradient-check a training loop.

Beginner: the big picture

Layer by layer, the network turns an input into progressively more useful hidden representations. Training repeats four steps: forward (compute prediction and loss), backward (compute how each weight affected the loss), update (move weights opposite the gradient), repeat. Backprop is just the chain rule applied from the loss back to the input, reusing intermediate results so each layer's gradient costs about one matrix product.

flowchart LR
    X["x"] --> L1["Layer 1: z1=W1x+b1, a1=phi(z1)"] --> L2["Layer 2: z2=W2a1+b2, yhat"] --> Loss["Loss L"]
    Loss -. "delta2 = dL/dz2" .-> L2
    L2 -. "delta1 = (W2^T delta2) * phi'(z1)" .-> L1
    L1 -. "dW1 = delta1 x^T" .-> X
Loading

Core concepts and derivations

Layers, neurons, weights, biases and hidden representations

Layer $\ell$ has weight $W^{(\ell)}\in\mathbb{R}^{n_\ell\times n_{\ell-1}}$, bias $\mathbf{b}^{(\ell)}\in\mathbb{R}^{n_\ell}$; each row is one neuron. Parameter count of an MLP $784\to256\to10$: $784\cdot256+256+256\cdot10+10=203{,}530$. Hidden activations are learned features.

Forward propagation

With $\mathbf{a}^{(0)}=\mathbf{x}$:

$$ \mathbf{z}^{(\ell)}=W^{(\ell)}\mathbf{a}^{(\ell-1)}+\mathbf{b}^{(\ell)},\qquad \mathbf{a}^{(\ell)}=\phi^{(\ell)}\bigl(\mathbf{z}^{(\ell)}\bigr),\qquad L=\ell\bigl(\mathbf{a}^{(\Lambda)},\mathbf{y}\bigr). $$

For a batch (rows are examples): $Z^{(\ell)}=A^{(\ell-1)}W^{(\ell)\top}+\mathbf{1}\mathbf{b}^{(\ell)\top}$.

Backpropagation: chain-rule derivation

Define the error signal $\boldsymbol\delta^{(\ell)}=\partial L/\partial\mathbf{z}^{(\ell)}$. At the output, $\boldsymbol\delta^{(\Lambda)}=\nabla_{\mathbf{a}}L\odot\phi'(\mathbf{z}^{(\Lambda)})$ — for softmax+cross-entropy simply $\mathbf{p}-\mathbf{y}$, for linear+MSE $\hat{\mathbf{y}}-\mathbf{y}$. Since $\mathbf{z}^{(\ell+1)}=W^{(\ell+1)}\phi(\mathbf{z}^{(\ell)})+\mathbf{b}^{(\ell+1)}$, the chain rule gives

$$ \boldsymbol\delta^{(\ell)}=\Bigl(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)}\Bigr)\odot\phi'\bigl(\mathbf{z}^{(\ell)}\bigr),\qquad \frac{\partial L}{\partial W^{(\ell)}}=\boldsymbol\delta^{(\ell)}\mathbf{a}^{(\ell-1)\top},\qquad \frac{\partial L}{\partial\mathbf{b}^{(\ell)}}=\boldsymbol\delta^{(\ell)}. $$

Interpretation: $W^\top\boldsymbol\delta$ routes blame backwards along the same connections; $\phi'$ gates it by how sensitive the unit was. Repeated multiplication by $W^\top$ and $\phi'$ is why gradients vanish or explode with depth (Module 09).

Gradients in batch (matrix) form

For a mini-batch of size $B$ with mean loss: $\Delta^{(\ell)}=\bigl(\Delta^{(\ell+1)}W^{(\ell+1)}\bigr)\odot\phi'(Z^{(\ell)})$, $\ \partial L/\partial W^{(\ell)}=\frac1B\Delta^{(\ell)\top}A^{(\ell-1)}$, $\ \partial L/\partial\mathbf{b}^{(\ell)}=\frac1B\mathbf{1}^\top\Delta^{(\ell)}$, where $\Delta^{(\ell)}\in\mathbb{R}^{B\times n_\ell}$. Shapes: $(n_\ell\times B)(B\times n_{\ell-1})=n_\ell\times n_{\ell-1}$ ✓.

XOR with hidden layers

A single unit cannot compute XOR (Module 04). With two or three hidden units the model learns a representation in which the classes are separable; the figure shows a network trained from scratch by exactly the recursion above.

Training loss and learned XOR decision regions for a 2-3-1 tanh network

Figure 7.1 — A 2–3–1 tanh network trained with full-batch gradient descent on XOR reaches loss ≈ 0.001 and carves a non-linear decision region. Original figure computed with NumPy backprop (figures/make_figs_1.py).

Regression and classification output layers

Task Output activation Loss $\boldsymbol\delta^{(\Lambda)}$
Regression identity MSE $\hat y-y$
Binary sigmoid BCE $\hat p-y$
Multiclass softmax CE $\mathbf{p}-\mathbf{y}$

Training loop and gradient checking

Loop: shuffle → mini-batches → forward → loss → backward → optimiser step → validate. Always gradient-check a new layer (Module 02) before trusting it.

Worked example

Network $2\to2\to1$, ReLU hidden, linear output, MSE $L=\tfrac12(\hat y-y)^2$. Take $\mathbf{x}=(1,2)$, $y=1$, $W^{(1)}=\begin{pmatrix}0.1&0.2\0.3&0.4\end{pmatrix}$, $\mathbf{b}^{(1)}=\mathbf{0}$, $W^{(2)}=(0.5,,-0.5)$, $b^{(2)}=0$.

Forward: $\mathbf{z}^{(1)}=(0.5,1.1)$; $\mathbf{a}^{(1)}=(0.5,1.1)$ (both positive); $\hat y=0.25-0.55=-0.3$; $L=\tfrac12(1.3)^2=0.845$.

Backward: $\delta^{(2)}=\hat y-y=-1.3$. $\partial L/\partial W^{(2)}=\delta^{(2)}\mathbf{a}^{(1)\top}=(-0.65,-1.43)$, $\partial L/\partial b^{(2)}=-1.3$. Then $\boldsymbol\delta^{(1)}=(W^{(2)\top}\delta^{(2)})\odot\mathbb{1}[\mathbf{z}^{(1)}>0]=(-0.65,,0.65)$, so $\partial L/\partial W^{(1)}=\boldsymbol\delta^{(1)}\mathbf{x}^\top=\begin{pmatrix}-0.65&-1.3\0.65&1.3\end{pmatrix}$, $\partial L/\partial\mathbf{b}^{(1)}=(-0.65,0.65)$.

Check: $\hat y$ depends on $W^{(2)}_1$ with slope $a_1=0.5$, so $\partial L/\partial W^{(2)}_1=(\hat y-y)\cdot0.5=-0.65$ ✓.

Implementation

import numpy as np

class MLP:
    def __init__(self, sizes, seed=0):
        r = np.random.default_rng(seed)
        self.W = [r.normal(0, np.sqrt(2 / m), (n, m)) for m, n in zip(sizes[:-1], sizes[1:])]
        self.b = [np.zeros(n) for n in sizes[1:]]
    def forward(self, X):
        self.A = [X]
        for i, (W, b) in enumerate(zip(self.W, self.b)):
            Z = self.A[-1] @ W.T + b
            self.A.append(Z if i == len(self.W) - 1 else np.maximum(0, Z))
        return self.A[-1]
    def backward(self, Y):                                   # MSE loss, mean over batch
        B = len(Y); D = (self.A[-1] - Y) / B; gW, gb = [], []
        for i in reversed(range(len(self.W))):
            gW.insert(0, D.T @ self.A[i]); gb.insert(0, D.sum(0))
            if i: D = (D @ self.W[i]) * (self.A[i] > 0)
        return gW, gb

Validate with num_grad from Module 02: perturb one weight, compare $\frac{L(w+h)-L(w-h)}{2h}$ with gW. In PyTorch the same loop is loss.backward(); optimizer.step().

Advanced topics

  • Computational cost: backward ≈ 2× forward FLOPs; activation memory scales with depth × batch.
  • Initialisation and normalisation keep $\boldsymbol\delta$ well scaled (Module 09).
  • Skip connections add identity paths to the recursion (Module 09).
  • Neural tangent kernel / lazy training: in the infinite-width limit with suitable scaling, training linearises; finite networks learn features.
  • Per-example gradients for differential privacy and influence functions.
  • Alternatives to backprop (target propagation, forward-forward, Hebbian rules) are research topics motivated by biological plausibility and hardware.

Pitfalls and best practices

  • Forgetting to apply $\phi'$ or to transpose $W$ in the recursion.
  • Mixing mean and sum reductions between loss and gradient.
  • Initialising all weights equally (symmetry: neurons stay identical) — Module 09.
  • Not checking shapes: assert grad.shape == param.shape.
  • Comparing training loss only; keep a validation set.

Conceptual questions and answers

Q1. Why is backprop efficient compared with differentiating each weight separately?

Reverse-mode reuses $\boldsymbol\delta^{(\ell+1)}$ for every gradient in layer $\ell$ and earlier; total cost is $O(#\text{weights})$ rather than $O(#\text{weights}^2)$.

Q2. Derive $\boldsymbol\delta^{(\ell)}$ in terms of $\boldsymbol\delta^{(\ell+1)}$.

$\boldsymbol\delta^{(\ell)}=\bigl(\partial\mathbf{z}^{(\ell+1)}/\partial\mathbf{z}^{(\ell)}\bigr)^\top\boldsymbol\delta^{(\ell+1)}=\bigl(W^{(\ell+1)}\operatorname{diag}\phi'\bigr)^\top\boldsymbol\delta^{(\ell+1)}$, i.e. $(W^{(\ell+1)\top}\boldsymbol\delta^{(\ell+1)})\odot\phi'(\mathbf{z}^{(\ell)})$.

Q3. Why must weights not all be initialised to the same value?

Neurons in a layer would receive identical gradients and remain identical forever (symmetry), wasting capacity. Random initialisation breaks the symmetry.

Q4. Why does the bias gradient sum over the batch?

The same bias is broadcast to every example, so its total effect is the sum of per-example effects.

Q5. How does a hidden layer solve XOR?

It maps inputs into a feature space (e.g. $x_1+x_2$ and its thresholded version) where the classes become linearly separable for the output unit.

Q6. Why is softmax+cross-entropy preferred over softmax+MSE?

CE yields $\mathbf{p}-\mathbf{y}$, a non-vanishing gradient for wrong predictions, and is the likelihood under a categorical model; MSE multiplies by softmax derivatives that can vanish.

Q7. What dominates the memory use of backprop?

Stored forward activations $\mathbf{a}^{(\ell)}$ needed for $\partial L/\partial W^{(\ell)}$ and $\phi'$; they scale with batch size and depth.

Q8. How would you verify your own backprop implementation?

Compare with central finite differences on a tiny network in float64; expect relative error $\lesssim10^{-6}$.

Sources and further reading

  • Rumelhart, D. E., Hinton, G. E., & Williams, R. J. (1986). Learning representations by back-propagating errors. Nature, 323, 533–536.
  • LeCun, Y., Bottou, L., Orr, G., & Müller, K.-R. (2012). Efficient BackProp. In Neural Networks: Tricks of the Trade. Springer.
  • Goodfellow, Bengio & Courville (2016). Deep Learning, Ch. 6.
  • Nielsen, M. (2015). Neural Networks and Deep Learning (online book), Ch. 2.
  • Jacot, A., Gabriel, F., & Hongler, C. (2018). Neural tangent kernel. NeurIPS.

⬅️ Module 06 · 🗺️ Curriculum · 🏠 Home · Module 08 ➡️

🎓 Deep Learning Hub

🏠 Home · 🗺️ Curriculum · 🧭 Learning paths

❓ Question bank · 📖 Glossary · 📚 References

Jump to module:

01 02 03 04 05 06 07 08 09 10 11 12

13 14 15 16 17 18 19 20 21 22 23 24

Part 1 · Mathematical foundations
Part 2 · Neural network fundamentals
Part 3 · Training deep networks
Part 4 · Core architectures
Part 5 · Representation and generative learning
Part 6 · Specialised, modern and responsible deep learning
Reference and meta

Clone this wiki locally