Lab: Train a Small CNN with Augmentation
Place the scikit-learn digits at random positions on a larger canvas, normalise them with statistics from the training split, and train an MLP, a small CNN and the same CNN with label-preserving augmentation from torchvision.transforms.v2 on identical splits; then see what a label-breaking flip does and check the result with more seeds.
Contentsand lesson path
On this page
- Goal and setup
- Step 1: Digits on a canvas, and normalisation from the training split
- Step 2: An MLP and a small CNN
- Step 3: The training script, and the MLP
- Step 4: The CNN on the same splits
- Step 5: Augmentation that keeps the label
- Step 6: An augmentation that breaks the label
- Step 7: Check the gain with more seeds
- Check your understanding
- Apply it
- Review prompt
Lessons of CNNs & Computer Vision
- Convolutions: Filters, Strides and Shapes Concept · 20 min
- Lab: Train a Small CNN with Augmentation Lab · 30 min
- Why Residual Networks Train Deeper Concept · 15 min
- Lab: Transfer Learning with a Pretrained Backbone Lab · 30 min
- Beyond Classification: Detection and Segmentation at a Glance Concept · 15 min
- Check: Reading and Adapting a CNN Knowledge check · 8 questions
What you will learn
- Train a small CNN with data augmentation and input normalization and show why it outperforms an MLP on the same images.
Prerequisites: Deep Learning Fundamentals
01. Goal and setup
In the first PyTorch training loop an MLP classified the 8 × 8 scikit-learn digits with about 97% test accuracy. Those digits are cropped and centred; in real photos the object can be anywhere. In this lab every digit is pasted at a random position on a 24 × 24 canvas, and only 300 training images are kept, 30 per digit. You then train three models on the same splits: an MLP, a small CNN, and the same CNN with data augmentation, random changes to the training images that keep their labels true.
You need: Python 3.12, PyTorch 2 with torchvision (CPU builds) and scikit-learn 1.9. Each training run takes under a minute on a laptop CPU. All randomness is seeded and each script uses one CPU thread, so your numbers should match the expected outputs; the last digit can differ on other CPUs or library versions.
cnn-lab/
├── data.py step 1: digits on a canvas, splits, normalisation statistics
├── models.py step 2: the MLP and the small CNN
├── train.py steps 3-6: the training script with optional augmentation
├── augcheck.py step 5: one random draw per image, not per batch
└── compare.py step 7: the same comparison with two more seedsmkdir cnn-lab && cd cnn-lab
python3.12 -m venv .venv
source .venv/bin/activate # Windows: .venv\Scripts\activate
python -m pip install "torch==2.15.*" "torchvision==0.29.*" \
--index-url https://download.pytorch.org/whl/cpu
python -m pip install "scikit-learn==1.9.*"02. Step 1: Digits on a canvas, and normalisation from the training split
place_on_canvas copies each 8 × 8 digit into a blank 24 × 24 image at a random position; there are 17 × 17 = 289 possible positions. The seed fixes the positions, so every model sees the same images. The data is split 60/20/20 by digit as in the earlier lab, and then the training part is cut down to 300 images to imitate a small dataset.
Normalisation shifts and scales the pixels so that they have mean 0 and standard deviation 1 on the training data: x ← (x − mean) / std. Inputs on that scale keep training well behaved. Colour images get one mean and std per channel; here there is one channel. The statistics come from the training split only and are then applied unchanged to validation and test data: they are part of the model, and computing them on test images would leak information about the test set into it.
import numpy as np
import torch
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
CANVAS = 24 # each 8 x 8 digit goes on a 24 x 24 canvas
def place_on_canvas(images, seed=0):
"""Put every digit at a random (but fixed) position on a blank canvas."""
rng = np.random.default_rng(seed)
out = np.zeros((len(images), 1, CANVAS, CANVAS), dtype=np.float32)
rows = rng.integers(0, CANVAS - 8 + 1, size=len(images))
cols = rng.integers(0, CANVAS - 8 + 1, size=len(images))
for i, (r, c) in enumerate(zip(rows, cols)):
out[i, 0, r:r + 8, c:c + 8] = images[i] / 16.0 # pixels 0..16 -> 0..1
return out
def splits(seed=0):
digits = load_digits()
X = place_on_canvas(digits.images, seed)
y = digits.target
X_rest, X_test, y_rest, y_test = train_test_split(
X, y, test_size=0.2, stratify=y, random_state=seed)
X_pool, X_val, y_pool, y_val = train_test_split(
X_rest, y_rest, test_size=0.25, stratify=y_rest, random_state=seed)
# keep only 300 training images (30 per digit) to imitate a small dataset
X_train, _, y_train, _ = train_test_split(
X_pool, y_pool, train_size=300, stratify=y_pool, random_state=seed)
t = lambda a, b: (torch.from_numpy(a), torch.from_numpy(b).long())
return t(X_train, y_train), t(X_val, y_val), t(X_test, y_test)
if __name__ == "__main__":
(Xtr, ytr), (Xva, yva), (Xte, yte) = splits()
print("train / val / test:", len(Xtr), len(Xva), len(Xte))
print("one image:", tuple(Xtr[0].shape), Xtr.dtype)
# normalisation statistics: from the training split only
mean, std = Xtr.mean().item(), Xtr.std().item()
print(f"train mean {mean:.4f} std {std:.4f}")
print(f"share of pixels that are background: {(Xtr == 0).float().mean():.3f}")
r, c = (Xtr[0, 0] > 0).nonzero().min(0).values.tolist()
print(f"first training digit: label {ytr[0].item()}, ink from row {r}, column {c}")python data.pytrain / val / test: 300 360 360
one image: (1, 24, 24) torch.float32
train mean 0.0339 std 0.1576
share of pixels that are background: 0.943
first training digit: label 5, ink from row 0, column 10About 94% of the pixels are background, hence the mean of 0.034. After normalisation a background pixel becomes (0 − 0.0339) / 0.1576 ≈ −0.22 and full ink becomes about 6.1.
03. Step 2: An MLP and a small CNN
The MLP flattens the canvas into 576 numbers and has two hidden layers. The CNN uses the usual modern building block: a 3 × 3 convolution, batch normalisation (BatchNorm), which normalises each channel over the batch and makes training faster and more stable, and ReLU. The convolution has bias=False because BatchNorm subtracts the channel mean straight after it, which would cancel any bias. Two 2 × 2 max-pools shrink 24 × 24 to 6 × 6, and global average pooling turns each of the 64 channels into one number before the final linear layer.
import torch
from torch import nn
class MLP(nn.Module):
def __init__(self, n_in=24 * 24, n_classes=10):
super().__init__()
self.net = nn.Sequential(
nn.Flatten(), # (N, 1, 24, 24) -> (N, 576)
nn.Linear(n_in, 256), nn.ReLU(),
nn.Linear(256, 128), nn.ReLU(),
nn.Linear(128, n_classes),
)
def forward(self, x):
return self.net(x)
def conv_bn(c_in, c_out):
"""3x3 convolution, batch normalisation, ReLU: the usual CNN building block."""
return nn.Sequential(nn.Conv2d(c_in, c_out, 3, padding=1, bias=False),
nn.BatchNorm2d(c_out), nn.ReLU())
class SmallCNN(nn.Module):
def __init__(self, n_classes=10):
super().__init__()
self.features = nn.Sequential(
conv_bn(1, 16), nn.MaxPool2d(2), # 24 x 24 -> 12 x 12
conv_bn(16, 32), nn.MaxPool2d(2), # 12 x 12 -> 6 x 6
conv_bn(32, 64),
nn.AdaptiveAvgPool2d(1), # one average per channel, any position
)
self.head = nn.Linear(64, n_classes)
def forward(self, x):
return self.head(self.features(x).flatten(1))
def n_params(model):
return sum(p.numel() for p in model.parameters())
if __name__ == "__main__":
x = torch.zeros(5, 1, 24, 24)
for model in (MLP(), SmallCNN()):
name = type(model).__name__
print(f"{name:8s} params {n_params(model):7,d} output {tuple(model(x).shape)}")python models.pyMLP params 181,898 output (5, 10)
SmallCNN params 24,058 output (5, 10)The CNN has about 7.5 times fewer parameters than the MLP. Most MLP weights sit in the first layer: 576 × 256 + 256 = 147,712, one per pixel and hidden unit. The CNN reuses its 3 × 3 filters at every position, as explained in the lesson on convolutions.
04. Step 3: The training script, and the MLP
train.py follows the loop from the earlier lab with three additions. make_transforms builds a torchvision.transforms.v2 pipeline: optional augmentation first, then v2.Normalize with the training mean and std. ImageSet is a small Dataset that applies that pipeline to one image at a time in __getitem__; step 5 shows why that matters. It keeps the weights of the epoch with the best validation accuracy and scores them once on the test set. All models get the same budget: AdamW, one learning rate, 40 epochs.
import argparse
import copy
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import v2
from data import splits
from models import MLP, SmallCNN, n_params
torch.set_num_threads(1) # small models: one thread is fast and gives repeatable sums
class ImageSet(Dataset):
"""Transforms one image at a time, so each image gets its own random draw."""
def __init__(self, X, y, transform):
self.X, self.y, self.transform = X, y, transform
def __len__(self):
return len(self.X)
def __getitem__(self, i):
return self.transform(self.X[i]), self.y[i]
def make_transforms(mean, std, augment=False, vflip=False):
steps = []
if augment: # small shifts and rotations keep the label
steps.append(v2.RandomAffine(degrees=10, translate=(0.15, 0.15)))
if vflip: # a vertical flip does not keep the label
steps.append(v2.RandomVerticalFlip(p=0.5))
steps.append(v2.Normalize(mean=[mean], std=[std]))
return v2.Compose(steps)
@torch.no_grad()
def accuracy(model, loader):
model.eval()
correct = sum((model(x).argmax(1) == y).sum().item() for x, y in loader)
return correct / len(loader.dataset)
def fit(kind, augment=False, vflip=False, seed=0, epochs=40, verbose=True):
torch.manual_seed(seed)
(Xtr, ytr), (Xva, yva), (Xte, yte) = splits()
mean, std = Xtr.mean().item(), Xtr.std().item() # training split only
plain = make_transforms(mean, std)
train_tf = make_transforms(mean, std, augment, vflip)
g = torch.Generator().manual_seed(seed)
train = DataLoader(ImageSet(Xtr, ytr, train_tf), batch_size=64, shuffle=True,
generator=g)
val = DataLoader(ImageSet(Xva, yva, plain), batch_size=256)
test = DataLoader(ImageSet(Xte, yte, plain), batch_size=256)
model = MLP() if kind == "mlp" else SmallCNN()
opt = torch.optim.AdamW(model.parameters(), lr=3e-3, weight_decay=0.01)
loss_fn = nn.CrossEntropyLoss()
best_acc, best_state = -1.0, None
for epoch in range(1, epochs + 1):
model.train()
total = 0.0
for x, y in train:
loss = loss_fn(model(x), y)
opt.zero_grad()
loss.backward()
opt.step()
total += loss.item() * len(x)
val_acc = accuracy(model, val)
if val_acc > best_acc:
best_acc, best_state = val_acc, copy.deepcopy(model.state_dict())
if verbose and epoch % 10 == 0:
print(f" epoch {epoch:2d} train loss {total / len(Xtr):.3f} "
f"val acc {val_acc:.3f}")
model.load_state_dict(best_state)
return model, n_params(model), best_acc, accuracy(model, test)
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("kind", choices=["mlp", "cnn"])
ap.add_argument("--augment", action="store_true")
ap.add_argument("--vflip", action="store_true")
a = ap.parse_args()
_, n, val_acc, test_acc = fit(a.kind, a.augment, a.vflip)
print(f"{a.kind}: {n:,} params, best val acc {val_acc:.3f}, "
f"test acc {test_acc:.3f}")python train.py mlp epoch 10 train loss 0.031 val acc 0.131
epoch 20 train loss 0.001 val acc 0.150
epoch 30 train loss 0.001 val acc 0.150
epoch 40 train loss 0.000 val acc 0.150
mlp: 181,898 params, best val acc 0.156, test acc 0.167The MLP drives its training loss to almost zero while validation accuracy stays near 15%, little better than the 10% of guessing. It has memorised the 300 training images, each digit at the one position where it happened to appear. To recognise a 3 at a new position it would need to have seen 3s near there, and 300 images spread over 289 positions do not provide that.
05. Step 4: The CNN on the same splits
python train.py cnn epoch 10 train loss 0.770 val acc 0.739
epoch 20 train loss 0.096 val acc 0.889
epoch 30 train loss 0.026 val acc 0.928
epoch 40 train loss 0.014 val acc 0.917
cnn: 24,058 params, best val acc 0.931, test acc 0.917Same images, same optimiser, same number of epochs: test accuracy rises from 0.167 to 0.917 with 13% of the parameters. Its filters are local and shared: a filter that learns the curve of a 3 at one place detects that curve everywhere, so each training image teaches all positions at once. Global average pooling then keeps how strongly a pattern was found and drops where, which suits a task where position does not matter. It still overfits: training loss falls to 0.014 while validation accuracy levels off near 0.92.
06. Step 5: Augmentation that keeps the label
A label-preserving augmentation is a change after which a person would still give the image the same label. For handwriting, small rotations and shifts qualify, because people write at slightly different angles and places. v2.RandomAffine(degrees=10, translate=(0.15, 0.15)) rotates each training image by up to 10° and shifts it by up to 15% of the width and height. Only the training split is augmented; validation and test images are just normalised.
First, one detail. A v2 transform called on a tensor of shape (N, C, H, W) treats it as one batch and draws one set of random parameters for all N images. The script below compares that with calling the transform on each image separately.
import torch
from torchvision.transforms import v2
from data import splits
torch.manual_seed(0)
(Xtr, ytr), _, _ = splits()
shift = v2.RandomAffine(degrees=0, translate=(0.15, 0.15)) # shifts only, for clarity
def centre(img):
"""Row and column of the centre of the ink in one 24 x 24 image."""
r, c = (img[0] > 0.1).nonzero().float().mean(0).tolist()
return round(r, 1), round(c, 1)
def moved(before, after):
"""How far the ink centre moved: (rows down, columns right)."""
return [(round(a[0] - b[0]), round(a[1] - b[1])) for b, a in zip(before, after)]
# four digits that sit away from the border, so a shift does not cut them off
inner = [i for i in range(len(Xtr)) if Xtr[i, 0, :4].sum() + Xtr[i, 0, -4:].sum()
+ Xtr[i, 0, :, :4].sum() + Xtr[i, 0, :, -4:].sum() == 0][:4]
batch = Xtr[inner]
start = [centre(x) for x in batch]
one_call = [centre(x) for x in shift(batch)]
one_each = [centre(shift(x)) for x in batch]
print("batch of 4 transformed in one call:", moved(start, one_call))
print("each image transformed on its own: ", moved(start, one_each))python augcheck.pybatch of 4 transformed in one call: [(-3, 2), (-3, 2), (-3, 2), (-3, 2)]
each image transformed on its own: [(1, -1), (0, 3), (-1, -1), (-1, -2)]In one call, all four digits moved 3 rows up and 2 columns right; one at a time, each moved differently. That is why ImageSet transforms inside __getitem__. Now train the CNN with augmentation.
python train.py cnn --augment epoch 10 train loss 1.240 val acc 0.703
epoch 20 train loss 0.586 val acc 0.864
epoch 30 train loss 0.378 val acc 0.903
epoch 40 train loss 0.309 val acc 0.947
cnn: 24,058 params, best val acc 0.947, test acc 0.964Test accuracy rises from 0.917 to 0.964. The training loss ends much higher, 0.309 instead of 0.014, as expected: the network rarely sees the same image twice, so it cannot memorise them. Augmentation is a regulariser, something that reduces overfitting: it shows the model variation that the 300 images lack. The cost is slower training, so augmented runs usually need more epochs.
07. Step 6: An augmentation that breaks the label
Augmentations are not neutral. The --vflip option adds v2.RandomVerticalFlip(p=0.5), which turns half of the training images upside down. An upside-down 6 looks like a 9 and an upside-down 7 is no digit at all, yet the labels stay 6 and 7: contradictory examples. The test images are never flipped.
python train.py cnn --augment --vflip epoch 10 train loss 1.511 val acc 0.661
epoch 20 train loss 0.935 val acc 0.703
epoch 30 train loss 0.688 val acc 0.739
epoch 40 train loss 0.506 val acc 0.858
cnn: 24,058 params, best val acc 0.878, test acc 0.853Test accuracy drops from 0.964 to 0.853, below the CNN with no augmentation at all. Whether a transform preserves the label depends on the task: horizontal flips suit photos of animals or cars but mirror digits and letters. For each augmentation, ask whether a person would still give the changed image the same label.
08. Step 7: Check the gain with more seeds
One run can mislead: one test image is worth 0.003, and a different seed changes the initial weights and the batch order. compare.py repeats both CNN runs with seeds 1 and 2 on the same splits; its four trainings take a minute or two.
from train import fit
print("test accuracy with two more seeds (seed 0 is in steps 4 and 5)")
for seed in (1, 2):
_, _, _, plain = fit("cnn", seed=seed, verbose=False)
_, _, _, aug = fit("cnn", augment=True, seed=seed, verbose=False)
print(f"seed {seed}: CNN {plain:.3f} CNN + augmentation {aug:.3f}")python compare.pytest accuracy with two more seeds (seed 0 is in steps 4 and 5)
seed 1: CNN 0.911 CNN + augmentation 0.936
seed 2: CNN 0.911 CNN + augmentation 0.964Augmentation wins with all three seeds, by 0.025 to 0.053, that is 9 to 19 of the 360 test images. Over three seeds the plain CNN averages 0.913 and the augmented one 0.955. The gap is larger than the spread between seeds, so for this data and budget the gain is likely real. It is still one dataset and one split; with more images or epochs the gap could shrink, so repeat the comparison on your own data.
09. Check your understanding
10. Apply it
The practice project trains a CNN from scratch on a small image dataset and compares it with a fine-tuned pretrained backbone. Build the from-scratch half now.
- Pick a dataset of a few hundred images per class (your own photos, or one you download once) and make fixed train, validation and test splits.
- Compute the per-channel mean and std of the training split and use them in
v2.Normalizefor all three splits. - For each augmentation you consider, write down why it keeps the label for your classes, then train with and without it for at least three seeds and report the mean and spread of test accuracy.
11. Review prompt
Without looking back, explain why the MLP failed on digits at random positions while the CNN with fewer parameters did not; say which split the normalisation statistics come from and why; describe what makes an augmentation label-preserving and give one that is and one that is not for handwritten digits; explain why a transform must draw its random parameters per image; and say why one run is not enough to claim that augmentation helps.
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.