Data augmentation: grow your data by changing it
Train a model on 100 cat photos and it is easier for it to memorize those 100 photos than to learn what a cat is. Show the same photos flipped, shifted and brightened, and memorizing stops working. Press the buttons below on a small grid picture and find out which changes break the answer.
Short answer. Data augmentation changes your training examples only as much as the answer allows, so each example becomes many practice questions. The same picture looks a little different every time the model sees it, so the model cannot memorize single pictures and has to learn features that survive a shift or a change of light. That cuts overfitting. Use it on training data only, and leave validation and test data as they are.
The three pictures are made-up 16 by 16 grids. Each cell holds a value from 0 (blank) to 1 (darkest). Every button applies one change to the original picture. In real training the shift, the angle and the cut-out spot are picked at random each time. Here they are fixed so you can compare (2 cells right and 1 down, 15°, a 5 by 5 square).
Try this. ① Flip the house: the window and the door swap sides, 16 cells change, and the answer is still house. ② Flip the right arrow: only 28 cells change, but the answer becomes left arrow. Shift and crop the house: 84 cells change and the answer stays the same. What matters is not how many cells change but whether a person would still give the same answer. ③ Turn the 6 by 180°: 54 cells change and it looks like a 9. Flip it left-right and it becomes mirror writing, not any digit. ④ "Brighter" changes only the cells with ink (76 for the house). The shape stays, so no picture changes its answer.
Definitions
The text below uses small grid pictures. These are the textbook definitions. Each training example is a pair of an input x and an answer (label) y.
- data augmentation
- A method that changes the training examples you have and uses the results as new training examples. You pick changes that keep the answer the same, and if you mix examples, as mixup does, you mix the answers in the same ratio. The changed examples are made at random during training and used only for training data.
- invariance
- The property that the answer does not change when a certain change is applied to the input. The same change can keep the answer in one task and change it in another. Data augmentation uses only changes under which the answer is invariant for that task.
- cutout
- A change that erases one square area at a random place in a picture. The answer stays the same.
- one-hot vector, soft label
- A one-hot vector is an answer vector with 1 in the correct slot and 0 in every other slot. A soft label is an answer vector that spreads shares of 0 or more over several slots, with the slots adding up to 1. The y′ of mixup is a soft label.
- mixup
- An augmentation that mixes two training examples (x₁, y₁) and (x₂, y₂) with the same ratio λ to make a new training example (x′, y′). Each y is a one-hot vector, and λ is drawn again from a Beta distribution every time during training. α is a hyperparameter you choose.
- test-time augmentation (TTA)
- A method that, when you use the model, changes one input in a few ways, predicts each one, and averages the predictions. It does not add training data. It is a way of predicting.
1. What data augmentation is, and why it cuts overfitting
Data augmentation takes one training example, changes it a little while keeping the same answer, and uses the result as a new training example. A cat photo flipped left to right is still a cat. A slightly brighter cat is still a cat. One photo turns into many practice questions.
Overfitting is when a model memorizes accidents of its training data (the cat was on the left in this photo, that photo was dark) and then fails on new data. With augmentation the same photo shows up in a different spot and a different light every time. Memorizing single cells no longer works, so the model has to look at what does not change with the spot or the light: the shape. You are feeding the model a piece of human knowledge, "a change this small does not change the answer", in the form of data.
Augmentation does not create new information. It only changes photos you already have, so it cannot produce an angle or a breed that was never photographed. It helps when you collect more real data. It does not replace it.
2. The basic picture changes
| Change | What it does | When it breaks the answer |
|---|---|---|
| Flip left-right | Swaps left and right, as in a mirror | Letters, digits, directions (arrows, left and right) |
| Shift and crop | Moves the picture a little or cuts out a part, then resizes back | Crop too much and the object leaves the frame |
| Rotate | Turns by a small angle | Turn too far and a 6 becomes a 9. The corners go empty |
| Brightness and color | Nudges brightness, contrast, saturation and hue | Tasks where the color is the answer (ripe fruit, traffic lights) |
| Cut out | Blanks out one square | It can hide the one small part that decides the answer |
In practice you chain these changes and draw the strength of each one at random every time. Training goes over the same data many times, and in each pass the same photo looks different. With torchvision in PyTorch it looks like this.
from torchvision.transforms import v2
train_transform = v2.Compose([
v2.RandomResizedCrop(224), # crop at random, resize to 224 x 224
v2.RandomHorizontalFlip(), # flip left-right half of the time
v2.RandomRotation(15), # rotate by an angle between -15 and 15 degrees
v2.ColorJitter(brightness=0.3), # nudge the brightness
])
eval_transform = v2.Compose([v2.Resize(256), v2.CenterCrop(224)]) # validation and test: no randomness, always the same
3. Never use a change that changes the answer
There is one question for picking a change: if you showed the changed picture to a person, would they give the same answer? If not, that change teaches a wrong answer.
- A 6 turned upside down (180°) looks like a 9. Keep the label 6 and the model learns that things shaped like 9 are 6. The "Turn 180°" button shows a warning.
- If the answer is a direction, flipping changes it. A right arrow flipped left to right is a left arrow.
- A picture that keeps its answer but never occurs in real life is of little use. Upside-down houses and mirror writing never come in. The model spends effort on practice it will never need.
- If the answer is a place in the picture, change the answer too. When the task is to find a box around an object and you flip the picture left to right, flip the box's horizontal position as well.
4. How the formula is built: mixup blends two pictures
The changes above alter one picture. mixup blends two pictures into a new one and blends their answers in the same ratio. Press "Next" to go one step at a time. λ (lambda) is the mixing ratio, between 0 and 1.
- Two examples and their answers:
(x₁, y₁), (x₂, y₂). An answer is three slots (house, right arrow, 6) with a 1 only in the right slot. The house isy₁ = (1, 0, 0)and the 6 isy₂ = (0, 0, 1). - Blend the pictures:
x′ = λ·x₁ + (1 − λ)·x₂. For every cell, multiply the value in x₁ by λ and the value in x₂ by 1 − λ, then add. Why: the two weights add up to 1, so the result stays between 0 and 1, and λ = 1 gives back x₁ while λ = 0 gives back x₂. - Blend the answers the same way:
y′ = λ·y₁ + (1 − λ)·y₂. Why: if the picture is 30% the 6 but the answer still says "house" only, you teach something false. Blending the answer in the same ratio keeps the picture and the answer in agreement. - Done, with a new λ each time:
λ ~ Beta(α, α). During training λ keeps being drawn again from a Beta distribution. You set α yourself, and torchvision's MixUp uses 1 by default. The loss is cross-entropy, which takes the blended answer y′ as it is.
Try this. ① Start at λ = 0.7 and press "Next" twice: cell A is 0.7 × 1 + 0.3 × 0 = 0.7, cell B is 0.3 and cell C is 1. ② Press once more and you get y′ = (0.7, 0, 0.3). ③ Set λ to 0.5 and y′ = (0.5, 0, 0.5). Only the 31 cells with ink in both pictures stay at a full 1, and every other inked cell fades to 0.5. ④ Set λ to 1 and x′ is exactly the house, with y′ = (1, 0, 0): the original example, not mixed at all.
Two other ways to mix. Cutout blanks out one square in a single picture (the "Cut out" button in the first lab). The answer stays the same. CutMix cuts a square from one picture and pastes it at the same spot in another, then blends the answers in proportion to the pasted area. Paste an 8 by 8 piece of the 6 onto the 16 by 16 house and the piece covers 64 ÷ 256 = 1/4 of it, so the answer is house 0.75 and 6 0.25, that is (0.75, 0, 0.25).
5. Work it by hand: λ = 0.7
These are the same numbers as the lab's starting values. Follow three cells of the house (x₁) and the 6 (x₂).
| Cell | x₁ (house) | x₂ (6) | 0.7 × x₁ + 0.3 × x₂ |
|---|---|---|---|
| A (ink only in the house) | 1 | 0 | 0.7 + 0 = 0.7 |
| B (ink only in the 6) | 0 | 1 | 0 + 0.3 = 0.3 |
| C (ink in both) | 1 | 1 | 0.7 + 0.3 = 1 |
| Answer y | (1, 0, 0) | (0, 0, 1) | (0.7, 0, 0.3) |
The slots of the blended answer add up to 0.7 + 0 + 0.3 = 1. That holds for any λ, so you can still read it as "how much of each answer".
6. Training data only, never validation or test
- Leave validation and test data as they are. The test score measures how well the model does on the inputs it will really get. Flip or blend the test pictures and the measuring stick no longer matches reality.
- Split first, then augment the training side only. If you make augmented copies first and then split into training and test, changed copies of the same photo end up on both sides. The test score looks better than it really is (data leakage).
- Test-time augmentation (TTA) changes one input into a few versions at use time (for example the original and a left-right flip), predicts on each and averages the predictions. Prediction costs that many times more. It does not change the test data. It is a way of predicting, so if you use it, measure the test score the same way.
7. Key properties
| Property | In plain words |
|---|---|
| The answer stays | A changed picture keeps its original answer. mixup and CutMix blend the answer in the same ratio as the pictures |
| Drawn fresh every time | Nothing is saved. Changes are made at random during training, so the same photo looks different in each pass |
| Training only | Validation and test data stay looking like real inputs |
| No new information | It only changes what you have. It cannot make kinds of data you never had |
| Depends on the task | The same change is safe for one task and breaks the answer in another (the house and the arrow in the lab) |
8. Augmenting text and sound
- Text: swap words for words with a similar meaning, drop a few words, or translate into another language and back (back-translation). One word can flip the meaning ("good" to "not good"), so take more care than with pictures.
- Sound: mix in noise, change the speed or pitch a little, or turn the sound into a picture (a spectrogram) and blank out a band of time or frequency.
9. Which one to use when
| Option | Good | Bad | Use it for |
|---|---|---|---|
| Flip left-right | Easy, and almost always safe for photos of things | Changes the answer for letters, digits and directions | Photos of objects, animals, scenery |
| Shift and crop | The model copes with objects in a different spot or size | Crop too much and the object is gone | The default for picture classification |
| Small rotation | Copes with photos taken at a slant | Empty corners, and large angles change the answer | Handwriting, document photos, anything shot at an angle |
| Brightness and color | Copes with different light and cameras | Useless when color is the answer | Outdoor photos, data from several cameras |
| Cut out | Stops the model leaning on one part | Can hide the small key part | Photos where part of the object is often hidden |
| mixup | Learns smooth behavior between examples. The paper reports less memorizing of wrong labels | Blended pictures never occur in real life. The answers are blended, so the loss must accept that | Classification, on top of other augmentation |
| CutMix | Pastes a real piece of another picture instead of blanking, so less information is thrown away | Even if the pasted piece is only background, the answer is still blended by area | Picture classification |
| No augmentation | Fast and simple | Small datasets overfit easily | Validation and test data. Training data that is already large and varied |
Where it is used
- Picture classification. Training a convolutional network to tell objects or animals apart usually starts with shift-and-crop and left-right flips.
- Small datasets. When more photos are hard to get, it lets you use the ones you have many times.
- Changing conditions. If the light, the camera or the angle at use time may differ from training, add changes that imitate those differences.
- Text and sound. Back-translation for sentence classification, noise and band masking for speech recognition.
Frequently asked questions
Should I save the augmented pictures to make my dataset several times bigger?
Usually not. Augmented pictures are made on the fly, at random, while the model trains. Saved copies repeat the same few versions, but on-the-fly changes give a different version in every pass over the data. It also needs no extra disk space.
Can I augment the validation and test data too?
No. Validation and test scores measure how well the model does on real inputs, so keep them looking like real inputs. If you average predictions over several changed copies at use time (TTA), measure the test score with that same method.
Is stronger augmentation always better?
No. Change the pictures too much and the answer gets blurry, or the model spends effort on shapes that never show up in real inputs. Pick which changes to use, and how strong, by watching the validation score.
Words
| Plain words used here | Textbook term |
|---|---|
| Growing data by changing it | Data augmentation |
| Memorizing the training data | Overfitting |
| Flip left-right | Horizontal flip |
| Shift and crop | Random crop, translation |
| Rotate | Rotation |
| Brightness and color changes | Color jitter |
| Blanking out a square | Cutout, random erasing |
| Blending two pictures | mixup |
| Cutting and pasting a piece | CutMix |
| The distribution λ is drawn from | Beta distribution |
| An answer with a 1 only in the right slot | One-hot vector |
| A blended answer | Soft label |
| The answer does not change when the input does | Invariance |
| One pass over the training data | Epoch |
| Averaging predictions over changed copies at use time | Test-time augmentation (TTA) |
| Test data leaking into training | Data leakage |
| Methods that hold back overfitting | Regularization |
Sources
- Hongyi Zhang, Moustapha Cisse, Yann N. Dauphin, David Lopez-Paz, mixup: Beyond Empirical Risk Minimization, arXiv:1710.09412. Blending pairs of examples together with their labels, and less memorizing of corrupt labels.
- Terrance DeVries, Graham W. Taylor, Improved Regularization of Convolutional Neural Networks with Cutout, arXiv:1708.04552. Masking out square regions of the input at random during training.
- Sangdoo Yun et al., CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features, arXiv:1905.04899. Cutting and pasting patches, with labels mixed in proportion to the patch area.
- torchvision docs: Transforming images (RandomResizedCrop, RandomHorizontalFlip, RandomRotation, ColorJitter, RandomErasing), MixUp (α of the Beta distribution that λ is drawn from, default 1).
← Grokking: generalizing long after memorizingTransfer learning and fine-tuning →