Training a CNN Image Classifier in PyTorch
The previous lesson ended with a hand-designed baseline, HOG features and a linear SVM, at 0.940 test accuracy on 600 generated shape crops, and showed it collapsing when the test images were rotated (0.302 at 45 degrees) or noisier (0.550). This lesson trains a small convolutional network on exactly the same crops and the same test set, and then does what the classical pipeline could not easily do: teaches the model the invariances it needs through data augmentation. How convolution, pooling and backpropagation work is the subject of Deep Learning (convolution layers, pooling and receptive fields, a CNN from scratch); here they are used, with the decisions that are specific to images: input normalisation, which augmentations keep the label, how to split and select, and what the first layer learns.
What a convolution layer gives an image model
A convolution slides the same small kernel over every position. The lab shows one kernel (Sobel x, a vertical-edge detector) on a image; try the other kernels.
Two properties follow, and they are exactly what the pixel classifier lacked:
- Weight sharing: a kernel that detects an edge detects it anywhere, so a shape at a new position produces the same features, shifted (the feature map is translation-equivariant). A conv layer with 16 kernels of has 448 parameters, whatever the image size; a dense layer from a image to 16 units has 49,168.
- Global average pooling at the end averages each feature map over all positions, which turns equivariance into invariance: the class scores no longer depend on where the shape is.
What convolutions do not give for free is invariance to rotation or scale. A network sees a rotated square as a new pattern unless training showed it rotated squares. That is the job of augmentation.
The network and its sizes
Three convolution blocks (convolution, batch normalisation, ReLU), two of them followed by max pooling, then global average pooling and a linear layer with 3 outputs. A convolution with input channels, kernels of size and a bias has
parameters, and with padding 1 a convolution keeps the height and width. Before writing any PyTorch, the shapes and parameter counts are worth computing by hand (here in NumPy, in your browser), along with the input normalisation: the per-channel mean and standard deviation of the training images only.
import numpy as np, cv2
CLASSES = ["square", "circle", "triangle"]
def make_crop(rng, c, size=32, hard=False):
"""Lesson variant of make_scene: ONE shape of class c on a noisy grey background, size x size RGB uint8.
hard=True (Project 1) adds any rotation, a wider size range and strong pixel noise."""
img = rng.normal(110, 12, (size, size, 3))
r = rng.uniform(5, 13) if hard else rng.uniform(7, 10) # circumradius in pixels
a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a) # inside a disc: rotations keep it in the frame
turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
else:
k = 4 if c == 0 else 3
t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
if hard:
img = img + rng.normal(0, 20, img.shape)
return img.clip(0, 255).astype(np.uint8)
def make_set(rng, n, hard=False):
y = rng.integers(0, 3, n)
return np.array([make_crop(rng, int(c), hard=hard) for c in y]), y
layers = [("conv 3->16", 3, 16, 3, False), ("conv 16->32", 16, 32, 3, True), ("conv 32->64", 32, 64, 3, True)]
h = w = 32; total = 0
print(f"{'input':14s} shape (3, {h}, {w})")
for name, cin, cout, k, pool_before in layers:
if pool_before:
h, w = h // 2, w // 2 # 2 x 2 max pooling, stride 2
conv = cout * (cin * k * k + 1); bn = 2 * cout # batch norm: scale and shift
total += conv + bn
shape = f"({cout}, {h}, {w})"
print(f"{name:14s} shape {shape:13s} parameters {conv:6d} + BN {bn:3d} MACs {cout * cin * k * k * h * w:,}")
head = 64 * 3 + 3; total += head
print(f"{'avgpool + fc':14s} shape {'(3,)':13s} parameters {head:6d}")
print(f"total parameters: {total:,}")
rng = np.random.default_rng(0) # the same images as the previous lesson
X_train, y_train = make_set(rng, 900)
X_test, y_test = make_set(rng, 600)
X_val, y_val = make_set(rng, 300) # new: a validation set for model selection
mean = (X_train / 255).mean(axis=(0, 1, 2)); std = (X_train / 255).std(axis=(0, 1, 2))
print("training-set channel mean (R, G, B):", mean.round(3).tolist())
print("training-set channel std (R, G, B):", std.round(3).tolist())input shape (3, 32, 32)
conv 3->16 shape (16, 32, 32) parameters 448 + BN 32 MACs 442,368
conv 16->32 shape (32, 16, 16) parameters 4640 + BN 64 MACs 1,179,648
conv 32->64 shape (64, 8, 8) parameters 18496 + BN 128 MACs 1,179,648
avgpool + fc shape (3,) parameters 195
total parameters: 24,003
training-set channel mean (R, G, B): [0.444, 0.442, 0.441]
training-set channel std (R, G, B): [0.128, 0.13, 0.128]
The whole network has 24,003 parameters, most of them in the last convolution, and needs about 2.8 million multiply-accumulates per image (the first layer works on the full resolution, the later ones on fewer pixels but many more channels). The channel means are close to the grey background (0.44, about 112 of 255), because the background covers most of every crop. These six numbers are part of the model: they are computed once on the training set and applied unchanged to every validation, test and production image.
Training with an honest split
The data are the same 900 training and 600 test crops as in the previous lesson (same generator, same seed, so the HOG + SVM score of 0.940 is directly comparable), plus 300 new validation crops. The validation set picks the epoch to keep; the test set is evaluated once, with that model, and then under the same robustness transforms as before. The training loop is the standard one (training loop): Adam, cross-entropy, mini-batches of 64, model.train() while training and model.eval() for every evaluation (batch norm behaves differently in the two modes). Everything runs on 4 CPU threads in a few seconds.
import copy
import numpy as np, cv2
import torch
from torch import nn
CLASSES = ["square", "circle", "triangle"]
def make_crop(rng, c, size=32, hard=False):
"""Lesson variant of make_scene: ONE shape of class c on a noisy grey background, size x size RGB uint8.
hard=True (Project 1) adds any rotation, a wider size range and strong pixel noise."""
img = rng.normal(110, 12, (size, size, 3))
r = rng.uniform(5, 13) if hard else rng.uniform(7, 10) # circumradius in pixels
a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a) # inside a disc: rotations keep it in the frame
turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
else:
k = 4 if c == 0 else 3
t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
if hard:
img = img + rng.normal(0, 20, img.shape)
return img.clip(0, 255).astype(np.uint8)
def make_set(rng, n, hard=False):
y = rng.integers(0, 3, n)
return np.array([make_crop(rng, int(c), hard=hard) for c in y]), y
def rotate(X, deg):
M = cv2.getRotationMatrix2D((15.5, 15.5), deg, 1.0)
return np.array([cv2.warpAffine(im, M, (32, 32), borderMode=cv2.BORDER_REFLECT_101) for im in X])
rng = np.random.default_rng(0)
X_train, y_train = make_set(rng, 900)
X_test, y_test = make_set(rng, 600)
X_val, y_val = make_set(rng, 300)
mean = (X_train / 255).mean(axis=(0, 1, 2)); std = (X_train / 255).std(axis=(0, 1, 2))
def to_tensor(X): # (N, H, W, C) uint8 -> (N, C, H, W) normalised float
return torch.tensor(((X / 255 - mean) / std).transpose(0, 3, 1, 2), dtype=torch.float32)
class SmallCNN(nn.Module):
def __init__(self):
super().__init__()
block = lambda cin, cout: [nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU()]
self.features = nn.Sequential(*block(3, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2),
*block(32, 64), nn.AdaptiveAvgPool2d(1), nn.Flatten())
self.head = nn.Linear(64, 3)
def forward(self, x):
return self.head(self.features(x))
def accuracy(model, X, y):
model.eval()
with torch.no_grad():
return (model(X).argmax(1) == y).float().mean().item()
torch.manual_seed(0)
Xtr, ytr = to_tensor(X_train), torch.tensor(y_train)
Xva, yva = to_tensor(X_val), torch.tensor(y_val)
model = SmallCNN()
print("parameters:", sum(p.numel() for p in model.parameters()))
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
best_acc, best_state, best_epoch = 0.0, None, 0
for epoch in range(1, 16):
model.train(); total = 0.0
for idx in torch.randperm(len(ytr)).split(64):
loss = nn.functional.cross_entropy(model(Xtr[idx]), ytr[idx])
opt.zero_grad(); loss.backward(); opt.step()
total += loss.item() * len(idx)
val = accuracy(model, Xva, yva)
if val > best_acc:
best_acc, best_state, best_epoch = val, copy.deepcopy(model.state_dict()), epoch
if epoch % 3 == 0:
print(f"epoch {epoch:2d} train loss {total / len(ytr):.3f} val accuracy {val:.3f}")
model.load_state_dict(best_state)
print(f"kept epoch {best_epoch} (val accuracy {best_acc:.3f})")
noise_rng = np.random.default_rng(1)
tests = {"original": X_test, "rotated 20 deg": rotate(X_test, 20), "rotated 45 deg": rotate(X_test, 45),
"noise sigma 25": np.clip(X_test + noise_rng.normal(0, 25, X_test.shape), 0, 255).astype(np.uint8)}
yte = torch.tensor(y_test)
for name, X in tests.items():
print(f"TEST {name:15s} accuracy {accuracy(model, to_tensor(X), yte):.3f}")
w = model.features[0].weight.detach().mean(1) # (16, 3, 3): first-layer kernels, averaged over R, G, B
sobel_x = torch.tensor([[-1., 0, 1], [-2, 0, 2], [-1, 0, 1]]); sobel_y = sobel_x.T
cos = lambda a, b: (a * b).sum((-2, -1)) / (a.norm(dim=(-2, -1)) * b.norm())
cx, cy = cos(w, sobel_x), cos(w, sobel_y)
print("first-layer kernels most like Sobel x / Sobel y (|cosine|):",
f"{cx.abs().max().item():.2f} (kernel {cx.abs().argmax().item()}) / {cy.abs().max().item():.2f} (kernel {cy.abs().argmax().item()})")
k = int(cy.abs().argmax())
print(f"kernel {k}, mean over colour channels:")
print((w[k] / w[k].abs().max()).numpy().round(2))parameters: 24003
epoch 3 train loss 0.720 val accuracy 0.503
epoch 6 train loss 0.469 val accuracy 0.520
epoch 9 train loss 0.214 val accuracy 0.883
epoch 12 train loss 0.114 val accuracy 0.640
epoch 15 train loss 0.113 val accuracy 0.783
kept epoch 10 (val accuracy 0.963)
TEST original accuracy 0.947
TEST rotated 20 deg accuracy 0.347
TEST rotated 45 deg accuracy 0.318
TEST noise sigma 25 accuracy 0.587
first-layer kernels most like Sobel x / Sobel y (|cosine|): 0.68 (kernel 0) / 0.63 (kernel 2)
kernel 2, mean over colour channels:
[[ 0.91 0.55 0.28]
[ 0.15 -0.28 -0.63]
[ 0.52 -0.63 -1. ]]
Reading the output:
- Validation accuracy jumps around (0.883 at epoch 9, 0.640 at epoch 12) while the training loss falls steadily. With batch norm and a fairly high learning rate, a small network's predictions on new images can swing from one epoch to the next; keeping the best validation epoch (here epoch 10, 0.963) instead of the last one protects against that. A lower learning rate or a schedule would smooth it.
- Test accuracy 0.947, against 0.940 for HOG + SVM on the same 600 images. The difference is 4 images: on this test set the two are tied, and the CNN's 24,003 learned parameters bought nothing over a hand-designed descriptor.
- Robustness is worse, not better. Turned by 20 degrees the CNN drops to 0.347 (HOG + SVM: 0.742), at 45 degrees to 0.318, and with noise to 0.587. A CNN learns what its training data shows; it saw shapes turned by at most 11 degrees and only the generator's mild noise, and nothing in a convolution makes it rotation-invariant.
- The first layer learned edge detectors. Averaged over the colour channels, the kernel closest to Sobel x has with it, and kernel 2 (printed, scaled to a maximum of 1) is mostly a gradient from its top-left to its bottom-right corner: a diagonal edge detector. That is what first layers of image models typically learn, from this toy up to ImageNet networks.
Augmentation: teach the invariances
Data augmentation applies random, label-preserving transformations to each training batch, so that the model sees the variation it should ignore (image augmentation). Which transformations keep the label depends on the classes, and choosing them is a modelling decision:
| Transform | Keeps the label here? | Why |
|---|---|---|
| rotation by any angle | yes | a turned square is still a square (for digits it would not be: 6 and 9) |
| horizontal and vertical flip | yes | all three shapes are symmetric in some axis; a flipped triangle points down, but is still a triangle |
| pixel noise | yes | the class is in the shape |
| colour change | yes | colour is random already |
| strong crop | no | cutting off half a square can leave something that looks like a triangle |
The example rotates every training image by its own random angle (with affine_grid and grid_sample, which apply one rotation matrix per image on the whole batch), flips half of them and adds Gaussian noise of a random strength, only in training. Validation and test images are never augmented: they measure the model on the data as it comes.
import copy, math
import numpy as np, cv2
import torch
from torch import nn
import torch.nn.functional as F
CLASSES = ["square", "circle", "triangle"]
def make_crop(rng, c, size=32, hard=False):
"""Lesson variant of make_scene: ONE shape of class c on a noisy grey background, size x size RGB uint8.
hard=True (Project 1) adds any rotation, a wider size range and strong pixel noise."""
img = rng.normal(110, 12, (size, size, 3))
r = rng.uniform(5, 13) if hard else rng.uniform(7, 10) # circumradius in pixels
a, d = rng.uniform(0, 2 * np.pi), rng.uniform(0, size / 2 - r - 1)
cx, cy = size / 2 + d * np.cos(a), size / 2 + d * np.sin(a) # inside a disc: rotations keep it in the frame
turn = rng.uniform(0, 2 * np.pi) if hard else rng.uniform(-0.2, 0.2)
m = np.zeros((size, size), np.uint8)
if c == 1:
cv2.circle(m, (int(round(cx)), int(round(cy))), int(round(r)), 1, -1)
else:
k = 4 if c == 0 else 3
t = turn + (np.pi / 4 if c == 0 else -np.pi / 2) + np.arange(k) * 2 * np.pi / k
cv2.fillPoly(m, [np.round(np.stack([cx + r * np.cos(t), cy + r * np.sin(t)], 1)).astype(np.int32)], 1)
img[m > 0] = rng.integers(0, 256, 3)
if hard:
img = img + rng.normal(0, 20, img.shape)
return img.clip(0, 255).astype(np.uint8)
def make_set(rng, n, hard=False):
y = rng.integers(0, 3, n)
return np.array([make_crop(rng, int(c), hard=hard) for c in y]), y
def rotate(X, deg):
M = cv2.getRotationMatrix2D((15.5, 15.5), deg, 1.0)
return np.array([cv2.warpAffine(im, M, (32, 32), borderMode=cv2.BORDER_REFLECT_101) for im in X])
rng = np.random.default_rng(0)
X_train, y_train = make_set(rng, 900)
X_test, y_test = make_set(rng, 600)
X_val, y_val = make_set(rng, 300)
mean = (X_train / 255).mean(axis=(0, 1, 2)); std = (X_train / 255).std(axis=(0, 1, 2))
def to_tensor(X):
return torch.tensor(((X / 255 - mean) / std).transpose(0, 3, 1, 2), dtype=torch.float32)
class SmallCNN(nn.Module):
def __init__(self):
super().__init__()
block = lambda cin, cout: [nn.Conv2d(cin, cout, 3, padding=1), nn.BatchNorm2d(cout), nn.ReLU()]
self.features = nn.Sequential(*block(3, 16), nn.MaxPool2d(2), *block(16, 32), nn.MaxPool2d(2),
*block(32, 64), nn.AdaptiveAvgPool2d(1), nn.Flatten())
self.head = nn.Linear(64, 3)
def forward(self, x):
return self.head(self.features(x))
def accuracy(model, X, y):
model.eval()
with torch.no_grad():
return (model(X).argmax(1) == y).float().mean().item()
def augment(x):
"""Random rotation (any angle), random horizontal flip, random noise: one draw per image."""
n = len(x)
a = torch.rand(n) * 2 * math.pi
theta = torch.zeros(n, 2, 3)
theta[:, 0, 0], theta[:, 0, 1], theta[:, 1, 0], theta[:, 1, 1] = a.cos(), -a.sin(), a.sin(), a.cos()
x = F.grid_sample(x, F.affine_grid(theta, list(x.shape), align_corners=False),
padding_mode="reflection", align_corners=False)
flip = torch.rand(n) < 0.5
x[flip] = x[flip].flip(3)
return x + torch.randn_like(x) * torch.rand(n, 1, 1, 1) * 0.5 # noise up to about 16 grey levels
Xtr, ytr = to_tensor(X_train), torch.tensor(y_train)
# the validation set now contains the conditions we care about: original, rotated and noisy copies
val_rng = np.random.default_rng(2)
Xva_all = to_tensor(np.concatenate([X_val, rotate(X_val, 30),
np.clip(X_val + val_rng.normal(0, 25, X_val.shape), 0, 255).astype(np.uint8)]))
yva_all = torch.tensor(np.tile(y_val, 3))
torch.manual_seed(0)
model = SmallCNN()
epochs, steps_per_epoch = 60, 29 # batches of 32: more, smaller steps than before
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
sched = torch.optim.lr_scheduler.OneCycleLR(opt, max_lr=3e-3, total_steps=epochs * steps_per_epoch)
best = (0.0, None, 0)
for epoch in range(1, epochs + 1):
model.train()
for idx in torch.randperm(len(ytr)).split(32):
loss = F.cross_entropy(model(augment(Xtr[idx])), ytr[idx])
opt.zero_grad(); loss.backward(); opt.step(); sched.step()
val = accuracy(model, Xva_all, yva_all)
if val > best[0]:
best = (val, copy.deepcopy(model.state_dict()), epoch)
model.load_state_dict(best[1])
print(f"kept epoch {best[2]} (validation accuracy on original + rotated + noisy: {best[0]:.3f})")
print(f"training accuracy, un-augmented images: {accuracy(model, Xtr, ytr):.3f}")
noise_rng = np.random.default_rng(1)
tests = {"original": X_test, "rotated 20 deg": rotate(X_test, 20), "rotated 45 deg": rotate(X_test, 45),
"noise sigma 25": np.clip(X_test + noise_rng.normal(0, 25, X_test.shape), 0, 255).astype(np.uint8)}
yte = torch.tensor(y_test)
for name, X in tests.items():
print(f"TEST {name:15s} accuracy {accuracy(model, to_tensor(X), yte):.3f}")
model.eval()
with torch.no_grad():
pred = model(to_tensor(X_test)).argmax(1).numpy()
print("confusion matrix, original test images (rows = true square, circle, triangle):")
print(np.array([[int(((y_test == t) & (pred == p)).sum()) for p in range(3)] for t in range(3)]))kept epoch 54 (validation accuracy on original + rotated + noisy: 0.863)
training accuracy, un-augmented images: 0.880
TEST original accuracy 0.852
TEST rotated 20 deg accuracy 0.855
TEST rotated 45 deg accuracy 0.837
TEST noise sigma 25 accuracy 0.767
confusion matrix, original test images (rows = true square, circle, triangle):
[[132 19 42]
[ 23 167 1]
[ 3 1 212]]
Two other things changed besides the augmentation. Augmented data is harder to fit, so training runs longer (60 epochs of batches of 32, about 1,700 steps instead of 225) with a one-cycle learning-rate schedule that warms up and then decays. And the validation set now contains original, rotated (30 degrees) and noisy copies of the 300 validation crops, because the epoch is chosen for the conditions the model must handle. The test set still uses different angles (20 and 45 degrees) and a different noise draw, so nothing about it was used for selection.
With augmentation the picture reverses. The test accuracy is now nearly the same under every condition: 0.852 on the original images, 0.855 and 0.837 turned by 20 and 45 degrees, 0.767 with noise (the model without augmentation: 0.947, 0.347, 0.318, 0.587). The model has learned the invariances, and paid for them with clean accuracy: 0.852 against 0.947. Its training accuracy on the un-augmented images is only 0.880, so it underfits: 24,003 parameters and 60 epochs on 900 images are not enough to recognise every shape at every angle, and the confusion matrix shows where it fails (42 squares called triangles, 19 squares and 23 circles confused). That is a capacity and data problem, with the usual remedies: a larger network, more images, longer training. The choice between the two models is a product decision: if deployed images can be rotated, the first model's 0.947 is a number that will not survive contact with them.
Pitfalls
- Normalisation statistics from the whole dataset, or from the test set: compute them on the training images, store them with the model, and apply the same numbers at inference.
- Channel order and layout. NumPy images are
(H, W, C), PyTorch expects(N, C, H, W); OpenCV loads BGR. A transposed or BGR input trains without error and fails on real data. - Augmenting the validation or test set, or a label-changing augmentation (crops that cut objects, rotations of digits).
- Forgetting
model.eval()when evaluating: batch norm then uses the statistics of the evaluation batch, and the score depends on the batch size. - Selecting the epoch on the test set. Use a validation set (or cross-validation), then report the test score once.
- Small test sets, big claims. 600 test images give each a weight of about 0.0017; differences of a few images between two models are noise. Repeat with several seeds before claiming a winner.
- Generated data. These shapes are far simpler than photographs. A real project starts from a pretrained backbone (pretrained models and transfer), not from 24,000 random weights.
Practice
- How many parameters would the first convolution have with 5 x 5 kernels and 32 output channels on RGB input?
- A colleague mirrors handwritten digits as augmentation. What goes wrong, and for which classes?
- The augmented model was selected on a validation set containing rotated images. Why is it still fair to report its test accuracy on rotated test images?
Answer
- .
- Mirroring is not label-preserving for digits: a mirrored 2, 3, 4, 5, 7 or 9 is not a valid digit (or looks like another one), so the model learns from wrong or impossible examples and may confuse classes. Use small rotations, shifts and scaling instead.
- The validation and test sets are different images, rotated by different angles (30 for validation, 20 and 45 for test) with different noise draws. The test set was used once, after all choices; including the expected conditions in the validation set is the honest way to select for them.
Test yourself
Why does a CNN with global average pooling recognise a shape wherever it appears in the image, while logistic regression on raw pixels does not?
- CNNs have more parameters
- Shared convolution kernels detect the same pattern at every position, and averaging over all positions removes where it was found
- CNNs use grey images
- Pooling rotates the image
Which statistic should be used to normalise the input channels of a CNN?
- The mean and standard deviation of the test set
- The mean and standard deviation of the training set, stored and reused at inference
- Each image's own mean, recomputed at test time only
- No normalisation is needed
A conv layer has 16 input channels, 32 output channels, 3 x 3 kernels and biases. How many parameters?
- 4,608
- 4,640
- 9,248
- 512
Which augmentation is NOT label-preserving for a classifier of handwritten digits?
- A shift by 2 pixels
- Slight blur
- Rotation by 180 degrees
- A small brightness change