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 — Assignment Project: A Digit Reader That Holds Up

Open in Colab

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.

PartTaskPoints
APrepare the data and build the network15
BA training loop with early stopping20
CExperiments: learning rate, architecture, regularisation30
DError analysis and robustness to shifted digits20
EReport15

Rules

  • Use 42 for 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.


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.

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.

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).


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).

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.


Part 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?

Your 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.

C3. 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.

C4. Train your final configuration and report its accuracy on the test set, once.


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?

Your 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.

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?

D4. 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.

Your observations:


Part E — Report (15 points)

Write 300–400 words for the post office’s engineers:

  1. What you built: data, network, training method.

  2. How you chose the settings: the key result of each experiment in C, in one or two sentences each.

  3. Results: test accuracy, the typical mistakes, and the robustness test with and without augmentation.

  4. 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

PartFull 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