Simple Algorithm
Deep Learning · Representation · 22 min

Data Augmentation

Teaching invariances by transforming data: crops, flips, color, mixup and more.

Show a network the same photo shifted, cropped, mirrored and recolored, all with the same label, and it is trained to give the same answer to every version. Data augmentation turns knowledge about what does not change the label into a stream of new training examples, and in image classification it is often the most effective regularizer of all. Here you build the standard pipelines, see how text and speech do the same thing, and find the cases where augmentation quietly does harm.

What you’ll learn

  • Write the augmented training objective and explain its two effects: more effective data and a prior toward invariance.
  • Build a standard image pipeline (random resized crops, flips, color jitter, erasing) and explain automated policies (AutoAugment, RandAugment) and mixing methods (mixup, CutMix).
  • Describe augmentation for text (back-translation) and speech (SpecAugment), test-time augmentation, and augmentation's role as the engine of self-supervised learning.
  • Recognize label-changing transformations and class-dependent harms, and check for them.

Label-preserving transformations

A transformation TT of inputs is label-preserving if T(x)T(\mathbf x) has the same true label as x\mathbf x. Given a family T\mathcal T of such transformations with a sampling distribution, augmented training minimizes the expected loss over transformed copies, drawing a fresh TT every time an example is used:

Laug(θ)=1n∑i=1nET∼T[ℓ(fθ(T(xi)), yi)]\loss_{\text{aug}}(\boldsymbol\theta)=\frac1n\sum_{i=1}^n\E_{T\sim\mathcal T}\Big[\ell\big(f_{\boldsymbol\theta}(T(\mathbf x_i)),\,y_i\big)\Big]
Each pass over the data sees new views, so the network effectively trains on many more examples, though highly correlated ones. And the objective rewards predictions that do not change under TT: a push toward invariance, which is how prior knowledge enters without changing the architecture.
Predict before you look

A 32×3232\times32 training image is augmented by taking 28×2828\times28 crops at every possible integer offset, each optionally flipped horizontally. How many distinct views does one image give?

Show the answer

50 views

A 2828-pixel window fits at 32−28+1=532-28+1=5 offsets along each axis, so 5×5=255\times5=25 crops, times 2 for the flip: 50. AlexNet's factor of 2048 is 32×32×232\times32\times2 for its 224224-pixel crops of 256256-pixel images: it counts 256−224=32256-224=32 offsets per axis, one fewer than the 33 this rule gives.

A catalog for images

MethodWhat it doesNotes
Random (resized) crop, horizontal flipTakes a random window, possibly of random scale and aspect ratio, resized to the input size; mirrors left–rightThe workhorses since AlexNet; crops teach invariance to position and framing
Color jitterRandomly perturbs brightness, contrast, saturation and hue, or the principal color componentsInvariance to lighting and camera
Cutout, random erasingMasks a random square (DeVries & Taylor, 2017) or rectangle (Zhong et al., 2020)Forces the network to use more than one region of the object
AutoAugmentSearches over policies of image operations with reinforcement learning, using a child model's validation accuracy as the reward (Cubuk et al., 2019)Each policy has 5 sub-policies of 2 operations with probabilities and magnitudes; the search is expensive, but learned policies transferred across datasets
RandAugmentApplies NN operations drawn uniformly from a fixed list, all at one global magnitude MM (Cubuk et al., 2020)Two interpretable hyperparameters, tuned by a small grid search; the search space shrinks from about 103210^{32} to about 10210^2 candidates
Mixup, CutMixBlend two images, by averaging pixels (Zhang et al., 2018) or pasting a patch (Yun et al., 2019), and blend their labels in proportionNot label-preserving: they create new labels; see Mixup, CutMix & Vicinal Risk
python
import torchvision.transforms as T

norm = T.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_tf = T.Compose([
    T.RandomResizedCrop(224),               # random scale and aspect ratio, resized to 224
    T.RandomHorizontalFlip(),               # p = 0.5
    T.RandAugment(num_ops=2, magnitude=9),  # N = 2 random operations at magnitude M = 9
    T.ToTensor(),
    norm,
    T.RandomErasing(p=0.25),                # erase a random rectangle (acts on tensors)
])
test_tf = T.Compose([T.Resize(256), T.CenterCrop(224), T.ToTensor(), norm])

A typical ImageNet-style pipeline. The randomness lives only in the training transform; the test transform is deterministic. Strengths such as NN, MM and the erasing probability are hyperparameters, tuned on validation data like any regularizer.

Check your understanding

Why did RandAugment largely replace AutoAugment in practice?

  1. It uses a larger and more expressive search space
  2. It only uses operations that are guaranteed to preserve the label
  3. It learns the augmentation jointly with the network weights by gradient descent
  4. It drops the expensive policy search: two hyperparameters, the number of operations and one shared magnitude, tuned by a small grid search, matched or beat searched policies
Show the answer

