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 of inputs is label-preserving if has the same true label as . Given a family of such transformations with a sampling distribution, augmented training minimizes the expected loss over transformed copies, drawing a fresh every time an example is used:
A training image is augmented by taking crops at every possible integer offset, each optionally flipped horizontally. How many distinct views does one image give?
Show the answer
50 views
A -pixel window fits at offsets along each axis, so crops, times 2 for the flip: 50. AlexNet's factor of 2048 is for its -pixel crops of -pixel images: it counts offsets per axis, one fewer than the 33 this rule gives.
A catalog for images
| Method | What it does | Notes |
|---|---|---|
| Random (resized) crop, horizontal flip | Takes a random window, possibly of random scale and aspect ratio, resized to the input size; mirrors left–right | The workhorses since AlexNet; crops teach invariance to position and framing |
| Color jitter | Randomly perturbs brightness, contrast, saturation and hue, or the principal color components | Invariance to lighting and camera |
| Cutout, random erasing | Masks a random square (DeVries & Taylor, 2017) or rectangle (Zhong et al., 2020) | Forces the network to use more than one region of the object |
| AutoAugment | Searches 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 |
| RandAugment | Applies operations drawn uniformly from a fixed list, all at one global magnitude (Cubuk et al., 2020) | Two interpretable hyperparameters, tuned by a small grid search; the search space shrinks from about to about candidates |
| Mixup, CutMix | Blend two images, by averaging pixels (Zhang et al., 2018) or pasting a patch (Yun et al., 2019), and blend their labels in proportion | Not label-preserving: they create new labels; see Mixup, CutMix & Vicinal Risk |
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 , and the erasing probability are hyperparameters, tuned on validation data like any regularizer.
Why did RandAugment largely replace AutoAugment in practice?
- It uses a larger and more expressive search space
- It only uses operations that are guaranteed to preserve the label
- It learns the augmentation jointly with the network weights by gradient descent
- 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.
In back-translation for an English→German translation model, which part of each synthetic training pair is machine-generated?
- The German target sentence, produced by an English→German model
- The English source sentence, produced by a German→English model from real German text
- Both sides, generated by a language model
- 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 :
Think first A network was trained with random horizontal flips. Why can averaging its predictions on and on the mirrored still help?
Training only encourages invariance, so and 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 : 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 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 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.
A training loop draws a fresh random crop and flip every time it loads an image. Which objective is it minimizing, in expectation?
- The ordinary training loss on the original images
- The loss on the single hardest transformation of each example
- The average over examples of the expected loss over random transformations of each example
- 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 , so SGD with on-the-fly augmentation minimizes the augmented objective.
For handwritten digit recognition, which augmentation risks training on wrong labels?
- Random translations by a few pixels
- Small changes of contrast
- Slight elastic deformations of the strokes
- 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.
At test time you average a classifier's predicted probabilities on an image and on its mirror image. What do you get?
- A predictor that is exactly invariant to mirroring, at twice the inference cost
- The same predictions as before, since the network was trained with flips
- A predictor that is invariant to every transformation used in training
- 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.
You tune augmentation strength for the best average validation accuracy over 1,000 classes. What did Balestriero, Bottou and LeCun (2022) show can happen?
- Nothing problematic: the best average setting is also best for every class
- Some individual classes can lose a large amount of accuracy even as the average improves
- The tuned augmentation always overfits the validation set
- 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.
In SimCLR, two random crops of the same image must get similar representations. Why was color distortion needed as well?
- Without it, crops of one image can be matched by their color histograms alone, so the network need not learn about shapes
- Color distortion makes training faster on GPUs
- Color is irrelevant to every downstream task, so it must be removed
- 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
- Mixup, CutMix & Vicinal Risk · Training on blends of examples, and what it does to boundaries and calibration.
- A Theory of Data Augmentation · Orbit averaging, variance reduction and when augmentation provably helps.
- Synthetic Data & Model Collapse · Training on generated data, and what happens when models learn from their own output.
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).