Skip to main content

Preprocessing & augmentation

Author

Marie-Hélène Burle

We already saw that, before images reach a model, they must be transformed into tensors with a uniform size and data type, and with values in a sensible range. On top of this, randomly perturbing the training images (augmentation) is a cheap way to get more out of a small dataset and prevent overfitting.

Let’s go back to JupyterHub for this section: it doesn’t require much computing power and that will make visualizing the augmented images as well as playing with code snippets easier.

Setup

from pathlib import Path

import torch
from matplotlib import pyplot as plt
from torch.utils.data import DataLoader, Subset
from torchvision.datasets import EuroSAT
from torchvision.transforms import v2 as T

torch.manual_seed(42)
<torch._C.Generator at 0x7fc90ffc52d0>

In an earlier section we stored a very simple transform as an attribute of the whole dataset because we needed to convert the images to tensors to play with DataLoaders. In this section, we will create more sophisticated transforms for the validation and training sets.

So first, let’s reload the dataset (without any transform this time) and the split saved earlier:

root = Path("/project/def-sponsor00/data")
eurosat = EuroSAT(root=root)
idx = torch.load(root / "split.pt", weights_only=True)

Then let’s pick a training image to work on:

img, label = eurosat[idx["train"][0]]
print(type(img).__name__, img.size, "->", label, eurosat.classes[label])
Image (64, 64) -> 1 Forest

The validation pipeline

A model needs every input as a float32 tensor of the same shape, with values in a comparable range. For evaluation, this conversion must be deterministic.

T.ToImage() turns the PIL image into a uint8 tensor of shape (3, 64, 64) (channels first, which is the layout that PyTorch expects). The values are raw pixel intensities from 0 to 255:

x = T.ToImage()(img)
print(
    f"Tensor shape: {x.shape}\nTensor type: {x.dtype}\nMin, max: {int(x.min())}, {int(x.max())}"
)
Tensor shape: torch.Size([3, 64, 64])
Tensor type: torch.uint8
Min, max: 43, 118

T.ToDtype with scale=True rescales to [0, 1] while converting to float32 (the data type models compute in):

x = T.ToDtype(torch.float32, scale=True)(x)
print(
    f"Tensor shape: {x.shape}\nTensor type: {x.dtype}\nMin, max: {x.min():.3f}, {x.max():.3f}"
)
Tensor shape: torch.Size([3, 64, 64])
Tensor type: torch.float32
Min, max: 0.169, 0.463

Older versions of PyTorch used transforms.ToTensor(): the modern v2 equivalent is ToImage() followed by ToDtype(torch.float32, scale=True).

T.Normalize standardizes each channel (red, green, and blue) by subtracting the mean and dividing by the standard deviation. We use the mean and standard deviation of the ImageNet dataset because later in the course we will use models pretrained on ImageNet, which expect inputs normalized exactly this way. We adopt them for the whole course, including our from-scratch baseline, so that every run stays comparable:

IMAGENET_MEAN = [0.485, 0.456, 0.406]
IMAGENET_STD = [0.229, 0.224, 0.225]

x = T.Normalize(IMAGENET_MEAN, IMAGENET_STD)(x)
print(
    f"Tensor shape: {x.shape}\nTensor type: {x.dtype}\nMin, max: {x.min():.2f}, {x.max():.2f}"
)
Tensor shape: torch.Size([3, 64, 64])
Tensor type: torch.float32
Min, max: -1.38, 0.25

Let’s combine the three steps with T.Compose:

val_tf = T.Compose(
    [
        T.ToImage(),  # PIL image -> uint8 CHW tensor
        T.ToDtype(torch.float32, scale=True),  # /255 -> float32 in [0, 1]
        T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
    ]
)

Our Forest patch normalizes to channel means of about −1.01, −0.65, and +0.11 (far from zero):

print([f"{v:+.2f}" for v in x.mean(dim=(1, 2)).tolist()])
['-1.01', '-0.65', '+0.11']

EuroSAT is darker and greener than the average ImageNet photo. When training a model from scratch, computing your own dataset statistics is a legitimate choice; what matters is using the same statistics everywhere for consistency.

