Augment the Training Photos

A classifier trained on a few hundred photos can learn those photos too well: it remembers where the object sat, which way it faced and how much of the frame it filled, and then does worse on photos it has never seen. Data augmentation counters this by showing the model a slightly different version of every training photo each time it sees it. This page explains how that works, the two changes used most for photographs, how to tell a safe change from one that breaks the label, and why the photos used for measuring are never changed at random.

A new version of each photo in every epoch

Recall what an epoch is: one pass of the training loop over every training example, batch by batch. Without augmentation, a photo reaches the model as exactly the same tensor in epoch 1, epoch 2 and every epoch after. The model can then lower its loss by remembering details that belong to that one photo, such as a cat always sitting in the lower left corner and always facing right. That is the start of overfitting: high accuracy on the training photos, lower accuracy on new ones.

Data augmentation means training on a randomly changed version of each image instead of the image itself. The change is made at the moment the image is loaded, by the dataset's transform, the function that prepares each image. A random transform draws new random numbers every time it is called, so every time a photo is fetched, in every epoch, the model gets a new variant of it:

What the model receives from three photos over three epochs
Epochcat-01.jpgcat-02.jpgdog-01.jpg
1large crop, mirroredtight crop on the headcrop of the left half
2crop of the right sidelarge crop, mirroredtight crop, mirrored
3tight crop, mirroredcrop of the top halflarge crop

Nothing is saved to disk and the dataset does not grow: it still holds three photos and still returns three examples per epoch. What grows is the variety the model sees over the whole training run. Because the position, the size and the direction of the cat change from epoch to epoch, remembering them no longer helps. The features that still lower the loss are the ones every variant shares, such as the shape of ears, the texture of fur and the outline of a face, and those are the features that also appear in photos the model has never seen. That is why augmentation helps most when the dataset is small.

It is not free. The training photos become harder, so the accuracy measured on them usually rises more slowly, and how much the accuracy on new photos improves depends on the data and the model. It is a change to try and then judge by the validation accuracy, not a guaranteed gain.

True or false?

Augmenting a dataset of 500 photos with random crops makes the dataset return more than 500 examples per epoch.

False. The dataset keeps its length. Each of the 500 photos is changed when it is loaded, so every epoch still has 500 examples, each one a fresh variant.

With a random transform, the same training photo usually reaches the model as a different tensor in each epoch.

True. The transform runs again every time the photo is fetched and draws new random numbers each time, so the crop and the flip change from epoch to epoch.

Random crop and random flip

For photographs, two changes are by far the most common, and torchvision's own reference training recipe for classifiers uses exactly these two by default: a random crop that is resized to the input size, and a mirror image made with a set chance.

The random crop is v2.RandomResizedCrop from torchvision.transforms.v2. Each time it is called, it picks a rectangle at a random position inside the photo. The rectangle's area is random, and so is its shape, its aspect ratio (width divided by height). Then it resizes that rectangle to the size you give it.

Two settings limit the random choice. With the default scale=(0.08, 1.0), the rectangle covers anywhere from 8% to 100% of the photo's area. With the default ratio=(0.75, 1.333...), it can be up to a third wider than a square or up to a third taller. Because of the resize at the end, every crop comes out as an image of one fixed size, whatever part of the photo it came from:

  • original photo
  • large crop
  • tight crop
  • no cat in it
  • cat cut out

Each crop shows the object at a different position and a different scale, which is what makes the model less sensitive to where the object sits and how big it is. The third crop shows the risk: a small rectangle can land where the object is not, and the result no longer shows what its label says. The next section returns to that.

Do not confuse it with v2.RandomCrop, which cuts a window of a fixed size at a random position and never resizes. It varies the position only, not the scale.

The random flip is v2.RandomHorizontalFlip(p=0.5). For each image it draws a random number and mirrors the image left to right when that number is below p. With the default 0.5, about half the images are mirrored and half are passed on unchanged, and a photo that was mirrored in one epoch may be the original in the next. A cat facing right becomes a cat facing left, so the model cannot rely on the direction an animal faces.

In a full training transform, the two random steps come right after the photo is converted to a tensor. At that point the image still holds whole numbers from 0 to 255, and the crop and the flip work on it as it is. Only after them come the steps the pretrained weights expect: the conversion to floats from 0 to 1, and normalisation with the mean and standard deviation of the weights:

A training transform with a random crop and a random flip
import torch
from torchvision.transforms import v2

train_transform = v2.Compose([
    v2.ToImage(),                       # Pillow image to a uint8 tensor
    v2.RandomResizedCrop(224),          # random area and shape, resized to 224 x 224
    v2.RandomHorizontalFlip(p=0.5),     # mirror with a chance of one half
    v2.ToDtype(torch.float32, scale=True),  # 0..255 to 0.0..1.0
    v2.Normalize(mean=[0.485, 0.456, 0.406],
                 std=[0.229, 0.224, 0.225]),
])

The output size, 224, and the normalisation values are those of the common ImageNet weights in torchvision. The random steps change which part of the photo is shown and which way it faces, but the tensor that leaves the transform has the size and value range the pretrained network expects, just as an evaluation image does.

True or false?

`v2.RandomHorizontalFlip()` with no arguments mirrors every image it receives.

