smartyfy.mrindigi.com

Python Master Course V2 — 166. Training Image Classifiers with Data Augmentation

Purpose and learning outcomes

Data augmentation creates additional training views under transformations believed to preserve the label. You will compare two small CPU convolutional classifiers on scikit-learn's bundled digits: one trained normally and one with modest shifts and noise. Validation and test preprocessing remain fixed. The experiment asks whether these specific augmentations help this specific evaluation, not whether augmentation is always beneficial.

  • Apply label-preserving augmentation only to training data
  • Build consistent image transforms and validation preprocessing
  • Compare augmentation choices under fixed evaluation conditions

Prerequisites

  • 143–146: PyTorch and CNNs
  • 161–165: images and features

Environment and execution

Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install numpy scikit-learn torch

Understand the model and its assumptions

The digits dataset contains eight-by-eight grayscale images with intensities from zero to sixteen. Dividing by sixteen establishes a zero-to-one range. Dividing by 255 would unnecessarily compress this dataset's signal. PyTorch convolution expects batch, channels, height, width, so we add a single channel dimension rather than flattening the images.

Augmentation expresses a semantic assumption. A one-pixel shift may preserve a digit when it remains recognizable, while an upside-down rotation can change a six into something resembling a nine. Horizontal reflection is also not universally label-preserving. At this low resolution even one pixel is a substantial fraction of the image, so inspect generated views and keep the transformation budget modest.

Only training examples receive random transformations. If validation is randomly augmented on each call, its score changes because the evaluation task changes, obscuring model comparisons. Apply fixed normalization to all splits, and use separately defined corruption tests if you want to measure robustness. The row-wise stratified split here does not establish writer-disjoint generalization because the bundled labels do not provide that grouping in this exercise.

A fair ablation changes augmentation while holding architecture, initial weights, optimizer settings, training budget, and split fixed. Randomness for shuffling and augmentation is separated so adding augmentation does not also change batch order. One seed is still only one training run. Multiple independently repeated runs are needed before claiming a stable advantage, especially when the difference is small.

Worked example: build it in stages

Split rows into training, validation, and final test sets before tensor construction. The augmentation pads with zeros, crops a shifted window, and adds bounded noise; it does not wrap content around the opposite edge. Both models train for four epochs using the same starting seed and batch-order generator. The test set is evaluated once for each predeclared experimental condition.

import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split

torch.set_num_threads(1)
data = load_digits()
indices = np.arange(len(data.target))
train_idx, remainder = train_test_split(indices, test_size=0.3,
                                       stratify=data.target, random_state=7)
valid_idx, test_idx = train_test_split(remainder, test_size=0.5,
                                     stratify=data.target[remainder], random_state=8)
images = torch.tensor(data.images / 16.0, dtype=torch.float32).unsqueeze(1)
labels = torch.tensor(data.target, dtype=torch.long)

def augment(batch, generator):
    shifted = []
    padded = F.pad(batch, (1, 1, 1, 1))
    for image in padded:
        dy, dx = torch.randint(0, 3, (2,), generator=generator).tolist()
        shifted.append(image[:, dy:dy+8, dx:dx+8])
    result = torch.stack(shifted)
    noise = torch.randn(result.shape, generator=generator) * 0.03
    return (result + noise).clamp(0, 1)

def build_model():
    return nn.Sequential(nn.Conv2d(1, 8, 3, padding=1), nn.ReLU(),
                         nn.MaxPool2d(2), nn.Conv2d(8, 16, 3, padding=1),
                         nn.ReLU(), nn.Flatten(), nn.Linear(16*4*4, 10))

def train(use_augmentation):
    torch.manual_seed(9)
    model = build_model()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.003)
    order_generator = torch.Generator().manual_seed(10)
    augmentation_generator = torch.Generator().manual_seed(11)
    subset = torch.tensor(train_idx, dtype=torch.long)
    for _ in range(4):
        model.train()
        permutation = torch.randperm(len(subset), generator=order_generator)
        for start in range(0, len(subset), 64):
            ids = subset[permutation[start:start+64]]
            x, y = images[ids], labels[ids]
            if use_augmentation:
                x = augment(x, augmentation_generator)
            optimizer.zero_grad()
            loss = F.cross_entropy(model(x), y)
            loss.backward()
            optimizer.step()
    return model

