A photo of a cat, moved two pixels to the left, is still a photo of a cat. You know that. A network trained on the first photo does not: to its first layer, the shifted photo is a different list of numbers (P4.5). You could collect more photos, but photos need labels, and labels cost money.
Data augmentation is the cheap alternative. Take each training example, change it in a way that should not change its label, and train on the changed copy. The cat moves, brightens or flips, and the label stays “cat”. The data set has not grown on disk, but the network now sees many versions of each example.
The idea, and the bet it makes
Two things are true at the same time:
- It gives the model more to learn from. A network with thousands of weights can memorize a small training set (P3.A5, P4.17). If every pass shows each image a little differently, memorizing one fixed pixel pattern is harder, and the useful signal (the shape of the digit) is what stays the same.
- It is a statement about the world. Choosing to shift images says “the label does not depend on where the object is”. Choosing not to flip digits says “left and right matter here”. The model is not told this in words. It is told by examples. So augmentation puts your knowledge into the training data, the way a penalty in the loss puts it into the objective (P3.A6, P4.17).
That makes it a bet. If new data really varies in the way you augmented, you win. If you augment in a way the data never varies, you spend the model’s capacity on cases that never come up, and the model can get worse. The experiment at the end of this lesson shows both outcomes on real digits.
The augmentation preview
The widget below uses the 8 by 8 digit images of P4.10 (one example per digit, chosen as the image closest to the average of its digit) and one made-up colour picture so colour changes are visible. In Part 1, change one thing at a time. In Part 2, draw random combinations the way a training loop does.
Things to try:
- Digit 6, rotate to 180. The picture turns into something that looks like a 9, and the warning says the label would now be wrong. Rotate by 10 or 15 degrees instead: still a 6.
- Digit 6, flip. It is a mirror image that no writer produces. Flip digit 0, 1 or 8 and the warning goes away, because the widget treats those as roughly symmetric (a rule of thumb; mirrored 4s are still close to real 4s).
- Shift right by 3. Part of the digit leaves the frame, and the warning counts how much. A shift of one pixel on an 8 by 8 image is already a big move, one eighth of the width.
- Mixup. Keep digit 6, mix in digit 9, and set lambda to 0.3. The picture is a ghostly blend and the label bars read 0.70 for the 6 and 0.30 for the 9.
- Part 2. Turn every change off except Cutout and press Random augment a few times. Then turn on Flip and watch the red marks appear.
Which changes keep the label?
The rule is one question: would a careful person still give this image the same label? If yes, the change is label-preserving, and it is a candidate. If not, it is label-changing, and it is a bug in the training data: the model is told a wrong answer, with full confidence.
Run the cell below. Its first part prints one handwritten 6 and the same picture turned by 180 degrees. Then it uses a crude reader, which names the class whose average image is closest, to count what happens to all the 6s. A trained network would be a better reader; this one is simple enough to write in five lines.
First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.
a 6, then turned 180 degrees #: :@ #. @. .@*##. .@#.*# ##.## #@# -------- #@# ##.## #*.#@. .##*@. .@ .# @: :# 6s read as 6: 0.967 turned, read as 9: 0.818 turned, read as 6: 0.0 mirrored 2s read as 2: 0.017 mirrored 5s read as 5: 0.0
Read the output:
- The picture of the turned 6 looks like a 9. The crude reader agrees: 81.8 per cent of the turned 6s are closest to the 9 average, and none is closest to the 6 average. Training with this change and the label “6” would teach the network a wrong rule.
- Mirrored 2s and mirrored 5s are almost never closest to their own class: 1.7 per cent and 0 per cent. The reader is crude, so the numbers are not exact; they say that a mirrored digit is far from where real 2s and 5s live. The mirror does not reliably turn a 2 into another digit. It mostly makes something that is not a normal digit, so it spends training effort on pictures that never appear in the test data (a milder problem than a wrong label, which is what turning a 6 gives).
So the answer depends on the data, not on the transformation:
- Digits and letters: mirror flips are unsafe (b and d are mirror images of each other), and so are large rotations (6 and 9).
- Photos of animals and everyday objects: left-right flips are usually safe. Up-down flips usually are not (the sky is on top).
- Medical images, satellite images, text in images: it depends on the task. Where left versus right carries meaning, flips are unsafe. Ask someone who knows the field, and look at the outputs.
- Magnitude matters as much as kind. A 5 degree rotation is safe for a 6. Rotating by 180 degrees is not.
The usual image changes
Geometric changes move the pixels.
- Horizontal flip: the pixel in column goes to column . Cheap and popular for natural images.
- Random crop with padding: pad the image with zeros (or a copy of the edge), then cut a random window of the original size. For a image padded by 4 on each side, the padded image is and the window can start in places in each direction, so there are possible crops. A common recipe for small photos is a random crop plus a flip (P5.7). For our 8 by 8 digits, padding by 1 gives crops, which is the same as shifting by , or pixel in each direction. The experiment below uses exactly this.
- Small rotation and shift: a rotation by about the centre looks up, for every output pixel, the input pixel that lands there. The result rarely falls exactly on a pixel, so a rule is needed: take the nearest pixel (what the widget does) or blend neighbours (bilinear interpolation, which looks smoother and is common for photos). Pixels that come from outside the picture are filled with black here, or with a copy of the edge.
- Scaling: zoom in (crop, then resize) or out (shrink, then pad).
Photometric changes change the values and leave the positions alone. In the widget they are applied to values between 0 and 1, then clipped back into that range:
- Brightness adds a number: .
- Contrast stretches values away from the middle: . With everything moves toward grey.
- Saturation (colour pictures) moves each colour toward its grey value , the weighted sum of its red, green and blue: . At the picture is grey.
- Colour jitter is the name for changing brightness, contrast, saturation (and often hue) by small random amounts together.
- Noise: add a random number to each pixel, here from a normal distribution scaled by the noise size. Blur averages neighbouring pixels. Both teach the model not to depend on fine detail.
Clipping matters. After a pixel can leave the range ; most image code clips it back, and the widget does too.
Erasing. Cutout hides a random square of each training image (DeVries and Taylor, 2017). The model cannot rely on one small region and has to use other evidence as well. The widget’s cutout fills the square with 0, which is black. When the square covers the stroke that tells two classes apart, the label becomes doubtful, which is why the widget reports the share of the picture erased.
Mixup and CutMix
The changes so far keep one image and one label. Mixup (Zhang, Cisse, Dauphin and Lopez-Paz, ICLR 2018) takes two training examples and trains on a blend of both. With images , and one-hot labels , (P3.A8), it builds
This is the linear combination of P1.B2, with the same formula as the point on the segment between two vectors: gives the first example and the second. The new label is a soft label: not “6” but “70 per cent 6 and 30 per cent 9”.
The number is drawn at random for each pair (or, as in the paper’s reference code, once per batch, as in the Code tab) from a Beta distribution (P1.D9 draws numbers from distributions; this one lives on the interval from 0 to 1). The setting controls how much blending there is. The next cell blends the 6 of the widget with its 9 at , one pixel by hand, then checks two things: the loss for the mixed label equals the same mix of the two ordinary losses, and how the Beta distribution spreads.
First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.
pixel (4,1): six 0.1875, nine 0.0000 mixed: 0.7*0.1875 + 0.3*0.0000 = 0.13125 label: 6 -> 0.7 , 9 -> 0.3 loss, soft label: 1.1963 0.7*loss(6) + 0.3*loss(9): 1.1963 Beta(1.0): mean 0.501, ends 0.199 Beta(0.4): mean 0.499, ends 0.479 Beta(0.2): mean 0.500, ends 0.674
Read the output:
- The pixel is . Every pixel is blended with the same , and so are the 10 numbers of the label.
- The cross-entropy with the soft label equals times the loss against “6” plus times the loss against “9”. In practice the program computes the two ordinary losses and mixes them, with no special soft-label code (the cross-entropy is linear in the target, P4.6). This holds for any scores: both losses use the network’s one output for the mixed picture, so one forward pass is enough. The scores 2 and 1 here are made up.
- A Beta draw is a plain uniform number: about 20 per cent of draws fall within 0.1 of an end. At it is 48 per cent and at it is 67 per cent: a small gives mostly nearly pure examples with an occasional real blend. Every setting has mean 0.5. (The widget’s Part 2 draws from Beta.)
CutMix (Yun and others, ICCV 2019) mixes by area instead of by pixel value. It cuts a rectangle out of one image and pastes in the same rectangle from another. Every pixel is a real pixel from one image, and the label is mixed by area: if the pasted patch covers a share of the picture, the label is .
What these do, and what is claimed. Mixup trains the network to behave in a simple way between training examples (the paper’s argument). The authors reported better generalization for several architectures and data sets, including ImageNet and CIFAR, and less memorization of wrong labels. In a separate check of the 100-image digit task below (not shown in the cells), mixup with of 0.2, 0.4 and 1 gave test accuracies between 0.870 and 0.883, against 0.885 and 0.888 without it (10 splits, 60 and 150 epochs). The differences are small compared with the spread between splits (about 0.02), so read this as no clear gain, not as mixup hurting. Do not expect it to help everywhere. Mixup and CutMix are applied to training batches only: at test time you give the network a single, unmixed image.
Where augmentation is applied
Training only, after the split. Augment the images the model trains on. The validation and test images must stay as they are, because they measure what the model does on real data (P3.A4). Split first, then augment: if you make augmented copies of every image and then split, copies of one picture land on both sides, and the validation score becomes too good to be true. Fixed preprocessing (resize, scale to 0..1, normalize) is not augmentation and is applied to every split in the same way.
Fresh randomness every time. Two designs:
- On the fly. Each time an image is read for a batch, a new random change is drawn and applied. Nothing is stored, and no two epochs show the same picture. This is what training code normally does.
- A fixed enlarged data set. Make copies of every image once and store them. It is simple but the data set takes times the space, and the network sees only those versions. With 50,000 images and it is images.
The draws are random numbers like any others (P1.G3): the loop draws a flip, a crop offset or a rotation angle for every image every time. That is a Monte Carlo view (P1.D9): the aim is to minimize the average loss over all the changes you might draw, and a single fresh draw per image per step is a one-sample estimate of that average. For a run you can repeat, seed the generator that makes the augmentation too, not only the one that initializes the weights; the widget’s Part 2 shows the idea: same seed and draw number, same eight copies.
Test-time augmentation is a different trick: at prediction time, average the model’s outputs over a few label-preserving copies of one image (for example the image and its mirror image). It can give a small gain at several times the cost per image, and how much it helps depends on the model and the data.
Look at the outputs. Save 20 augmented images with their labels and look at them, as the widget does. Mistakes show at once: an unrealistic crop, a label-changing flip, a picture clipped to white. For boxes (P5.11) or masks (P5.13), the labels must move together with the pixels.
Beyond this lesson. Text, audio and tables have their own label-preserving changes, each with the same question of whether the label survives; for images, AutoAugment (Cubuk and others, 2018 preprint, CVPR 2019) searches for a policy of changes and RandAugment (Cubuk and others, 2019) shrinks the search to a few settings.
An experiment on 100 digits
How much do these things matter? Use a small task where augmentation has the best chance: a network of the P4.10 kind () trained on only 100 digit images, tested on the other 1,697. Three runs, with the same starting weights and the same order of data:
- no augmentation,
- shift half the time: with probability 0.5, move the image by , or pixels in each direction (the random crop with padding 1 of above),
- shift every time: with probability 1.
Each run is tested twice: on the test images as they are (the digits are centred) and on the same test images shifted by a random step of at most one pixel. Five different splits and starting weights, averaged. The cell trains 15 networks for 200 epochs each, so allow a few seconds.
First run downloads about 9 MB (Python 6, NumPy 3; once) and a 118 KB data file. The cells of this lesson share their variables, so run them in order.
100 training images, 5 seeds shift prob as is shifted test 0.0 0.887 0.348 0.5 0.886 0.775 1.0 0.856 0.821 seconds: 2.3
What the numbers say, and what they do not:
- On the shifted test images, augmentation is a large win. Accuracy rises from about 0.35 to 0.78 with shifts half the time and to 0.82 with shifts every time. The network without augmentation never saw a shifted digit, so a one-pixel move breaks it. This is what augmentation is for.
- On the centred test images it is not a win. Shifting half the time gives about the same accuracy as no augmentation (0.886 against 0.887; with five runs and 1,697 images a gap this small is noise). Shifting every time costs about three points (0.856), and it was worse in all five runs. Only one shifted image in nine is still centred, so the network practises on a different set of pictures from the one it is tested on.
- Augmented runs need more training. With 60 epochs instead of 200 (the same cell with
epochs=60), the numbers on the centred images are 0.884 with no shifts, 0.864 with half shifts and 0.774 with shifts every time, and on the shifted images 0.350, 0.613 and 0.706. The augmented networks had not finished learning. Each epoch shows each image once, in one of up to nine positions, so there is more to learn. At 200 epochs the augmented runs may still not have fully converged; the cell does not check this. - This is one small, easy task. It uses whole-pixel shifts on 8 by 8 images, where one pixel is a large move. On the big photo sets of the papers, augmentation is reported to help on ordinary test images too. Do not carry the numbers from here to those.
The lesson of the experiment is the one of the bet above: augmentation pays when the variation it adds is variation the model will meet. It is not free: it needs a good choice of changes, a size that fits, and more epochs.
Summary: intuition, math, code
Intuition
Imagine teaching a child what a 6 is by showing one drawing. Now show it slightly higher on the page, slightly bigger, a little darker. The child learns that these things do not matter. Augmentation does this for a network. The analogy breaks in one place: the child can tell that a 6 upside down is a 9, and a network only learns this if you do not show it that picture labelled “6”. The model has no common sense about which changes are safe: you do.
Math
Training minimizes the average loss . With augmentation, each example is first changed by a random transformation drawn from a distribution (flip or not, crop offset, angle, noise), and the objective is the average over both:
One fresh draw of per example per step is a Monte Carlo estimate of the inside average. Mixup: , , with ; the cross-entropy with soft label is . Photometric: for contrast and brightness . Crop count: padding on a -wide image gives crop positions per direction.
Code
The core of an on-the-fly shift and a mixup step in NumPy. The full experiment with its output is in the section above.
def mixup(xb, Yb, rng, alpha=0.4):
lam = rng.beta(alpha, alpha) # one lambda per batch
j = rng.permutation(len(xb)) # a random partner for each image
return (1 - lam) * xb + lam * xb[j], (1 - lam) * Yb + lam * Yb[j]
# inside the training loop, with Yb one-hot:
# xb = random_shift(Xtr[i], rng, p_shift) # fresh random shifts
# xb, Yb = mixup(xb, Yb, rng) # optionalCheck your understanding
You train a digit classifier and add a random 180 degree rotation to every training image, keeping each label. What is the most likely problem?
A 6 turned by 180 degrees looks like a 9 (and the other way round), so the label "6" is wrong for that image and the network is taught the wrong answer. Augmentation does not make the training set smaller. A rotation by 180 degrees does not change the number of pixels. The validation images are not rotated, because only the training images are augmented.
Mixup blends a picture of a cat (label cat) and a picture of a dog (label dog) with , where weights the dog. What are the pixels and the label of the mixed example?
Mixup uses the same weights on the pixels and on the labels: for the cat and for the dog. The swapped weights would put the larger share on the dog. Keeping a hard label "cat" throws away the mixing of the label. The pasted square describes CutMix, not mixup.
A student makes 10 augmented copies of every image in a data set, and only then splits the data into training and validation sets at random. What goes wrong?
The split is random over images, so a picture and its copies often land on different sides. The model is then tested on near-duplicates of what it trained on, and the score overstates how it will do on new data. Split first and augment only the training part. The sizes of the sets are not the problem, and the copies do not cancel.
On the 8 by 8 digits, a network trained with a random shift of every training image scored lower on the ordinary, centred test images than one trained with no shifts, but much higher on shifted test images. What explains it?
With shifts of , or in each direction, only one training image in nine is still centred, and the shifted test set matches what the network practised on. A shift of one pixel does not change a digit's label. The scores are averages over five splits with 1,697 test images each, so they are not a fluke of one draw. Augmentation raised accuracy on the shifted test images, so it cannot only lower it.
Which is the right place to apply a random flip in a training pipeline?
Fresh random changes of the training images give the model different versions every epoch, and the evaluation sets stay untouched so they measure real data. Flipping the test images changes what is measured. One fixed pass of changes gives the model only one version of each image. A class label has no left and right to mirror (boxes or masks must move with the pixels, which is a different case).
Exercises
- Mixup with blends image 1 (a pixel with value , label A) and image 2 (the same pixel with value , label B). What is the mixed pixel, and what is the label vector over the classes (A, B)?
Show answer
The pixel is . The label is . The weights and are the same for the pixel and the label. - A image is padded by 4 pixels on each side and a window is cut at a random place. How many different windows are possible? With a random flip as well, how many versions of one image?
Show answer
The padded image is , so the window can start in places in each direction: windows. With flip or no flip it is versions. - A data set has 50,000 images. You store 20 augmented copies of each, as 8-bit images of pixels. How many images and how many megabytes (1 MB is 1,000,000 bytes)? Why does on-the-fly augmentation avoid this?
Show answer
images. Each has bytes, so about bytes, or about 3,072 MB (3.1 GB). On the fly, the copies are made when a batch is built and thrown away afterwards, so only the original 50,000 images are stored, and every epoch can draw new versions. - CutMix pastes a patch of image 2 into a image 1. What is the mixed label if image 1 is “cat” and image 2 is “dog”?
Show answer
The patch covers of pixels, which is of the picture. The label is 75 per cent cat and 25 per cent dog. - A brightness change adds to every pixel and the result is clipped to the range 0 to 1. What happens to a pixel of value 0.8, and to a pixel of value 0.1? Why does the clip matter for a bright image?
Show answer
is clipped to , and . Every bright pixel that would go above 1 ends at exactly 1, so bright areas flatten into pure white and the detail in them is lost. A strong brightness change can destroy the information in a bright image. - For a data set of photos of street signs, explain why a random horizontal flip is risky, and give a case where it is safe.
Show answer
Many signs contain text, arrows or letters that change meaning when mirrored: a left-turn arrow becomes a right-turn arrow, so the label would be wrong. A flip is safe for a class whose picture does not depend on left or right, such as a circular sign with a symmetric symbol. In practice you check the classes one by one, or leave the flip out.
Next: P4.17 covers the other regularizers of neural networks (weight decay, dropout, early stopping), which work on the model and the loss instead of the data. P5.7 trains a CNN on CIFAR-10 with random crops and flips, and P4.22 shows how to tell whether a model is overfitting.