Sub topic 3
Preprocessing and Augmentation
Assume you know basic Python, PyTorch tensors, modules, and the ideas of loss, epochs, and gradient descent. This chapter focuses on turning image files into model-ready tensors while keeping training and evaluation fair.
Why preprocessing matters
A pretrained model expects images in a particular format. ResNet-18, for example, was trained with three-channel RGB images, a 224 × 224 input size, and ImageNet normalization. Normalization changes each color channel so that its values have a familiar scale:
x' = \frac{x-\text{mean}}{\text{standard deviation}}The mean and standard deviation must match the model's pretraining setup. Using different values can make the pretrained features less useful.
Images in a folder may have different sizes, aspect ratios, color modes, or file formats. A transform pipeline makes these differences consistent.
Training and validation transforms
Training needs controlled randomness. Random crops and flips show the model slightly different versions of the same image, which can reduce memorization. This process is called data augmentation. An augmentation is useful only when it preserves the image's label.
Validation and test data need deterministic transforms. Otherwise, the measured score changes because the evaluation images change on every pass.
| Phase | Typical operations | Random? |
|---|---|---|
| Training | Random crop, horizontal flip, tensor conversion, normalization | Yes |
| Validation or test | Resize, center crop, tensor conversion, normalization | No |
from torch.utils.data import DataLoader
from torchvision import datasets, transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tfms = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.8, 1.0)),
transforms.RandomHorizontalFlip(p=0.5),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
eval_tfms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
# Layout:
# data/train/cat/*.jpg
# data/val/cat/*.jpg
train_ds = datasets.ImageFolder("data/train", transform=train_tfms)
val_ds = datasets.ImageFolder("data/val", transform=eval_tfms)
train_loader = DataLoader(
train_ds, batch_size=32, shuffle=True, num_workers=2
)
val_loader = DataLoader(
val_ds, batch_size=32, shuffle=False, num_workers=2
)
print(train_ds.classes)RandomResizedCrop selects a random part of the image and resizes it. The scale argument prevents it from discarding too much of the original image. RandomHorizontalFlip is appropriate when left and right do not change the class. It may be harmful for text, road signs, medical images, or objects with meaningful orientation.
Avoiding preprocessing errors
Apply augmentation only to the training split. Augmenting validation or test images makes evaluation noisy and may hide real errors.
Do not normalize twice. ToTensor changes most 8-bit pixel values from 0–255 to floating-point values between 0 and 1. Normalize then applies the channel-specific transformation.
Convert images to RGB when your files may contain grayscale or four-channel images. ImageFolder usually loads images through PIL, but inconsistent modes can still cause unexpected input shapes.
Keep preprocessing separate from the model. The model should receive tensors with the same shape and normalization during every phase.
Exercise
Why should validation images use deterministic transforms instead of random crops and flips?
Show answer
Deterministic transforms make the evaluation repeatable and measure performance on a consistent representation of each image.