Sub topic 1
Why augment images: overfitting and limited data
Prerequisites
This chapter assumes you know basic Python, that an image is an array of pixel values with height, width, and color channels, and that you have seen supervised classification with a train/validation split. Examples use PyTorch and torchvision.
Why augmentation helps
A model that memorizes its training set performs well on those images and poorly on new ones. This is overfitting. Augmentation reduces it by creating altered copies of each training image, such as a flipped or cropped version, so the model sees more variety than the raw dataset holds. It acts as a regularizer: it limits how closely the model can fit details that do not generalize.
Invariance and label-preserving transforms
An augmentation is useful only if it keeps the label correct. A transform is label-preserving when the true class stays the same after the change. A flipped photo of a cat is still a cat. A horizontal flip of the letter "b" is a "d", so it is not label-preserving for text recognition. Before adding a transform, ask whether a human would assign the same label to the result.
Offline versus online augmentation
Offline augmentation writes new image files once, before training. Online augmentation applies random transforms each time a batch is loaded, so every epoch sees different versions. Online augmentation is usually preferred because it adds variety without storing extra files.
caption: Online augmentation draws a new random transform for each image on every epoch. alt: A flowchart where an original image feeds a random transform step, which feeds the model training batch.
Geometric transforms: flips, crops, rotations, and scaling
Geometric transforms change where pixels sit. Common ones are flips, random crops, rotations, and scaling. The following pipeline applies them to one image:
from PIL import Image
from torchvision import transforms
augment = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.5, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.RandomRotation(degrees=10),
transforms.ToTensor(),
])
img = Image.open("cat.jpg").convert("RGB")
x = augment(img)
print(x.shape) # torch.Size([3, 224, 224])Each call to augment(img) returns a different random view of the image.
> Note: Keep rotations small. Large rotations can cut off the subject or turn it into an unnatural pose.
Exercise
Exercise
Is a horizontal flip label-preserving for recognizing the letters "b" and "d" in scanned text?
Show answer
No. Flipping a "b" horizontally produces a "d", so the label changes. Use flips only when the class is unchanged by mirroring.