False. Its default `p` is 0.5, so each image is mirrored with a chance of one half and passed on unchanged otherwise.

With its default settings, `v2.RandomResizedCrop` can return a crop that covered less than a tenth of the original photo.

True. The default `scale` is (0.08, 1.0), so the crop can cover as little as 8% of the photo's area before it is resized to the output size.

Only changes that keep the label true

Every augmented image is trained with the label of the original photo. That is only right when the changed image still shows that class. If it does not, the model is taught something false: it sees one thing and is told it is another. So the question to ask of every augmentation is plain: would a person who looked only at the changed image still give it the same label?

The answer depends on the task, not on the change. A mirrored cat is still a cat, which is why the horizontal flip is safe for most photos of animals, objects and scenes. A mirrored lowercase b is a d, and a road sign with an arrow turning left becomes a sign turning right. The same flip that is harmless in one task swaps the classes in another:

One change, different tasks
ChangePhotos of animalsLetters, digits, arrow signs
Mirror left to rightLabel kept: a cat facing left is still a catLabel can change: b becomes d, a left arrow points right
Turn upside downLabel kept, but such photos hardly ever occurLabel can change: 6 reads as 9
Small random cropLabel lost when the crop misses the animalLabel lost when the crop cuts the symbol
Change of colourUsually kept, unless colour tells classes apartUsually kept

Two kinds of risk show in the table. Some changes produce a different class, like the flipped letter. Others produce an image that shows no class at all, like a small crop that lands on background. The crop's risk depends on how much of the photo the object fills: for photos where the object fills most of the frame, the default range of 8% to 100% works well, while for small objects a higher lower bound, for example scale=(0.5, 1.0), keeps more of the object in every crop.

A change can also keep the label and still be a poor choice. Photos of animals are almost never upside down, so turning them upside down keeps the label but spends training on views that never come up in use. This is why flipping up and down is much less common than flipping left and right. A good augmentation produces images that could plausibly have been taken in the first place.

True or false?

A horizontal flip is safe for any image classification task, because it adds no new content to the image.

False. It adds no content, but it can turn one class into another: a mirrored b is a d, and a mirrored left arrow points right.

An augmentation that keeps the label in one task can change the label in another.

True. Whether a change is safe depends on what the classes are. Turning a photo of a dog upside down keeps it a dog; turning a 6 upside down makes it a 9.

Random for training, fixed for measuring

Augmentation belongs to the training set only. The validation set and the test set exist to measure the model, and a measurement must not depend on chance. If the validation photos were cropped at random, the same weights could score a different accuracy each time they were evaluated. You could then not tell whether a change to the training helped or the crops were just luckier. The same holds for real use, where a photo should get the same answer every time it is classified.

So a classifier has two transforms. The training transform has the random steps. The evaluation transform is one fixed preparation, the same for the validation set, the test set and every photo the finished model classifies. For torchvision's pretrained weights, that fixed preparation is the one bundled with the weights, which the documentation calls the inference transforms: resize, crop the centre, convert to floats and normalise, with no random step.

Which transform each set uses
ImagesTransformWhy
Training setRandom resized crop, random flip, to float, normaliseMore variety than the photos hold
Validation setResize, centre crop, to float, normaliseComparable numbers between runs and epochs
Test setThe same fixed preparationOne measurement that does not depend on chance
A new photo in real useThe same fixed preparationThe same answer every time

Two details catch people out when they set this up in PyTorch. The first is that model.eval() does not switch augmentation off. It only changes how some layers behave, such as batch normalisation. The random crop and flip belong to the dataset, which runs its transform whenever an image is loaded, whatever mode the model is in.

The second is that the pieces random_split returns are Subset objects. All of them read from one dataset, so they share its one transform: setting the transform for the training part sets it for the validation and test parts too. The simple way out is two dataset objects over the same folder, one with each transform, and the same fixed split used to pick from them:

Two datasets over one folder, one split
from torch.utils.data import Subset
from torchvision import datasets, models

weights = models.ResNet18_Weights.IMAGENET1K_V1
eval_transform = weights.transforms()     # resize 256, centre crop 224, normalise

train_source = datasets.ImageFolder("photos", transform=train_transform)
eval_source = datasets.ImageFolder("photos", transform=eval_transform)

# train_idx, val_idx, test_idx: the fixed split, computed once with a seed
train_set = Subset(train_source, train_idx)
val_set = Subset(eval_source, val_idx)
test_set = Subset(eval_source, test_idx)

Because both datasets read the same folder in the same order, an index means the same photo in both, so no photo ends up in two sets. The training transform still ends at the same size and normalisation as eval_transform; only the way it gets there is random.

Random crops and flips also fit into a run that repeats exactly. The v2 transforms draw their random numbers from PyTorch's global random generator, so after torch.manual_seed, with the data loaded in the main process (num_workers=0, the default of DataLoader), the same code produces the same sequence of crops and flips on the same machine and library version.

True or false?

Calling `model.eval()` before validation switches off the random crop and flip of the training transform.

False. `model.eval()` changes layer behaviour such as batch normalisation. The transform belongs to the dataset, so the validation data needs its own fixed transform.

If the validation set used random crops, evaluating the same weights twice could give two different validation accuracies.

True. Each evaluation would see differently cropped and flipped photos, so the accuracy would depend on the draw, not only on the model.