@torch.no_grad()
def accuracy(model, indexes):
    model.eval()
    ids = torch.tensor(indexes, dtype=torch.long)
    predicted = model(images[ids]).argmax(1)
    return float((predicted == labels[ids]).float().mean())

plain, augmented = train(False), train(True)
for name, model in [("plain", plain), ("augmented", augmented)]:
    print(name, "validation:", accuracy(model, valid_idx))
    print(name, "test:", accuracy(model, test_idx))
assert set(train_idx).isdisjoint(test_idx)
assert images.shape[1:] == (1, 8, 8)

What the output means

The program prints measured validation and test accuracies for both training conditions. Neither a score nor an improvement is promised. The augmented model sees a harder training distribution and may need a different budget; changing that budget would be a new experiment to choose on validation data. The final shape assertion confirms one channel and an eight-by-eight grid, independent of learned performance.

Guided lab and acceptance checks

Inspect several original and augmented arrays side by side or as small images before training. Record which digits become ambiguous under the allowed shifts. Run the fixed comparison, then repeat the full experiment with additional training seeds while preserving the data split. Report the distribution of differences rather than selecting the most favorable run.

Acceptance requires training-only augmentation, identical evaluation arrays, disjoint row IDs, and a documented normalization range. If you compare new augmentation strengths, reserve a fresh final evaluation protocol rather than repeatedly optimizing against the printed test score. Record that this split measures held-out rows, not new-writer performance.

Common mistakes and repairs

Do not use torch.roll for a physical translation unless wrapping is intended; it moves edge pixels to the opposite border. Do not normalize these digits as though they were eight-bit photographs. Avoid random validation augmentation and label-changing rotations. Finally, setting one global seed is insufficient for a controlled ablation if two code paths consume randomness differently.

Questions and answers

Why augment only training data?

Training augmentation encourages the model to tolerate a chosen variation. Validation and test sets estimate behavior on a declared distribution. Randomly changing them during measurement makes comparisons noisy and changes the question being answered.

Why avoid flips for digit classification?

Many reflected digits are unnatural or ambiguous, and some transformations change identity. Label preservation is task-specific. A transformation useful for object categories can be inappropriate for characters, symbols, or orientation-dependent inspection.

Does more augmentation always reduce overfitting?

It can regularize learning, but unrealistic or label-changing views introduce harmful training noise. Strong augmentation can also make a small training budget insufficient. Select its type and strength using development evidence rather than treating it as a universal improvement.

Why use separate random generators?

They isolate batch ordering from augmentation draws. Otherwise enabling noise could consume random values and change later shuffles, making the experiment differ in more than the intended factor. Separate streams make controlled comparisons easier to interpret.

What does the bundled digits test establish?

It measures performance on the held-out rows under this split and preprocessing. It does not establish accuracy on phone photographs, new writing instruments, or unseen writers. Those are separate deployment distributions requiring appropriate data and evaluation.

Exercises

1. Verify that augmentation preserves shape and numeric bounds. 2. Confirm that calling evaluation does not mutate the stored test images. 3. Explain why equal training epochs do not imply equal optimization difficulty.

Worked solutions and reasoning

The augmented condition asks the same network to handle more input variation, so its learning curve can differ even with the same update count. That is part of the measured tradeoff. Adjusting budgets after seeing final scores would require a new independent evaluation.

g = torch.Generator().manual_seed(99)
view = augment(images[:5], g)
assert view.shape == images[:5].shape
assert 0 <= float(view.min()) <= float(view.max()) <= 1
saved = images[test_idx].clone()
_ = accuracy(plain, test_idx)
assert torch.equal(saved, images[test_idx])

Recap

Augmentation is a testable statement about label-preserving variation. A careful experiment isolates that statement, leaves evaluation unchanged, and reports both gains and costs. Small CPU models and bundled data are enough to learn this discipline without downloading large models or image collections.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.