Chapter 17 — Assignment Project: Finding Digits Anywhere
Overview¶
A scanner reads digits from forms, but the digits are never in the same place: each is somewhere on a 24×24 patch, with some noise from the paper. You will show why a dense network struggles, design a small convolutional network under a parameter budget, test which design choices matter, and check how it behaves at positions it never saw in training.
| Part | Task | Points |
|---|---|---|
| A | A dense baseline | 15 |
| B | A CNN under a budget | 25 |
| C | One change at a time | 20 |
| D | Positions never seen | 20 |
| E | Look inside, and report | 20 |
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
torch.set_num_threads(2)
X, y = load_digits(return_X_y=True); X = X.reshape(-1, 8, 8) / 16
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
def scatter(imgs, rng, cols=(0, 17), size=24, noise=0.1):
"""Each digit at a random place on a noisy size x size patch; its left edge drawn from range(*cols)."""
out = rng.random((len(imgs), size, size)) * noise
for i, im in enumerate(imgs):
r, c = rng.integers(0, size - 7), rng.integers(*cols)
out[i, r:r + 8, c:c + 8] = np.maximum(out[i, r:r + 8, c:c + 8], im)
return torch.tensor(out, dtype=torch.float32).unsqueeze(1)
rng = np.random.default_rng(0)
Ptr, Pte = scatter(Xtr, rng), scatter(Xte, rng)
ytr_t, yte_t = torch.tensor(ytr), torch.tensor(yte)
fig, axes = plt.subplots(1, 8, figsize=(12, 1.8))
for i, ax in enumerate(axes): ax.imshow(Ptr[i, 0], cmap='gray_r'); ax.set_title(str(ytr[i]), fontsize=9); ax.axis('off')
plt.tight_layout(); plt.show()
def train(net, Xa, ya, epochs=30, seed=0):
torch.manual_seed(seed); opt = torch.optim.Adam(net.parameters(), 1e-3); g = torch.Generator().manual_seed(seed)
for ep in range(epochs):
net.train()
for idx in torch.randperm(len(Xa), generator=g).split(64):
opt.zero_grad(); F.cross_entropy(net(Xa[idx]), ya[idx]).backward(); opt.step()
net.eval(); return net
def acc(net, Xa, ya):
with torch.no_grad(): return float((net(Xa).argmax(1) == ya).float().mean())
count = lambda net: sum(p.numel() for p in net.parameters())
print(f'training {len(Ptr)} patches, test {len(Pte)}')Part A — A Dense Baseline (15 points)¶
Train a dense network with two hidden layers of 128 ReLU units on the flattened patches (30 epochs, Adam at 10-3, with
train). Report its parameter count, its training accuracy and its test accuracy.In two sentences, explain the gap using Section 17.1.
# Your code hereYour explanation:
Part B — A CNN Under a Budget (25 points)¶
Design a convolutional network with at most 30 000 parameters. Print a layer-by-layer summary (output shape, parameters, receptive field) and make sure the last convolution’s receptive field covers a whole digit (8×8) at least. Train it like the dense network and report the test accuracy.
# Your code hereYour design and its justification:
Part C — One Change at a Time (20 points)¶
Starting from your network of Part B, change one thing at a time and report the parameter count and test accuracy of each version:
5×5 kernels instead of 3×3;
average pooling instead of max pooling;
a flattened head (
Flatten+Linearon the last feature maps) instead of global max pooling.
Which change matters most here, and why?
# Your code hereYour answer:
Part D — Positions Never Seen (20 points)¶
Build a new training set where every digit is in the left part of the patch (left edge in columns 0 to 6) and a test set where every digit is in the right part (columns 10 to 16). Train the global-pooling network and the flattened-head network of Part C on it, and test both on the left and on the right positions. Explain the result with equivariance and invariance.
# Your code hereYour explanation:
Part E — Look Inside, and Report (20 points)¶
Show the first layer’s 16 filters of your Part B network, and the 16 feature maps of one test patch.
One page for the scanner team: which network you recommend and why (accuracy, size, behaviour at new positions), what the filters show, and one test you would run on real forms before deployment.
# Your code hereYour report:
Grading Rubric¶
| Criterion | Excellent | Adequate | Insufficient |
|---|---|---|---|
| A (15) | numbers and a clear link to locality and weight sharing | numbers only | missing |
| B (25) | within budget, summary with receptive field, justified design | works, no justification | over budget |
| C (20) | one change at a time, the main effect explained | changes mixed | missing |
| D (20) | both heads, the invariance of global pooling explained | numbers only | missing |
| E (20) | filters shown and interpreted, a concrete recommendation and test | generic | missing |