Two things that you will usually need for your own data are missing from this pipeline. EuroSAT images are all 64 × 64 pixels, so there is no T.Resize, and the crop is deterministic at evaluation time, so there is no random crop. For mixed-size images, the standard evaluation recipe is T.Resize(256) followed by T.CenterCrop(224).

Data augmentation

What is data augmentation?

Training deep learning models requires vast amounts of labelled data. The more diverse and numerous the data, the better the models will perform on new, unseen data. Labelled data, however, is limited.

Data augmentation is the artificial creation of new data by modifying the existing data in small ways. This prevents the model from seeing the exact same tensors at each epoch. It is a very effective way to avoid overfitting, particularly where datasets are small (if you were lucky enough to have a huge dataset, you wouldn’t need to bother with data augmentation, which would actually be an additional, computationally costly step with extremely little benefit).

Xu et al. performed a comprehensive survey of image augmentation techniques for deep learning in 2023 [1], but the field is evolving very fast with new techniques coming out all the time.

Validation and test transforms must be deterministic. Random transforms at evaluation time add noise to your metrics and let luck masquerade as performance. Augmentation is a training-time tool.

Augmentation libraries

Data augmentation being such a classic technique, many libraries offer sets of augmentation tools. Among the most popular ones, we can list:

There are others: Amarù et al. created a curated repository of libraries for data augmentation in computer vision [2]. In this course, we will use Torchvision transforms.

Augmentation techniques

There are many techniques:

  • Geometric transformations (flips, rotations, scaling, crops…).
  • Colour space transformations (brightness, contrast, gamma, hue, saturation, grayscale conversion, channel shuffling…).
  • Noise transformations (Gaussian noise, blurring…).
  • Occlusive transformations (erasing parts of the image).
  • Mixing images (various techniques mixing images and appropriately applying the same treatment to labels).

For a quick, strong default on natural images, torchvision also ships one-liner policies such as T.TrivialAugmentWide and T.RandAugment, which compose random transforms for you.

Choosing techniques

How many to use?

The size of your dataset dictates how aggressively you should augment.

Dataset size Strategy Recommended count
Tiny (<1k images) Heavy augmentation. You should be worried about overfitting, so you need to create more artificial data 4-6 techniques
Medium (1k - 100k) Standard augmentation. Balance variety with training speed 3-4 techniques
Large (>100k images) Light augmentation. 1-2 techniques
Massive (>1M images) No augmentation. The data itself provides enough diversity. Augmentation will only slow down training. 0 techniques


Our dataset contains 27K images (including the validation set). This puts us in the medium category, and a standard approach with 3 or 4 techniques should be reasonable.

Which ones to use?

Which augmentation to choose is domain-specific: every transform must be label-preserving and representative of real variation. Which transform will respect this depends on the type of data.

For instance, geometric flips and rotations would not work for handwritten digits (rotations would turn some 6s into 9s, and flipping text left to right destroys it). For satellite images, which look straight down, however, a field, a highway, or a lake flipped or rotated still belongs to the same class.

Conversely, photometric jitter on satellite images could be tricky: colour carries a physical signal there (e.g. vegetation vs water), but it is safe for handwritten digits.

The training pipeline

Order matters: the random transforms sit before the dtype conversion because geometry on uint8 tensors is cheaper than on float32, and Normalize must come last:

train_tf = T.Compose(
    [
        T.ToImage(),
        T.RandomHorizontalFlip(),  # p=0.5 by default
        T.RandomVerticalFlip(),  # p=0.5 by default
        T.RandomRotation(90),  # random angle in [-90, 90]
        T.ToDtype(torch.float32, scale=True),
        T.Normalize(IMAGENET_MEAN, IMAGENET_STD),
    ]
)

Here is one image (a highway) next to seven versions of it produced by the random part of the pipeline:

aug_display = T.Compose(
    [  # for screens: without Normalize
        T.ToImage(),
        T.RandomHorizontalFlip(),
        T.RandomVerticalFlip(),
        T.RandomRotation(90),
    ]
)

img, label = eurosat[10000]
print(label, eurosat.classes[label])
fig, axes = plt.subplots(2, 4, figsize=(10.5, 5.5))
axes.flat[0].imshow(img)
axes.flat[0].set_title("original", fontsize=9)
axes.flat[0].axis("off")
for ax in axes.flat[1:]:
    ax.imshow(aug_display(img).permute(1, 2, 0))  # CHW -> HWC
    ax.axis("off")