D. It drops the expensive policy search: two hyperparameters, the number of operations and one shared magnitude, tuned by a small grid search, matched or beat searched policies

AutoAugment needed a reinforcement-learning search with many child-model trainings. RandAugment's two interpretable knobs can be tuned on the target task and model directly, which also lets the augmentation strength be tailored to the model and dataset size.

Beyond images

Text is harder: tokens are discrete, and a one-word edit ("not") can flip the meaning. The most effective trick in machine translation generates whole new sentences. Back-translation (Sennrich, Haddow & Birch, 2016) translates monolingual text in the target language into the source language with a reverse model, then trains on the synthetic source paired with the real target. On WMT 2015 English↔German it gained 2.8 to 3.7 BLEU. The synthetic side is the input, so the model never learns to produce machine-made text.

Speech: SpecAugment (Park et al., 2019) works directly on the log-mel spectrogram the network reads: it warps the time axis, masks blocks of consecutive frequency channels, and masks blocks of consecutive time steps. It needs no extra data, runs online during training, and gave state-of-the-art results on LibriSpeech and Switchboard at the time.

Self-supervised learning turns augmentation into the task itself: two random views of the same image should get nearby representations, and views of different images distant ones. In SimCLR (Chen, Kornblith, Norouzi & Hinton, 2020) the composition of augmentations was decisive: neither random cropping nor color distortion did well alone, but together they did, because without color distortion two crops of one image can be matched by their color histograms alone. See Self-Supervised Learning.

Check your understanding

In back-translation for an English→German translation model, which part of each synthetic training pair is machine-generated?

  1. The German target sentence, produced by an English→German model
  2. The English source sentence, produced by a German→English model from real German text
  3. Both sides, generated by a language model
  4. Neither: back-translation reorders words within real pairs
Show the answer

B. The English source sentence, produced by a German→English model from real German text

Real German text is translated back into English, and the model learns to map that synthetic English to the real German. Its outputs are trained toward human-written text, while its inputs see some noise, which also makes it more robust.

Test-time augmentation

Augmentation can also be used at prediction time: run the network on several transformed copies of the input and average. AlexNet did it with ten patches, the four corners and the center plus their mirror images. On the ILSVRC-2010 test set the averaging lowered the top-1 error from 39.0% to 37.5% and the top-5 error from 18.3% to 17.0% (Krizhevsky et al., 2012). In general, with fixed transformations T1,…,TKT_1,\dots,T_K:

fˉ(x)=1K∑k=1Kf(Tk(x)),and if {Tk} is a finite group G:fˉ(gx)=1∣G∣∑h∈Gf(hgx)=fˉ(x)\bar f(\mathbf x)=\frac1K\sum_{k=1}^Kf\big(T_k(\mathbf x)\big),\qquad\text{and if }\{T_k\}\text{ is a finite group }G:\quad\bar f(g\mathbf x)=\frac1{|G|}\sum_{h\in G}f(hg\mathbf x)=\bar f(\mathbf x)
Over a group, the average is exactly invariant, because h↦hgh\mapsto hg only reorders the terms. That is the orbit averaging that A Theory of Data Augmentation builds on. The price is KK forward passes per prediction.
Think first A network was trained with random horizontal flips. Why can averaging its predictions on x\mathbf x and on the mirrored x\mathbf x still help?

Training only encourages invariance, so f(x)f(\mathbf x) and f(mirror(x))f(\text{mirror}(\mathbf x)) still differ, and their errors partly cancel when averaged, as in any ensemble. There is even a guarantee: if mirrored images are as likely as the originals and the loss is convex in the prediction (cross-entropy is), Jensen's inequality gives E[ℓ(fˉ)]≤12(E[ℓ(f(x))]+E[ℓ(f(mirror(x)))])=E[ℓ(f(x))]\E[\ell(\bar f)]\le\frac12\big(\E[\ell(f(\mathbf x))]+\E[\ell(f(\text{mirror}(\mathbf x)))]\big)=\E[\ell(f(\mathbf x))]: the averaged predictor's expected loss is never higher.

When augmentation hurts

Every augmentation encodes a claim: "this change does not affect the label". When the claim is false, augmentation trains on wrong labels. Rotations turn a 6 into a 9; mirroring turns text into nonsense and some letters into others; an aggressive crop can cut away the object the label refers to; color jitter erases evidence when color matters for the class. The safe set is a property of the task, not of the image format.

Harm can also hide inside averages. Balestriero, Bottou and LeCun (2022) showed that the amount of augmentation chosen by cross-validation for the best average accuracy can be very bad for particular classes. For a ResNet-50 on ImageNet, test accuracy on the "barn spider" class fell from 68% to 46% when random-crop augmentation was introduced, while the average improved. After pretraining with random-crop augmentation, one class of the iNaturalist dataset fell from 70% to 30% accuracy when the model was transferred. And the same class-dependent effect appeared with weight decay, a regularizer that encodes no knowledge of images at all.

