Chapter 15 — Assignment Project: A Digit Reader That Holds Up
Overview¶
A post office wants to read handwritten postcode digits automatically. You will train a neural network for it, find good settings by experiment rather than by guessing, look closely at its mistakes, and test whether it still works when a digit is written slightly off-centre. Then you will report what you found.
Data. The scikit-learn digits dataset: 1,797 handwritten digits, each an 8×8 grey image (64 pixel values from 0 to 16), labelled 0 to 9.
| Part | Task | Points |
|---|---|---|
| A | Prepare the data and build the network | 15 |
| B | A training loop with early stopping | 20 |
| C | Experiments: learning rate, architecture, regularisation | 30 |
| D | Error analysis and robustness to shifted digits | 20 |
| E | Report | 15 |
Rules
Use
42for every random seed, so your results can be reproduced.The test set is used only in Part C4 and Part D. Every choice is made on the validation set.
Cells marked checked have an automatic check under them; the other parts are graded with the rubric at the end.
import copy
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import torch
from torch import nn
from torch.utils.data import TensorDataset, DataLoader
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix
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')
digits = load_digits()
fig, axes = plt.subplots(1, 10, figsize=(10, 1.3))
for d, ax in enumerate(axes):
ax.imshow(digits.images[np.where(digits.target == d)[0][0]], cmap='gray_r'); ax.set_title(d); ax.axis('off')
plt.show()Part A — Prepare the Data and Build the Network (15 points)¶
A1 (checked). Split the data into 60% training, 20% validation, 20% test, stratified by label, with random_state=42: first take the test set off, then split the rest. Return the six raw NumPy arrays (pixels 0–16), in the order X_train, X_val, X_test, y_train, y_val, y_test.
def split_data(X, y):
raise NotImplementedError # TODO: two calls to train_test_splitcheck('A1: 1077 / 360 / 360 digits', lambda: [len(a) for a in split_data(digits.data, digits.target)] == [1077, 360, 360, 1077, 360, 360])
Xr_train, Xr_val, Xr_test, y_train_np, y_val_np, y_test_np = split_data(digits.data, digits.target)A2 (checked). Complete to_tensors(scaler, X, y): scale X with an already fitted StandardScaler and return a float32 tensor of inputs and an int64 tensor of labels. The scaler is fitted on the training set only, below.
def to_tensors(scaler, X, y):
raise NotImplementedError # TODOscaler = StandardScaler().fit(Xr_train)
check('A2: types and shapes', lambda: (lambda X, y: X.dtype == torch.float32 and y.dtype == torch.int64 and X.shape == (360, 64))(*to_tensors(scaler, Xr_val, y_val_np)))
check('A2: training inputs have mean 0', lambda: abs(to_tensors(scaler, Xr_train, y_train_np)[0].mean().item()) < 1e-4)
X_train, y_train = to_tensors(scaler, Xr_train, y_train_np)
X_val, y_val = to_tensors(scaler, Xr_val, y_val_np)
X_test, y_test = to_tensors(scaler, Xr_test, y_test_np)A3 (checked). Complete make_mlp(hidden, dropout): an nn.Sequential that maps 64 inputs to 10 scores. For every size in the tuple hidden add a Linear layer, a ReLU and, when dropout > 0, a Dropout(dropout). End with a Linear layer to 10 outputs (no softmax: the loss applies it).
def make_mlp(hidden=(64,), dropout=0.0):
raise NotImplementedError # TODO
def n_params(model):
return sum(p.numel() for p in model.parameters())check('A3: hidden=(32, 16) has 2,778 parameters', lambda: n_params(make_mlp((32, 16))) == 2778)
check('A3: dropout layers are added', lambda: sum(isinstance(m, nn.Dropout) for m in make_mlp((32, 16), 0.3)) == 2)
check('A3: the output has 10 scores', lambda: make_mlp((8,))(torch.zeros(5, 64)).shape == (5, 10))Part B — A Training Loop with Early Stopping (20 points)¶
B1 (checked). Complete fit. It trains model with Adam and the cross-entropy loss on mini-batches, and after every epoch records the training loss (the mean over the epoch), the validation loss and the validation accuracy in history. It stops when the validation accuracy has not improved for patience epochs, and returns the model with the weights of its best epoch (keep a copy.deepcopy(model.state_dict()) of them).
def accuracy(model, X, y):
model.eval()
with torch.no_grad():
return (model(X).argmax(1) == y).float().mean().item()
def fit(model, X_train, y_train, X_val, y_val, epochs=100, lr=1e-3, weight_decay=0.0, batch_size=64, patience=10, seed=42):
torch.manual_seed(seed)
loader = DataLoader(TensorDataset(X_train, y_train), batch_size=batch_size, shuffle=True)
loss_fn = nn.CrossEntropyLoss()
opt = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=weight_decay)
history = {'train_loss': [], 'val_loss': [], 'val_acc': []}
raise NotImplementedError # TODO: the epoch loop, the history, early stopping, and restoring the best weightsdef _fit_ok():
torch.manual_seed(42)
model, h = fit(make_mlp((32,)), X_train, y_train, X_val, y_val, epochs=40, patience=5)
same_length = len(h['train_loss']) == len(h['val_loss']) == len(h['val_acc'])
best_restored = abs(accuracy(model, X_val, y_val) - max(h['val_acc'])) < 1e-6
print(f' {len(h["val_acc"])} epochs, best validation accuracy {max(h["val_acc"]):.3f}')
return same_length and best_restored and max(h['val_acc']) > 0.9 and len(h['val_acc']) <= 40
check('B1: history recorded, best weights restored, accuracy > 0.9', _fit_ok)B2. Train make_mlp((64,)) for up to 100 epochs with patience 15 and plot the training and validation loss curves. Mark the epoch whose weights were kept.
# TODOPart C — Experiments (30 points)¶
Each experiment changes one thing and keeps the rest fixed. Call torch.manual_seed(42) before building each model.
C1. Learning rate. Train make_mlp((64,)) with the learning rates 0.0001, 0.001, 0.01 and 0.1, for 60 epochs without early stopping (patience=60). Plot the four validation-loss curves on one chart. What happens with the smallest and the largest rate?
# TODOYour observations:
C2. Architecture. With the learning rate you chose, compare at least five networks, from small to large and from shallow to deep, for example (16,), (64,), (256,), (64, 64) and (128, 64, 32). Use early stopping (patience 15). Show a table with the number of parameters, the epochs trained and the best validation accuracy.
# TODOC3. Regularisation. For one architecture from C2, try dropout 0, 0.2 and 0.5 combined with weight decay 0 and 0.001 (six runs). Show a table and pick your final configuration.
# TODOC4. Train your final configuration and report its accuracy on the test set, once.
# TODO: final = ...Part D — Errors and Robustness (20 points)¶
D1. Show the confusion matrix of your final model on the test set, and the test digits it got wrong (image, true label, prediction). Which digits does it confuse, and would a person confuse them too?
# TODOYour observations:
D2 (checked). A digit written slightly to one side should still be read. Complete shift_images(X, dx, dy): move each 8×8 image (given as rows of 64 raw pixels) dx pixels to the right and dy pixels down (negative values move left or up). Pixels that leave the image are lost; pixels that come in are 0. Return the same shape as X.
def shift_images(X, dx, dy):
raise NotImplementedError # TODO_dot = np.zeros((1, 64)); _dot[0, 2 * 8 + 3] = 7 # one pixel at row 2, column 3
check('D2: right 1 and up 1 moves row 2, column 3 to row 1, column 4', lambda: shift_images(_dot, 1, -1).reshape(8, 8)[1, 4] == 7 and shift_images(_dot, 1, -1).sum() == 7)
check('D2: pixels pushed off the edge are lost', lambda: shift_images(_dot, 5, 0).sum() == 0)
check('D2: the shape is kept', lambda: shift_images(Xr_test, -1, 1).shape == Xr_test.shape)D3. Measure the final model’s test accuracy when every test digit is shifted by one pixel in each of the 8 directions (right, left, up, down and the diagonals). How much does accuracy drop?
DIRECTIONS = [(dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (dx, dy) != (0, 0)]
def shifted_accuracy(model):
return np.mean([accuracy(model, *to_tensors(scaler, shift_images(Xr_test, dx, dy), y_test_np)) for dx, dy in DIRECTIONS])
# TODOD4. Fix it with data augmentation: add to the training set a shifted copy of every training digit for each of the 8 directions (the labels do not change), train your final configuration again, and compare both accuracies with D3. Keep the validation set unshifted.
# TODOYour observations:
Part E — Report (15 points)¶
Write 300–400 words for the post office’s engineers:
What you built: data, network, training method.
How you chose the settings: the key result of each experiment in C, in one or two sentences each.
Results: test accuracy, the typical mistakes, and the robustness test with and without augmentation.
What next: an MLP sees 64 unrelated numbers; it does not know that neighbouring pixels belong together. Explain in a few sentences why that makes shifts hard for it, and what kind of network (Chapter 18) is built to handle them.
Your report:
Grading Rubric¶
| Part | Full marks if… |
|---|---|
| A (15) | split, tensors and network correct (checked) |
| B (20) | the training loop passes its check; clear learning curves with the kept epoch marked |
| C (30) | one change at a time; readable chart and tables; a sensible final choice made on validation data; test set used once |
| D (20) | confusion matrix and mistakes shown and discussed; shift_images correct (checked); robustness measured before and after augmentation |
| E (15) | all four sections, numbers that match the notebook, a clear argument for convolutional networks |