3 Highway

Every call draws fresh random parameters:

a, b, c = train_tf(img), train_tf(img), train_tf(img)
print(torch.equal(a, b), torch.equal(b, c))
False False

Our 21,600 training files now yield effectively unbounded distinct training tensors: after 10 epochs, the model has seen each file 10 times, but almost never the same tensor twice.

And the validation transform, being deterministic, returns the same tensor every time:

a, b = val_tf(img), val_tf(img)
print(torch.equal(a, b))
True

Remember that the transforms run inside __getitem__(), once per sample. This means that augmentation is parallelized across the DataLoader worker processes.

On my laptop, one pass over the training set with 16 workers took about 1 s without augmentation and 2.5 s with flips, rotation, and normalization. Cheap transforms keep the workers ahead of the accelerator; expensive ones starve it again. This means that, with augmentation, you might need to increase the number of workers to keep the GPU busy.

Augmentation is a form of regularization: it trades an easy fit on the training set for generalization. Expect the training loss to fall more slowly with augmentation: the task got harder, not the model worse. Judge on validation metrics.

Your turn:

Add T.RandomResizedCrop(64, scale=(0.4, 1.0)) to the training pipeline (right after T.ToImage()), then display 8 variants of one image. Finally, think: which EuroSAT classes could lose their identity if crops get very tight?

  • First hint: start from aug_display and insert the crop right after T.ToImage().
  • Second hint: scale bounds the fraction of the image area kept by the crop.
  • Third hint: two classes are long and thin.

One draw per call

The v2 transforms also accept batches of tensors. But watch out: a transform draws one set of random parameters per call, so the whole batch gets flipped or rotated together:

batch = torch.stack([T.ToImage()(eurosat[i][0]) for i in range(8)])
hflip = T.RandomHorizontalFlip()
for _ in range(4):
    out = hflip(batch)
    print([not torch.equal(out[i], batch[i]) for i in range(8)])
[False, False, False, False, False, False, False, False]
[True, True, True, True, True, True, True, True]
[False, False, False, False, False, False, False, False]
[False, False, False, False, False, False, False, False]

Every line is all True or all False: never a mix. Per-sample randomness must therefore happen on the dataset side, one __getitem__() at a time, as we have set up.

Batched calls remain useful for deterministic transforms such as Normalize.

The complete data pipeline

The data side of the course is now complete: datasets with the right transform per split, loaders with the options measured earlier. Here is what it looks like:

train = Subset(EuroSAT(root=root, transform=train_tf), idx["train"])
val = Subset(EuroSAT(root=root, transform=val_tf), idx["val"])
print(
    f"Length of the training set: {len(train)}\nLength of the validation set: {len(val)}"
)
Length of the training set: 21600
Length of the validation set: 5400
loader_kwargs = {
    "batch_size": 64,
    "num_workers": 8,
    "pin_memory": torch.accelerator.is_available(),
}
train_loader = DataLoader(train, shuffle=True, **loader_kwargs)
val_loader = DataLoader(val, **loader_kwargs)

Of course, we get a warning when we run this on JupyterHub since we requested a single CPU and are asking for 8 processes.

One training batch:

images, labels = next(iter(train_loader))
print(
    f"Images batch shape: {images.shape}\nImages batch type: {images.dtype}\nMin, max image values: {images.min():.2f}, {images.max():.2f}"
)
print(f"First few labels: {labels[:8]}")
Images batch shape: torch.Size([64, 3, 64, 64])
Images batch type: torch.float32
Min, max image values: -2.12, 2.64
First few labels: tensor([7, 2, 9, 7, 8, 1, 1, 9])

Augmented, normalized, shuffled batches of tensors now flow at steady state.

References

1.
Xu M, Yoon S, Fuentes A, Park DS (2023) A comprehensive survey of image augmentation techniques for deep learning. Pattern Recognition 137:109347. https://doi.org/10.1016/j.patcog.2023.109347
2.
Amarù S, Marelli D, Ciocca G, Schettini R (2023) DALib: A curated repository of libraries for data augmentation in computer vision. Journal of Imaging 9(10). https://doi.org/10.3390/jimaging9100232