AutoAugment is a method that uses reinforcement learning to automatically search for which data augmentations to apply and with what probability and magnitude (a policy). It was released by Cubuk et al. at Google Brain in 2018 and presented at CVPR 2019.
Data augmentations such as rotation, flipping, and color changes used to be chosen by hand for each dataset. However, good combinations differ from dataset to dataset. For example, horizontal flipping helps on CIFAR-10 (photos) but not on MNIST (handwritten digits), because flipping a digit turns it into a different shape. AutoAugment determines this choice from data by framing it as the problem of finding the policy that maximizes validation accuracy.
AutoAugment consists of the following two stages (see the diagram at the top).
Search (left): Thousands of policies are tried with a small dataset and a small model to find good ones.
Use (right): The policy found is used as data augmentation when training the production model.
The policies found can be transferred to other datasets and models. In the paper, applying a policy found on ImageNet to fine-grained classification datasets of flowers, aircraft, cars, and so on also greatly reduced error rates.
The search requires heavy computation, but the policies found in the paper (for CIFAR-10, SVHN, and ImageNet) are public and built into torchvision. You can pick the policy for similar data and use it without running the search yourself.
Structure of a policy (what is searched)
The "policy" AutoAugment searches for has the following nested structure.
Policy: A set of 5 sub-policies.
Sub-policy: Two operations applied in a fixed order.
Operation: A triple of the following.
Type: one of the 16 types in the table below
Probability: the probability of applying the operation (0 to 1 in 11 steps)
Magnitude: the size of the operation, such as the rotation angle (the range in 10 steps)
The operation types and their magnitude ranges are as follows (ranges are for 331 Γ 331 images).
Operation
Description
Magnitude range
ShearX, ShearY
Shift and slant horizontally or vertically
β0.3 to 0.3
TranslateX, TranslateY
Translate horizontally or vertically
β150 to 150 pixels
Rotate
Rotate
β30 to 30 degrees
AutoContrast
Maximize contrast by making the darkest pixel black and the brightest white
None
Invert
Invert pixel intensities
None
Equalize
Flatten the brightness histogram
None
Solarize
Invert only pixels brighter than a threshold
0 to 256
Posterize
Reduce the number of bits per pixel
4 to 8 bits
Contrast, Color, Brightness, Sharpness
Change contrast, saturation, brightness, or sharpness (1 is the original image)
Add another image from the mini-batch with a weight (label unchanged)
0 to 0.4
There are (16Γ10Γ11)2 ways to choose a single sub-policy, and (16Γ10Γ11)10β2.9Γ1032 ways for a whole policy, which chooses 5 sub-policies at once. There is no "do nothing" operation, but setting the probability to 0 has the same effect.
Search procedure
The search uses the same mechanism as NAS with reinforcement learning (automatic search for network architectures) (left side of the diagram at the top).
The controller outputs a policy: The controller is a one-layer LSTM (100 hidden units). It makes 30 choices in total, 5 sub-policies Γ 2 operations Γ 3 values (type, probability, magnitude), one at a time with a softmax.
Train a child model: A small model with a fixed architecture (the child model) is trained while applying data augmentation with that policy. For each image in a mini-batch, one of the 5 sub-policies is chosen at random and applied.
Measure validation accuracy R: The child model's accuracy is measured on validation data held out from the training data.
Update the controller: Using R as the reward, the controller is updated with PPO (a kind of policy gradient method) so that it becomes more likely to output good policies. Reinforcement learning is used because accuracy is not differentiable with respect to the policy.
Repeat steps 1 to 4. About 15,000 policies are tried per dataset.
Concatenate the top 5 policies: The sub-policies of the 5 best policies are combined into a final policy of 25 sub-policies.
To reduce computation, the search is performed on small subsets of data with small models.
Data used for the search
Child model
GPU hours (NVIDIA P100 equivalent)
4,000 images from CIFAR-10
Wide-ResNet-40-2 (120 epochs)
5,000
1,000 images from SVHN
Wide-ResNet-40-2 (120 epochs)
1,000
6,000 images from 120 ImageNet classes
Wide-ResNet-40-2 (200 epochs)
15,000
The paper states that reinforcement learning was used for convenience, and that its main contribution is not the search algorithm but the design of a search space that represents data augmentation as policies.
How it is used in training
The policy found is used in production training as follows (right side of the diagram at the top).
For each image, choose one of the 25 sub-policies uniformly at random.
Apply the sub-policy's first operation with its specified probability. When it is applied, use the specified magnitude.
Apply the second operation with its probability in the same way.
Even for the same sub-policy, whether "both are applied," "only one is applied," or "neither is applied" depends on the probabilities, so different images are produced from the same image in each mini-batch. In the example in the diagram at the top (Rotate with probability 0.7, TranslateX with probability 0.3), the probability that only rotation is applied is 0.7Γ0.7=0.49, and the probability that both are applied is 0.7Γ0.3=0.21.
On CIFAR, it is combined with standard augmentation and applied in the following order.
Standard augmentation (horizontal flip, cropping after padding)
The contents of the policies found reflect the characteristics of each dataset well.
CIFAR-10: Many color-related operations such as Equalize, AutoContrast, Color, and Brightness were selected. Invert was hardly ever selected.
SVHN (house numbers): Invert, Equalize, ShearX/Y, and Rotate were selected frequently. For digits, the contrast against the background matters more than the colors themselves, so a digit remains the same digit when inverted. Also, house-number photos are often taken at an angle, so slanting operations are helpful.
ImageNet: As with CIFAR-10, color operations dominated, and Rotate was also selected often.
Results reported in the paper
Test error rates (%) on CIFAR and SVHN are as follows. "Standard" is each model's standard preprocessing (horizontal flip and cropping for CIFAR), and "+ AutoAugment" adds the policy to it; CIFAR uses the policy found on CIFAR-10 and SVHN uses the policy found on SVHN.
Top-1 accuracy (%) on ImageNet rose from 76.3 to 77.6 for ResNet-50, from 78.5 to 80.0 for ResNet-200, and from 83.1 to 83.5 for AmoebaNet-C.
The results of applying the policy found on ImageNet directly to other datasets (Inception v4 trained from scratch, top-1 error %) are as follows.
Dataset
Standard
+ AutoAugment (ImageNet policy)
Oxford 102 Flowers
6.7
4.6
Caltech-101
19.4
13.1
Oxford-IIIT Pets
13.5
11.0
FGVC Aircraft
9.1
7.3
Stanford Cars
6.4
5.2
The paper's ablation experiments (CIFAR-10, Wide-ResNet-28-10) also showed the following.
Learning probabilities and magnitudes matters: Keeping the operation types of the found policy but randomizing only the probabilities and magnitudes raised the error from 2.6% to 3.0%. Randomizing the whole policy gave 3.1% (still an improvement over standard augmentation).
More sub-policies are better: Increasing the number of sub-policies used raised validation accuracy up to about 20.
Practical notes
Running the search yourself is very expensive. The CIFAR-10 search alone took 5,000 GPU hours. In most cases, pick the published policy that is closest to your data and use it. In the paper, using the CIFAR-10 policy to train on SVHN did improve results, but not as much as the policy found on SVHN.
Train for longer. Sub-policies are applied stochastically, so the effect only appears once each sub-policy has been applied many times. In the paper, child models had to be trained for more than 80 to 100 epochs, so 120 epochs were used.
Magnitudes found on a small proxy task do not necessarily suit production. The later RandAugment paper showed that the optimal augmentation magnitude depends on model size and dataset size, and pointed out that policies found with small models and little data may not be optimal in production.
When using torchvision's transforms.AutoAugment, keep the following in mind.
Apply it to PIL images or uint8 tensors. Do not place it after ToTensor (which converts to floats in 0 to 1) or Normalize; place it before them.
The default policy is AutoAugmentPolicy.IMAGENET. Specify AutoAugmentPolicy.CIFAR10 for CIFAR and AutoAugmentPolicy.SVHN for digit images.
The paper's CIFAR setting also applies Cutout (16 Γ 16) after the policy, but this is not included in AutoAugment. To follow the paper, add Cutout separately.
The value used to fill areas exposed by rotation or translation is set with fill (the default is 0, which gives black).
Comparison with similar methods and how to choose
After AutoAugment, several methods were proposed to reduce the cost of the search. The comparison compiled under the same conditions in the RandAugment paper is as follows (search space is the order of magnitude of the number of policies; accuracy is in %).
Method
How policies are found
Search space
CIFAR-10 (PyramidNet)
ImageNet (ResNet-50)
Standard augmentation
No search
β
97.3
76.3
AutoAugment
Search with reinforcement learning (separate stage)
Operations chosen uniformly; grid search only over the number N and magnitude M
102
98.5
77.6
Rough guidelines for choosing are as follows.
You want strong augmentation right away without searching: Use a published AutoAugment policy (torchvision's AutoAugment) or RandAugment.
You want to tune the magnitude to your model and data size: Use RandAugment. Since only two values are tuned, you can grid search directly on the production model.
Your data differs greatly from CIFAR, SVHN, and ImageNet, and you have compute to spare: Search for a policy for your own data with AutoAugment or Fast AutoAugment.
PyTorch example
βΆShow code
python
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torchvision.transforms import AutoAugment, AutoAugmentPolicy, InterpolationMode
from torch.utils.data import DataLoader
'''
CIFAR-10 image classification (trained with the CIFAR-10 policy found in the paper)
'''
# Hyperparameters
batch_size = 128 # Batch size
epochs = 5 # Number of epochs
learning_rate = 1e-3 # Learning rate
# Use 'cuda' if available, 'mps' on Apple Silicon, otherwise 'cpu'
device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'
mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4), # 1. Standard augmentation
transforms.RandomHorizontalFlip(),
AutoAugment( # 2. AutoAugment policy (works on PIL or uint8 tensors, so before ToTensor)
policy=AutoAugmentPolicy.CIFAR10, # Default is IMAGENET. SVHN is also available
interpolation=InterpolationMode.NEAREST, # Interpolation for rotation etc. (default)
fill=None, # Value to fill exposed areas (0 if None)
),
transforms.ToTensor(),
transforms.Normalize(mean, std),
transforms.RandomErasing(p=1.0, scale=(0.25, 0.25), ratio=(1.0, 1.0), value=0), # 3. Close to Cutout (16x16)
])
test_transform = transforms.Compose([ # No data augmentation for evaluation
transforms.ToTensor(),
transforms.Normalize(mean, std),
])
train_dataset = datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
test_dataset = datasets.CIFAR10(root='./data', train=False, download=True, transform=test_transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
# Contents of the policy: 25 sub-policies. Each is ((type, probability, magnitude), (type, probability, magnitude))
policy = AutoAugment(AutoAugmentPolicy.CIFAR10).policies
print(len(policy), policy[1]) # 25 (('Rotate', 0.7, 2), ('TranslateX', 0.3, 9))
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(3, 32, kernel_size=3, padding=1), # [B, 3, 32, 32] -> [B, 32, 32, 32]
nn.BatchNorm2d(32),
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 32, 16, 16]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> [B, 64, 16, 16]
nn.BatchNorm2d(64),
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 64, 8, 8]
nn.Flatten(),
)
self.classifier = nn.Linear(64 * 8 * 8, num_classes)
def forward(self, x):
return self.classifier(self.features(x))
model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training: data augmentation is applied while loading data
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
loss = criterion(model(images), labels)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Evaluation: check on the original images
model.eval()
correct = 0
total = 0
with torch.no_grad():
for images, labels in test_loader:
images, labels = images.to(device), labels.to(device)
predicted = model(images).argmax(dim=1)
total += labels.size(0)
correct += (predicted == labels).sum().item()
print(f"Test Accuracy: {100 * correct / total:.2f}%")
FAQ
Q. Do I have to search for a policy on my own data to use it?
A.
No, you can use it without searching. The CIFAR-10, SVHN, and ImageNet policies found in the paper are public and can be selected in torchvision's AutoAugment. In the paper, applying the ImageNet policy to other fine-grained classification datasets also greatly reduced error rates. That said, a policy found on data closer to yours is more effective.
Q. Should I use AutoAugment or RandAugment?
A.
In most cases, RandAugment is easier. It has only two values to tune, the number N and the magnitude M, so you can grid search directly on the production model, and in the comparison in the RandAugment paper it matched or exceeded AutoAugment's accuracy.
Q. What do the "probability" and "magnitude" of a policy represent?
A.
The probability determines whether the operation is applied (for example, 0.7 means it is applied about 7 times out of 10). The magnitude is the size of the operation when applied, such as the angle for rotation or the number of pixels for translation, expressed as a value on a 10-step scale over the range.