Chapter 19 — Assignment Project: A Classifier From 500 Photographs
Overview¶
A wildlife project wants to sort camera photos into five kinds of animal: bird, cat, deer, dog and frog. It has labelled 100 photos of each. You will measure what a network trained from scratch can do with so little data, compare two pretrained backbones as feature extractors, fine-tune the better one, find how many labelled photos are really needed, and recommend a strategy. We use CIFAR-10’s photos of these five classes (32×32 pixels), and a fixed test set of 500 photos that you use only to report.
| Part | Task | Points |
|---|---|---|
| A | A baseline from scratch | 15 |
| B | Two backbones as feature extractors | 20 |
| C | Fine-tuning | 25 |
| D | How many photos are needed? | 20 |
| E | Recommendation | 20 |
import copy
import time
from pathlib import Path
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import matplotlib.pyplot as plt
from torchvision.models import resnet18, ResNet18_Weights, mobilenet_v3_small, MobileNet_V3_Small_Weights
torch.set_num_threads(4)
root = Path.home() / '.cache' / 'ai-book-data'
train_set = torchvision.datasets.CIFAR10(root, train=True, download=True)
test_set = torchvision.datasets.CIFAR10(root, train=False, download=True)
KEEP = [2, 3, 4, 5, 6] # bird, cat, deer, dog, frog
names = [train_set.classes[c] for c in KEEP]
rng = np.random.default_rng(42)
def subset(ds, n_per_class):
t = np.array(ds.targets)
idx = np.concatenate([rng.choice(np.where(t == c)[0], n_per_class, replace=False) for c in KEEP])
X = torch.tensor(ds.data[idx]).permute(0, 3, 1, 2).float() / 255
y = torch.tensor([KEEP.index(c) for c in t[idx]])
return X, y
Xtr, ytr = subset(train_set, 100)
Xte, yte = subset(test_set, 100)
print(names, tuple(Xtr.shape), tuple(Xte.shape))
def fit(net, H, H_flip, y, epochs, lr, batch=32, seed=0):
"""Adam on the trainable parameters; random horizontal flips; frozen batch norm stays in evaluation mode."""
opt = torch.optim.Adam([p for p in net.parameters() if p.requires_grad], lr); g = torch.Generator().manual_seed(seed)
for ep in range(epochs):
net.train()
for m in net.modules():
if isinstance(m, nn.BatchNorm2d) and not next(m.parameters()).requires_grad: m.eval()
for idx in torch.randperm(len(H), generator=g).split(batch):
hb = torch.where(torch.rand(len(idx), *[1] * (H.dim() - 1), generator=g) < 0.5, H_flip[idx], H[idx])
opt.zero_grad(); F.cross_entropy(net(hb), y[idx]).backward(); opt.step()
net.eval(); return net
def accuracy(net, H, y):
with torch.no_grad(): return float(torch.cat([net(H[i:i + 250]).argmax(1) for i in range(0, len(H), 250)]).eq(y).float().mean())Part A — A Baseline From Scratch (15 points)¶
Train the small CNN below from scratch for 30 epochs (Adam, 10-3, with fit) on the 500 training photos. Report its parameter count and test accuracy. What would a random guess score?
def small_cnn(k=5):
return nn.Sequential(nn.Conv2d(3, 32, 3, padding=1), nn.BatchNorm2d(32), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(32, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(),
nn.AdaptiveAvgPool2d(1), nn.Flatten(), nn.Linear(128, k))# Your code herePart B — Two Backbones as Feature Extractors (20 points)¶
Extract pooled features from ResNet-18 and MobileNet-V3-Small, both pretrained on ImageNet, at an input size of 96×96 with ImageNet normalisation (for the training photos, their mirror images, and the test photos).
Train a linear head on each for 30 epochs (10-3). Report the feature size, the extraction time and the test accuracy of each.
Which backbone would you keep, and why? Consider accuracy, speed and size.
# Your code hereYour choice and why:
Part C — Fine-Tuning (25 points)¶
Keep ResNet-18. Cache the output of layer3 (for the training photos, their mirror images and the test photos), then compare, with 10 epochs each:
the head alone on pooled features (Part B);
layer4and a new head, with one learning rate of 10-4;layer4at 10-4 and the head at 10-3, as two parameter groups;layer4and the head at 10-2.
Explain the differences.
# Your code hereYour explanation:
Part D — How Many Photos Are Needed? (20 points)¶
With 10, 25, 50 and 100 training photos per class (the first ones of each class in Xtr), compare the ResNet-18 feature extractor (linear head, 30 epochs) with the small CNN from scratch (30 epochs). Plot both curves. From how many photos per class does the pretrained model reach the accuracy that the CNN from scratch gets with 100?
# Your code hereYour answer:
Part E — Recommendation (20 points)¶
One page for the wildlife project:
which approach you recommend (backbone, frozen or fine-tuned, learning rates), with the evidence;
how many photos they should label, from Part D;
the risks: the camera photos are larger, at night, often blurred; and ImageNet’s own biases;
how they should check the model on their own photos before relying on it.
Grading Rubric¶
| Criterion | Excellent | Adequate | Insufficient |
|---|---|---|---|
| A (15) | accuracy against chance, overfitting discussed | number only | missing |
| B (20) | both backbones, the trade-off argued | numbers only | one backbone |
| C (25) | four variants, the effect of the rate explained | variants without explanation | missing |
| D (20) | both curves, the crossing point read off | one curve | missing |
| E (20) | concrete, evidence-based, honest about the domain gap | generic | missing |