Chapter 15 — Lab: Neural Networks
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.
| Exercise | Topic | Points |
|---|---|---|
| 1 | Activation functions and their derivatives | 15 |
| 2 | The forward pass | 15 |
| 3 | Backpropagation, with a gradient check | 25 |
| 4 | Mini-batch training on curved data | 15 |
| 5 | A PyTorch classifier for handwritten digits | 20 |
| 6 | Early stopping | 10 |
| Challenge | The Adam optimiser | +10 |
Complete the code where you see # TODO, then run the check cell under it.
import numpy as np
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import make_moons, load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
print('Setup complete.')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.
def sigmoid(z):
raise NotImplementedError # TODO
def sigmoid_grad(z):
raise NotImplementedError # TODO: the derivative of the sigmoid at z
def relu(z):
raise NotImplementedError # TODO
def relu_grad(z):
raise NotImplementedError # TODO: 1 where z > 0, else 0
def softmax(Z):
raise NotImplementedError # TODO: row-wise, stablecheck('sigmoid(0) = 0.5 and its slope is 0.25', lambda: sigmoid(np.array([0.]))[0] == 0.5 and abs(sigmoid_grad(np.array([0.]))[0] - 0.25) < 1e-12)
check('relu and its derivative', lambda: np.array_equal(relu(np.array([-2., 0., 3.])), [0, 0, 3]) and np.array_equal(relu_grad(np.array([-2., 0.5, 3.])), [0, 1, 1]))
check('softmax rows sum to 1', lambda: np.allclose(softmax(np.array([[1., 2., 3.], [0., 0., 0.]])).sum(axis=1), 1))
check('softmax is stable for large scores', lambda: np.allclose(softmax(np.array([[1000., 1001.]])), [[0.26894142, 0.73105858]]))Exercise 2: The Forward Pass (15 points)¶
A network with one hidden layer: , , where rows of 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'.
def forward(X, params, hidden='relu'):
W1, b1, W2, b2 = params['W1'], params['b1'], params['W2'], params['b2']
raise NotImplementedError # TODO: Z1, H, Z2, then the sigmoid output# the worked example of the chapter (weights transposed: here rows of W1 are inputs)
example = {'W1': np.array([[0.5, 0.3], [-0.4, 0.8]]), 'b1': np.array([0.1, -0.1]), 'W2': np.array([[0.7], [-0.6]]), 'b2': np.array([0.2])}
check('the worked example: y_hat = 0.580', lambda: abs(forward(np.array([[1., 0.]]), example, 'sigmoid')[0][0] - 0.580) < 1e-3)
check('a batch of 5 gives 5 outputs', lambda: forward(np.ones((5, 2)), example)[0].shape == (5,))Exercise 3: Backpropagation (25 points)¶
With the binary cross-entropy loss averaged over the examples of a batch, the output error is simply (as a column). Complete backward(X, y, params, cache, hidden) returning a dictionary of gradients with the same keys and shapes as params:
The check compares your gradients with numerical estimates.
def bce(p, y):
p = np.clip(p, 1e-12, 1 - 1e-12)
return -np.mean(y * np.log(p) + (1 - y) * np.log(1 - p))
def backward(X, y, params, cache, hidden='relu'):
raise NotImplementedError # TODO: the five formulas abovedef numeric_grads(X, y, params, hidden, eps=1e-6):
grads = {}
for k, P in params.items():
G = np.zeros_like(P)
for idx in np.ndindex(P.shape):
old = P[idx]
P[idx] = old + eps; lp = bce(forward(X, params, hidden)[0], y)
P[idx] = old - eps; lm = bce(forward(X, params, hidden)[0], y)
P[idx] = old; G[idx] = (lp - lm) / (2 * eps)
grads[k] = G
return grads
def _grad_ok(hidden):
rng = np.random.default_rng(1)
X = rng.normal(size=(8, 3)); y = (rng.random(8) > 0.5).astype(float)
params = {'W1': rng.normal(size=(3, 4)), 'b1': rng.normal(size=4), 'W2': rng.normal(size=(4, 1)), 'b2': rng.normal(size=1)}
_, cache = forward(X, params, hidden)
mine, ref = backward(X, y, params, cache, hidden), numeric_grads(X, y, params, hidden)
return all(mine[k].shape == ref[k].shape and np.allclose(mine[k], ref[k], atol=1e-6) for k in params)
check('gradients match the numerical check (ReLU hidden layer)', lambda: _grad_ok('relu'))
check('gradients match the numerical check (sigmoid hidden layer)', lambda: _grad_ok('sigmoid'))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 ; 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.
def train_mlp(X, y, hidden_units=16, eta=0.5, epochs=200, batch_size=32, seed=0):
rng = np.random.default_rng(seed)
d = X.shape[1]
raise NotImplementedError # TODO: initialise, then epochs of shuffled mini-batch updatesXm, ym = make_moons(500, noise=0.2, random_state=0)
Xtr, Xva, ytr, yva = train_test_split(Xm, ym.astype(float), test_size=0.3, random_state=0)
check('validation accuracy on the moons ≥ 0.95', lambda: np.mean((forward(Xva, train_mlp(Xtr, ytr))[0] > 0.5) == yva) >= 0.95)Exercise 5: A PyTorch Digit Classifier (20 points)¶
Using the 8×8 digits prepared below, complete:
make_model(): annn.SequentialMLP with input size 64, at least one hidden ReLU layer, and 10 outputs (raw scores; no softmax).train_torch(model, loader, epochs): the standard loop withnn.CrossEntropyLossandtorch.optim.Adam(lr=1e-3).
digits = load_digits()
X_tr, X_te, y_tr, y_te = train_test_split(digits.data, digits.target, test_size=0.25, stratify=digits.target, random_state=0)
sc = StandardScaler().fit(X_tr)
train_ds = TensorDataset(torch.tensor(sc.transform(X_tr), dtype=torch.float32), torch.tensor(y_tr))
test_X, test_y = torch.tensor(sc.transform(X_te), dtype=torch.float32), torch.tensor(y_te)
def make_model():
raise NotImplementedError # TODO
def train_torch(model, loader, epochs=30):
raise NotImplementedError # TODO: forward, loss, zero_grad, backward, stepdef _torch_ok():
torch.manual_seed(0)
model = train_torch(make_model(), DataLoader(train_ds, batch_size=64, shuffle=True), epochs=30)
model.eval()
with torch.no_grad():
acc = (model(test_X).argmax(1) == test_y).float().mean().item()
print(f' test accuracy: {acc:.3f}')
return isinstance(model, nn.Module) and acc >= 0.95
check('test accuracy ≥ 0.95', _torch_ok)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.
def should_stop(valid_losses, patience=3):
raise NotImplementedError # TODOcheck('still improving: do not stop', lambda: should_stop([1.0, 0.8, 0.7, 0.6, 0.55], 3) is False)
check('three epochs without improvement: stop', lambda: should_stop([1.0, 0.6, 0.65, 0.7, 0.62], 3) is True)
check('too few epochs to decide', lambda: should_stop([1.0, 1.1], 3) is False)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.
def adam_step(param, grad, state, t, lr=1e-3, b1=0.9, b2=0.999, eps=1e-8):
raise NotImplementedError # TODOdef _adam_ok():
w0, g = np.array([0.5, -1.0, 2.0]), np.array([0.1, -0.3, 0.05])
tw = torch.tensor(w0, requires_grad=True); opt = torch.optim.Adam([tw], lr=0.01)
state, w = {}, w0.copy()
for t in range(1, 4):
tw.grad = torch.tensor(g); opt.step()
w = adam_step(w, g, state, t, lr=0.01)
return np.allclose(w, tw.detach().numpy(), atol=1e-7)
check('three steps agree with torch.optim.Adam', _adam_ok)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.