Sub topic 3
Preprocessing and augmentation
This chapter assumes you know basic Python and PyTorch tensors. It also assumes you have a rough idea of what a convolutional neural network does with an image, and that your images are already split into train and val folders. You will learn which transforms a pretrained model needs, which ones only help during training, and the mistakes that quietly lower accuracy.
Why preprocessing is not optional
A pretrained network learned from images prepared in one specific way. If you feed it images prepared differently, its features still work, but less well. The weights expect a certain input size, a certain pixel scale, and a certain channel order.
For torchvision's ImageNet models, that means:
- Color images with three channels (RGB).
- Tensors shaped
(3, H, W), withHandWusually 224. - Pixel values scaled to the range 0 to 1, then normalized per channel with the ImageNet mean
[0.485, 0.456, 0.406]and standard deviation[0.229, 0.224, 0.225].
Preprocessing has two jobs. The first is to make every image match what the model expects. This is mandatory and identical for training and evaluation. The second is augmentation, which adds random variation to the training images. It is optional and applies to training only.
The pipeline in order
A transforms.Compose runs its steps in sequence. The order matters.
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tfms = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
val_tfms = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])Both pipelines end the same way: ToTensor and then Normalize. They differ only at the start.
Here is the same idea as a diagram.
What each step does
Resize(256)scales the shorter side to 256 pixels and keeps the aspect ratio. It does not force a square.CenterCrop(224)cuts a 224 by 224 square from the middle. Together withResize(256), this keeps about 87% of the image's width, so the object is not stretched.RandomResizedCrop(224)picks a random region, by default covering 8% to 100% of the image area with a random aspect ratio, and resizes it to 224 by 224. Each epoch shows the network a different view of the same photo.RandomHorizontalFlipmirrors the image left to right with probability 0.5.ToTensorconverts a PIL image to a float tensor, divides by 255, and moves channels to the front.Normalizecomputes(x - mean) / stdfor each channel.
Order rules
- Geometric and color transforms act on PIL images, so they come before
ToTensor. Normalizeacts on tensors, so it comes afterToTensor.Normalizeis always last. Normalizing before a color change would break the statistics.
Why validation must be deterministic
Validation and test images should go through the same fixed steps every time. If you used RandomResizedCrop on the validation set, your accuracy would change from run to run, and you could not tell a real improvement from luck. A deterministic pipeline also tells you how the model behaves on the clean images it will meet in production.
Augmentation is a regularizer, meaning a technique that makes overfitting harder. It makes the training task harder on purpose. So training accuracy measured under augmentation is often lower than validation accuracy early on. This is normal and not a bug.
Choosing augmentations that are safe for your data
Each augmentation encodes a claim: "this change does not alter the label." That claim must be true for your classes.
| Augmentation | Safe when | Harmful when |
|---|---|---|
| Horizontal flip | Animals, vehicles, food, scenery | Text, digits, left/right-sensitive medical images |
| Vertical flip | Aerial or microscope images | Most everyday photos, where "up" has meaning |
| Random rotation | Objects seen at any angle | Scenes with a clear horizon |
| Color jitter | Lighting varies in your data | Color is the label, such as ripe versus unripe fruit |
| Random crop with small scale | Large, centered objects | Small objects that a crop might remove entirely |
A common failure is cropping too aggressively. With the default scale=(0.08, 1.0), some crops show only a patch of fur or a corner of the background, yet keep the label "cat". On a small dataset this adds label noise. You can limit it:
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
gentle_train_tfms = transforms.Compose([
transforms.RandomResizedCrop(224, scale=(0.6, 1.0)),
transforms.RandomHorizontalFlip(),
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])A scale of (0.6, 1.0) keeps at least 60% of the image. Start gentle, then strengthen augmentation only if the gap between training and validation accuracy grows.
Checking your pipeline by looking at it
Most preprocessing bugs are visible. Before training, pull a batch and inspect the numbers and the pictures.
import matplotlib.pyplot as plt
import torch
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),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
train_ds = datasets.ImageFolder("data/train", transform=train_tfms)
loader = DataLoader(train_ds, batch_size=8, shuffle=True)
images, labels = next(iter(loader))
print("shape:", tuple(images.shape))
print("dtype:", images.dtype)
print("min/max:", images.min().item(), images.max().item())
# Undo normalization so the pictures display correctly.
mean_t = torch.tensor(mean).view(1, 3, 1, 1)
std_t = torch.tensor(std).view(1, 3, 1, 1)
shown = (images * std_t + mean_t).clamp(0, 1)
fig, axes = plt.subplots(2, 4, figsize=(10, 5))
for ax, img, lab in zip(axes.flat, shown, labels):
ax.imshow(img.permute(1, 2, 0))
ax.set_title(train_ds.classes[lab])
ax.axis("off")
plt.tight_layout()
plt.show()What to look for:
- The shape should be
(8, 3, 224, 224)and the dtypetorch.float32. - After normalization, values fall roughly between -2.1 and 2.6. If you see values between 0 and 1,
Normalizeis missing. If you see values up to 255,ToTensoris missing. - The displayed images should look like plausible photos with the right labels. Crops that contain nothing recognizable tell you the augmentation is too strong.
Common errors
- Wrong normalization constants. Using
0.5for every channel, or computing statistics from your own data, works poorly with frozen pretrained weights. Use the constants the weights were trained with. You can read them frommodels.ResNet18_Weights.DEFAULT.transforms(), which also shows the expected resize and crop sizes. - Different normalization at inference. If you train with
Normalizeand then predict on raw tensors, the outputs are close to meaningless. Reuseval_tfmsfor every prediction. - Augmenting the validation set. This makes metrics noisy and hides real changes.
- Grayscale or RGBA files.
ImageFolderopens files with PIL'sRGBconversion by default, so the usual loader handles these. If you write your own loader withImage.open, call.convert("RGB"), or a one-channel or four-channel image will crash the first convolution. - Augmentation that changes the label. Flipping a dataset of the letters "b" and "d" teaches the model nothing useful.
- Resizing to a square by squashing.
Resize((224, 224))distorts aspect ratio. A pretrained model can cope, but accuracy on thin or wide objects often drops. PreferResize(256)followed by a crop. - Expecting augmentation to run once. Random transforms run each time an image is loaded, so every epoch sees new variations. Nothing is saved to disk, and the dataset size on disk does not change.
Cost and speed
Transforms run on the CPU inside the DataLoader workers. Decoding large JPEG files and cropping them can become the bottleneck, leaving a fast GPU idle. If training is slow, check the following:
- Increase
num_workers, which sets how many parallel processes load data. - Shrink very large source images ahead of time, for example to a longer side of 512 pixels. This works if your crops still look right.
- Keep the pipeline short. Each extra transform costs time on every image in every epoch.
from torch.utils.data import DataLoader
train_loader = DataLoader(
train_ds,
batch_size=32,
shuffle=True,
num_workers=4,
pin_memory=True,
)pin_memory=True speeds up copying batches to a GPU. It has no effect on a CPU-only machine.
Summary of rules
- Every image, in every phase, must be RGB, the right size, scaled to 0 to 1, and normalized with the pretrained model's constants.
- Training adds random augmentation. Validation, test, and inference use fixed resize and center crop.
- Choose augmentations only if they preserve the label for your classes.
- Look at a batch before you train.
Exercise
Your validation pipeline is Resize(256), CenterCrop(224), ToTensor(), Normalize(mean, std). A colleague moves Normalize before ToTensor to "normalize first." What happens, and why is the order fixed?
Show answer
The code raises an error. Normalize works on tensors, but before ToTensor the data is still a PIL image, so Normalize fails. The order is fixed because ToTensor first converts the image to a float tensor scaled to 0 to 1, and only then can per-channel mean and standard deviation be applied. Geometric transforms such as resize and crop work on PIL images and come first.
Exercise
You are classifying photos of ripe and unripe bananas. You add ColorJitter(hue=0.3) and RandomHorizontalFlip(). Training accuracy is poor and validation accuracy does not improve. Which augmentation is the likely cause, and what would you do?
Show answer
The hue jitter is the likely cause. Color is what separates the classes, so shifting hue can turn a green banana yellow while keeping the "unripe" label, which makes the labels wrong. Remove the hue change, or reduce color jitter to small brightness and contrast changes. The horizontal flip is safe here, since flipping a banana does not change its ripeness.
Exercise
You print the min and max of a training batch and see 0.0 and 1.0. What is wrong, and how do you fix it?
Show answer
The images were scaled to 0 to 1 by ToTensor but not normalized, so Normalize(mean, std) is missing or not applied. Add transforms.Normalize(mean, std) after ToTensor in the pipeline. After the fix, the values should range roughly from -2.1 to 2.6.