The practical lessons: treat augmentation strength as a hyperparameter tuned on clean validation data, and look at per-class (or per-group) metrics, not only the average.

Key takeaways

  • Augmentation minimizes 1n∑iET[ℓ(f(T(xi)),yi)]\frac1n\sum_i\E_T[\ell(f(T(\mathbf x_i)),y_i)] over label-preserving transformations: it adds (correlated) data and pushes the network toward invariance.
  • Image recipes combine crops, flips, color jitter and erasing with automated policies (AutoAugment's searched policies, RandAugment's two knobs) and mixing methods (mixup, CutMix) that blend labels too.
  • Text uses back-translation (synthetic source, real target), speech uses SpecAugment's warping and masking, and self-supervised learning uses augmentation to define its training task.
  • Test-time augmentation averages predictions over transformed copies; over a group it is exactly invariant, at KK times the cost.
  • Augmentation that changes labels, or helps the average while hurting some classes (Balestriero, Bottou & LeCun, 2022), does harm: tune its strength on clean validation data and check per-class metrics.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A training loop draws a fresh random crop and flip every time it loads an image. Which objective is it minimizing, in expectation?

  1. The ordinary training loss on the original images
  2. The loss on the single hardest transformation of each example
  3. The average over examples of the expected loss over random transformations of each example
  4. The loss on transformed images whose labels have been randomized
Show the answer

C. The average over examples of the expected loss over random transformations of each example

Each sampled transformation gives an unbiased stochastic estimate of 1n∑iET[ℓ(f(T(xi)),yi)]\frac1n\sum_i\E_T[\ell(f(T(\mathbf x_i)),y_i)], so SGD with on-the-fly augmentation minimizes the augmented objective.

Question 2

For handwritten digit recognition, which augmentation risks training on wrong labels?

  1. Random translations by a few pixels
  2. Small changes of contrast
  3. Slight elastic deformations of the strokes
  4. Random rotations covering the full circle
Show the answer

D. Random rotations covering the full circle

A 6 rotated by half a turn looks like a 9, so full-circle rotations produce examples whose true label differs from the one attached. Small rotations are fine; the safe range is a property of the task.

Question 3

At test time you average a classifier's predicted probabilities on an image and on its mirror image. What do you get?

  1. A predictor that is exactly invariant to mirroring, at twice the inference cost
  2. The same predictions as before, since the network was trained with flips
  3. A predictor that is invariant to every transformation used in training
  4. Lower training error, but test error cannot change
Show the answer

A. A predictor that is exactly invariant to mirroring, at twice the inference cost

The identity and the mirror form a group of two elements, and averaging over a group gives an exactly invariant function. Training with flips only makes the network approximately invariant, so the averaged predictor differs from the original and, for convex losses on mirror-symmetric data, is no worse in expectation.

Question 4

You tune augmentation strength for the best average validation accuracy over 1,000 classes. What did Balestriero, Bottou and LeCun (2022) show can happen?

  1. Nothing problematic: the best average setting is also best for every class
  2. Some individual classes can lose a large amount of accuracy even as the average improves
  3. The tuned augmentation always overfits the validation set
  4. Augmentation helps rare classes and hurts frequent ones, by design
Show the answer

B. Some individual classes can lose a large amount of accuracy even as the average improves

Regularization trades accuracy between classes. On ImageNet with a ResNet-50, adding random-crop augmentation took the "barn spider" class from 68% to 46%. Per-class metrics reveal what the average hides.

Question 5

In SimCLR, two random crops of the same image must get similar representations. Why was color distortion needed as well?

  1. Without it, crops of one image can be matched by their color histograms alone, so the network need not learn about shapes
  2. Color distortion makes training faster on GPUs
  3. Color is irrelevant to every downstream task, so it must be removed
  4. Crops alone would make all representations collapse to a single point
Show the answer

A. Without it, crops of one image can be matched by their color histograms alone, so the network need not learn about shapes

Two crops of the same photo share its color statistics, a shortcut that solves the matching task without semantic features. Distorting colors removes the shortcut; neither transformation alone gave good representations, their composition did.

Go deeper

Further reading

  • A. Krizhevsky, I. Sutskever & G. E. Hinton, "ImageNet classification with deep convolutional neural networks," NeurIPS (2012).
  • E. D. Cubuk, B. Zoph, J. Shlens & Q. V. Le, "RandAugment: practical automated data augmentation with a reduced search space," NeurIPS (2020).
  • D. S. Park, W. Chan, Y. Zhang, C.-C. Chiu, B. Zoph, E. D. Cubuk & Q. V. Le, "SpecAugment: a simple data augmentation method for automatic speech recognition," Interspeech (2019).
  • R. Balestriero, L. Bottou & Y. LeCun, "The effects of regularization and data augmentation are class dependent," NeurIPS (2022).