Level 3 In-Depth AI · Vision, Audio and Multimodal
Data Augmentation
Make more training data out of the data you have by flipping, cropping, recolouring, blending and masking it, in ways that don't change the right answer. It is the cheapest reliable way to make a vision, audio or text model more accurate and more robust.
- Level
- ●●●●● Easy
- Reading
- 12 min
- To learn it well
- 45 minutes to read, an hour to practise
- Builds on
- 18 concepts →
- Quiz
- 5 questions ↓
Read first
Image ClassificationThis leads to
—The full path from zero — 18 concepts before this one
- What Is AI?
- Vectors
- Derivatives and Slopes
- Probability Basics
- How Machines Learn
- Partial Derivatives and Gradients
- Matrices and Matrix Multiplication
- Supervised, Unsupervised and Reinforcement Learning
- Gradient Descent
- Tensors and Shapes
- Supervised Learning
- Images as Data
- Linear Regression
- The Perceptron
- Logistic Regression
- Neural Networks
- Convolutional Neural Networks
- Image Classification
- Data Augmentation
Read them roughly in this order. See it on the concept map →
Why it matters
Deep networks are hungry for data, and labelled data is expensive. A model trained on 500 photos of your product will overfit: it memorises those exact pixels instead of learning what the product looks like. Augmentation fights this by showing the model a slightly different version of each training example every time it sees it: mirrored, cropped, brighter, rotated, partly hidden. The model can't memorise pixels that keep changing, so it has to learn the features that survive the changes.
Every serious vision training recipe uses it. AlexNet's 2012 win relied on random crops and flips. Much of the accuracy gained by later CNN architectures came from better augmentation. Vision Transformers only matched CNNs on ImageNet-sized data once they were trained with heavy augmentation. Speech recognisers use SpecAugment, and text models use paraphrasing. It costs no extra labelling and only a little extra compute.
The intuition
Suppose you teach a child what a dog is using one photo of a brown dog facing left. They might conclude that dogs are brown and face left. Show them the same dog facing right, close up, far away, in dim light and half hidden behind a sofa, and they learn what actually makes it a dog.
Augmentation does this for a model. You choose transformations that change the picture but not the answer: a flipped cat is still a cat, and a darker cat is still a cat. These are called label-preserving transformations. By training on random transformations, you tell the model which differences don't matter. In technical terms, you are teaching it to be invariant to them.
Crucially, the transformations are applied on the fly, freshly randomised every time an image is loaded. Over 100 epochs, each photo appears in 100 different versions. That is why augmentation multiplies your effective dataset without using any extra disk space.
Key idea Augment with transformations that don't change the correct label for your task, randomise them anew on every pass, and apply them only during training. At test time, use the plain image.
How it works
Geometric transformations
- Horizontal flip (with probability 0.5): almost free and almost always safe for natural photos. A vertical flip is usually not safe, because skies are on top. It is fine for satellite images and microscope slides, which have no "up".
- Random resized crop: pick a random rectangle covering between 8% and 100% of the image area, with a random aspect ratio between 3:4 and 4:3, and resize it to the training size, for example 224 × 224. This is the standard ImageNet training transformation (torchvision's
RandomResizedCropdefaults). It teaches the model to recognise objects at different scales, positions and partial views. - Rotation, shift, zoom and shear (affine transformations): small random amounts suit handwriting, documents and medical images.
- Perspective and elastic distortions: useful for handwriting and for documents photographed at an angle.
Photometric transformations
- Colour jitter: random changes to brightness, contrast, saturation and hue. It protects against different cameras, white balance and lighting.
- Greyscale with a small probability, blur, sharpening, noise and JPEG compression. These make the model robust to poor image quality.
Hiding parts of the image
Random erasing (also called Cutout) blanks out a random rectangle by filling it with noise or a constant. The model can no longer rely on one telltale region, such as a dog's face, and has to use the whole object. This is a form of Dropout and Regularizing Neural Networks applied to the input.
Mixing images: mixup and CutMix
These two go further and change the labels too.
Mixup blends two random training images and their one-hot labels with the same weight :
Here and are two images, and their labels written as one-hot vectors (a 1 in the position of the true class and 0 elsewhere), and is a random number between 0 and 1 drawn from a Beta(, ) distribution. With small , such as 0.2, is usually close to 0 or 1, so most blends are mostly one image.
Worked example. With , a house image (class 0) and a boat image (class 2) among four classes give the label . The model is trained to say "70% house, 30% boat". The cross-entropy loss works unchanged with such soft targets.
CutMix pastes a random rectangle from image into image , and sets to the fraction of image that is still visible. If the patch covers a quarter of the image, the label is 75% and 25% . Unlike mixup, every pixel stays realistic.
Both act as strong regularisers. They discourage the model from making overconfident, sharply switching predictions between classes, and they tend to improve calibration as well as accuracy. Modern ImageNet recipes typically apply one of the two to each batch at random.
Automatic policies: RandAugment and friends
Which transformations, how strong and how often? AutoAugment (2018) searched for the best "policy" with reinforcement learning, at a large compute cost. RandAugment (2019) showed you can skip the search: for each image, pick operations at random from a fixed list (rotate, shear, posterise, solarise, contrast, and so on) and apply each at a shared strength . Two numbers to tune, such as and , matched the searched policies. TrivialAugment (2021) simplifies further: one random operation at a random strength, with nothing to tune at all.
Test-time augmentation
At prediction time you can average the model's outputs over a few augmented versions of the test image, such as the original and its mirror image, or five crops. This test-time augmentation (TTA) often adds a fraction of a percent of accuracy, at the cost of several times more computation per prediction.
Beyond images: audio and text
Audio (see Audio as Data):
- Add background noise, or simulate a room's echo.
- Change the speed by a few per cent (speed perturbation), or shift the pitch.
- SpecAugment masks random stripes of time and of frequency in the spectrogram, so the model can't depend on any single moment or frequency band. It was a large, cheap gain for Speech Recognition.
Text is harder, because changing one word can flip the meaning ("not good"). Common techniques:
- Synonym replacement, random insertion, swap and deletion of words. These are the four "EDA" operations, and they help most for small classification datasets.
- Back-translation: translate the sentence into another language and back again to get a natural paraphrase.
- Paraphrasing with a language model. This blends into Synthetic Data.
In code
A real experiment on the digits dataset. Train the same small CNN on only 200 images, with and without random small rotations, shifts and zooms, and average over 5 random seeds. It takes about half a minute on a laptop.
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
X = torch.tensor(digits.images, dtype=torch.float32).unsqueeze(1) / 16.0
y = torch.tensor(digits.target)
X_train, X_test, y_train, y_test = train_test_split(
X, y, train_size=200, random_state=0, stratify=y) # only 200 training images
def random_affine(x, max_deg=12, max_shift=0.16, scale=(0.9, 1.1)):
"""Rotate, shift and zoom each image by a small random amount."""
n = len(x)
a = (torch.rand(n) * 2 - 1) * math.radians(max_deg) # angle
s = torch.empty(n).uniform_(*scale) # zoom
tx, ty = (torch.rand(2, n) * 2 - 1) * max_shift # shift (fraction of half-width)
theta = torch.stack([torch.stack([a.cos() / s, -a.sin() / s, tx], 1),
torch.stack([a.sin() / s, a.cos() / s, ty], 1)], 1)
grid = F.affine_grid(theta, x.shape, align_corners=False)
return F.grid_sample(x, grid, align_corners=False)
def train_and_test(augment, seed):
torch.manual_seed(seed)
model = nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2),
nn.Flatten(), nn.Linear(128, 10))
opt = torch.optim.Adam(model.parameters(), lr=3e-3)
for epoch in range(100):
for i in torch.randperm(len(X_train)).split(32):
xb = random_affine(X_train[i]) if augment else X_train[i] # new variant every time
loss = F.cross_entropy(model(xb), y_train[i])
opt.zero_grad(); loss.backward(); opt.step()
with torch.no_grad():
return (model(X_test).argmax(1) == y_test).float().mean().item()
for augment in [False, True]:
accs = [train_and_test(augment, seed) for seed in range(5)]
print(f"augment={augment!s:5} mean test accuracy {sum(accs) / len(accs):.3f}")
# augment=False mean test accuracy 0.938
# augment=True mean test accuracy 0.957
Test error drops from 6.2% to 4.3%, almost a third fewer mistakes, with no new data. Mixup and CutMix take only a few lines each:
import torch
import torch.nn.functional as F
def mixup(x, y, num_classes, alpha=0.2):
lam = torch.distributions.Beta(alpha, alpha).sample().item()
perm = torch.randperm(len(x))
y1 = F.one_hot(y, num_classes).float()
return lam * x + (1 - lam) * x[perm], lam * y1 + (1 - lam) * y1[perm]
def cutmix(x, y, num_classes, alpha=1.0):
lam = torch.distributions.Beta(alpha, alpha).sample().item()
perm = torch.randperm(len(x))
H, W = x.shape[-2:]
h, w = int(H * (1 - lam) ** 0.5), int(W * (1 - lam) ** 0.5) # box covers 1 - lam of the area
top, left = torch.randint(0, H - h + 1, (1,)).item(), torch.randint(0, W - w + 1, (1,)).item()
x = x.clone()
x[..., top:top + h, left:left + w] = x[perm][..., top:top + h, left:left + w]
lam = 1 - h * w / (H * W) # exact share of the original image
y1 = F.one_hot(y, num_classes).float()
return x, lam * y1 + (1 - lam) * y1[perm]
torch.manual_seed(3)
x, y = torch.rand(4, 3, 32, 32), torch.tensor([0, 1, 2, 3])
xm, ym = mixup(x, y, num_classes=4)
xc, yc = cutmix(x, y, num_classes=4)
print("mixup label :", [round(v, 2) for v in ym[0].tolist()]) # [0.9, 0.1, 0.0, 0.0]
print("cutmix label:", [round(v, 2) for v in yc[0].tolist()]) # [0.53, 0.0, 0.47, 0.0]
loss = F.cross_entropy(torch.randn(4, 4), yc) # soft targets work directly
In a real project, use torchvision's ready-made transforms. A typical modern ImageNet-style training pipeline:
import torch
from torchvision.transforms import v2
NUM_CLASSES = 10
train_tf = v2.Compose([
v2.ToImage(),
v2.RandomResizedCrop(224, scale=(0.08, 1.0)),
v2.RandomHorizontalFlip(),
v2.RandAugment(num_ops=2, magnitude=9),
v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
v2.RandomErasing(p=0.25),
])
eval_tf = v2.Compose([ # no randomness at test time
v2.ToImage(), v2.Resize(256), v2.CenterCrop(224),
v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
mix = v2.RandomChoice([v2.MixUp(num_classes=NUM_CLASSES), v2.CutMix(num_classes=NUM_CLASSES)])
# in the training loop, per batch: images, labels = mix(images, labels)
Common pitfalls
- Transformations that change the label. Flipping a "b" makes a "d". Rotating a "6" by 180° makes a "9". A left–right flip swaps the heart's side on a chest X-ray. Rotating a photo of a "turn left" road sign turns it into a different sign. Always ask: would a human still give this the same label?
- Augmenting the test set. Validation and test images should get only the deterministic resize and crop. Otherwise your measurements are noisy and not comparable between runs.
- Forgetting the boxes and masks. For Object Detection and Image Segmentation, a flip or crop must move the bounding boxes and masks too. Use libraries that handle them together (torchvision v2 with
tv_tensors, or Albumentations). - Too much augmentation for a small model. Heavy mixup, CutMix and RandAugment help big models trained for a long time. A small model trained briefly can underfit with them. Start mild and increase while validation accuracy improves.
- Augmentation that fights the real data. If production images are always well lit and centred, extreme colour jitter and crops waste model capacity. Augment towards the variety you actually expect.
- The data loader becomes the bottleneck. Image decoding and augmentation run on the CPU. If the GPU sits idle, add
num_workersto theDataLoaderor move augmentation to the GPU.
Watch out Augmentation must not leak into evaluation. If augmented copies of one image end up in both the training and test sets (for example, because you saved augmented files to disk before splitting), your test score measures memorisation, not generalisation. Split first, and augment on the fly.
Where it leads
- Dropout and regularisation covers the other main tools against overfitting. Augmentation is regularisation through the data.
- Self-Supervised Learning turns augmentation into the learning signal itself. Methods such as SimCLR and DINO train a network to give two augmented views of the same image similar embeddings.
- CLIP and Contrastive Learning is trained contrastively on image–text pairs, and the same "two views" idea underlies it.
- Synthetic Data goes further, generating new training examples with simulators or generative models.
- Speech Recognition systems rely heavily on SpecAugment and on noise and reverberation augmentation.
A bit of history
Augmentation is older than deep learning. In the 1990s, LeCun's group distorted handwritten digits to train LeNet, and Patrice Simard and colleagues showed in 2003 that elastic distortions of MNIST digits cut error rates substantially. AlexNet (2012) made random crops, flips and colour perturbation standard, and reported that without them the network overfitted badly. The paper noted that cropping and flipping alone enlarged the training set by a factor of 2,048.
The late 2010s brought a wave of new methods: Cutout and Random Erasing (2017), mixup (2017), AutoAugment (2018), CutMix, RandAugment and SpecAugment (2019) and TrivialAugment (2021). DeiT (2021) showed that with mixup, CutMix, RandAugment and random erasing, a vision Transformer could be trained well on ImageNet alone. Augmentation views also became the engine of self-supervised learning, from SimCLR (2020) to DINO (2021).
Try it
- In the digits experiment, add horizontal flips (
xb.flip(-1)for a random half of the batch). Does accuracy go up or down? Why?- Change
max_degto 45 andmax_shiftto 0.4. At what point does augmentation start to hurt?- Harder: train the digits model with
mixup(use soft-target cross-entropy) instead ofrandom_affine, and compare the average over 5 seeds.Hint for 1: a mirrored 2, 3, 4, 5, 7 or 9 is not a valid digit, and the test set never contains one, so flips change the meaning rather than preserve it.
Learn more
Hand-picked courses, books, videos and tutorials for going deeper. See all resources →
torchvision: Transforming and augmenting images
Official guide to torchvision's transforms (including the v2 API) for resizing, cropping, converting, normalising and augmenting images, boxes and masks.
RandAugment: Practical automated data augmentation with a reduced search space
Replaces expensive augmentation-policy search with two knobs, the number of random operations and their strength, and matches or beats searched policies.
mixup: Beyond Empirical Risk Minimization
Trains on weighted blends of pairs of images and their labels. A two-line change that improves accuracy and calibration.
CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features
Pastes a rectangle from one training image into another and mixes the labels in proportion to the area.
SpecAugment: A Simple Data Augmentation Method for Automatic Speech Recognition
Augments speech by masking random blocks of time and frequency in the spectrogram (plus time warping). Simple, and a big gain for speech recognisers.
Albumentations documentation
A fast, popular image augmentation library whose transforms also update bounding boxes, masks and keypoints, which suits detection and segmentation.
Stanford CS231n: Deep Learning for Computer Vision
Famous course notes on neural nets, backprop, CNNs and training, written very clearly.
Facts checked as of 30 November 2026. Fast-moving details (products, prices, laws) change often. · Source: content/entries/vision/data-augmentation.md