Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 15 — Lab: Neural Networks

Open in Colab

Lab Overview

You will build a neural network piece by piece in NumPy, prove your backpropagation correct, and then train a real classifier in PyTorch.

ExerciseTopicPoints
1Activation functions and their derivatives15
2The forward pass15
3Backpropagation, with a gradient check25
4Mini-batch training on curved data15
5A PyTorch classifier for handwritten digits20
6Early stopping10
ChallengeThe Adam optimiser+10

Complete the code where you see # TODO, then run the check cell under it.


Exercise 1: Activation Functions (15 points)

Complete the five functions. They take NumPy arrays and work element-wise, except softmax, which works on each row. Make softmax numerically stable by subtracting each row’s maximum before exponentiating.


Exercise 2: The Forward Pass (15 points)

A network with one hidden layer: H=g(XW1+b1)H = g(XW_1 + \mathbf{b}_1), y^=σ(HW2+b2)\hat{\mathbf{y}} = \sigma(HW_2 + b_2), where rows of XX are examples. Complete forward(X, params, hidden='relu'), which returns the output probabilities (a 1-D array) and a dictionary cache holding Z1, H, Z2 (you will need them in Exercise 3). hidden is 'relu' or 'sigmoid'.


Exercise 3: Backpropagation (25 points)

With the binary cross-entropy loss averaged over the nn examples of a batch, the output error is simply D2=(y^−y)/nD_2 = (\hat{\mathbf{y}} - \mathbf{y})/n (as a column). Complete backward(X, y, params, cache, hidden) returning a dictionary of gradients with the same keys and shapes as params:

∂L∂W2=H⊤D2,∂L∂b2=∑D2,D1=(D2W2⊤)⊙g′(Z1),∂L∂W1=X⊤D1,∂L∂b1=∑rowsD1\frac{\partial L}{\partial W_2} = H^\top D_2, \quad \frac{\partial L}{\partial b_2} = \textstyle\sum D_2, \quad D_1 = (D_2W_2^\top) \odot g'(Z_1), \quad \frac{\partial L}{\partial W_1} = X^\top D_1, \quad \frac{\partial L}{\partial b_1} = \textstyle\sum_{\text{rows}} D_1

The check compares your gradients with numerical estimates.


Exercise 4: Mini-Batch Training (15 points)

Complete train_mlp(X, y, hidden_units, eta, epochs, batch_size, seed): initialise the weights with He initialisation (normal, standard deviation 2/nin\sqrt{2/n_{in}}; biases 0), then for every epoch shuffle the data and update the weights after every mini-batch with plain gradient descent. Return the trained params.


Exercise 5: A PyTorch Digit Classifier (20 points)

Using the 8×8 digits prepared below, complete:

  1. make_model(): an nn.Sequential MLP with input size 64, at least one hidden ReLU layer, and 10 outputs (raw scores; no softmax).

  2. train_torch(model, loader, epochs): the standard loop with nn.CrossEntropyLoss and torch.optim.Adam(lr=1e-3).


Exercise 6: Early Stopping (10 points)

Complete should_stop(valid_losses, patience): return True when the last patience validation losses have all failed to improve on the best loss seen before them.

Question. Your network reaches 100% training accuracy and 85% validation accuracy. Name three changes you would try, and say why each one helps.

Your answer:


Challenge: The Adam Optimiser (+10 points)

Complete adam_step(param, grad, state, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8). state is a dictionary holding the running averages m and v (start them at 0 when missing); t counts steps from 1. Update m and v, apply the bias corrections, and return the new parameter. The check compares one step with PyTorch’s Adam.


Lab Report

Submit this notebook with every check cell showing ✅, your answer to the question, and one paragraph on what surprised you most about training neural networks.