AI Logic

Data Augmentation

AutoAugment

Updated:

Diagram of AutoAugment. The left side shows the policy search: an RNN controller outputs a policy, a child model is trained with it, and the controller is updated using the validation accuracy as the reward; this is repeated about 15,000 times and the top 5 policies are concatenated. The right side shows a table of sub-policies 0 to 4 of the policy found on CIFAR-10, and the four possible outcomes, with their probabilities, of applying sub-policy 1 (Rotate and TranslateX) to a triangle image

What is AutoAugment?

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).

OperationDescriptionMagnitude range
ShearX, ShearYShift and slant horizontally or verticallyβˆ’0.3 to 0.3
TranslateX, TranslateYTranslate horizontally or verticallyβˆ’150 to 150 pixels
RotateRotateβˆ’30 to 30 degrees
AutoContrastMaximize contrast by making the darkest pixel black and the brightest whiteNone
InvertInvert pixel intensitiesNone
EqualizeFlatten the brightness histogramNone
SolarizeInvert only pixels brighter than a threshold0 to 256
PosterizeReduce the number of bits per pixel4 to 8 bits
Contrast, Color, Brightness, SharpnessChange contrast, saturation, brightness, or sharpness (1 is the original image)0.1 to 1.9
CutoutFill a square with graySide length 0 to 60 pixels
Sample PairingAdd another image from the mini-batch with a weight (label unchanged)0 to 0.4

There are (16Γ—10Γ—11)2(16 \times 10 \times 11)^2 ways to choose a single sub-policy, and (16Γ—10Γ—11)10β‰ˆ2.9Γ—1032(16 \times 10 \times 11)^{10} \approx 2.9 \times 10^{32} 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).

  1. 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.
  2. 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.
  3. Measure validation accuracy RR: The child model's accuracy is measured on validation data held out from the training data.
  4. Update the controller: Using RR 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.
  5. Repeat steps 1 to 4. About 15,000 policies are tried per dataset.
  6. 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 searchChild modelGPU hours (NVIDIA P100 equivalent)
4,000 images from CIFAR-10Wide-ResNet-40-2 (120 epochs)5,000
1,000 images from SVHNWide-ResNet-40-2 (120 epochs)1,000
6,000 images from 120 ImageNet classesWide-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).

  1. For each image, choose one of the 25 sub-policies uniformly at random.
  2. Apply the sub-policy's first operation with its specified probability. When it is applied, use the specified magnitude.
  3. 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.490.7 \times 0.7 = 0.49, and the probability that both are applied is 0.7Γ—0.3=0.210.7 \times 0.3 = 0.21.

On CIFAR, it is combined with standard augmentation and applied in the following order.

  1. Standard augmentation (horizontal flip, cropping after padding)
  2. The AutoAugment policy
  3. Cutout (side length 16 pixels)

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.

DatasetModelStandard+ Cutout+ AutoAugment
CIFAR-10Wide-ResNet-28-103.93.12.6
CIFAR-10Shake-Shake (26 2x96d)2.92.62.0
CIFAR-10PyramidNet + ShakeDrop2.72.31.5
CIFAR-100PyramidNet + ShakeDrop14.012.210.7
SVHNShake-Shake (26 2x96d)1.41.21.0
1,000 images from SVHNWide-ResNet-28-1013.232.58.2

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.

DatasetStandard+ AutoAugment (ImageNet policy)
Oxford 102 Flowers6.74.6
Caltech-10119.413.1
Oxford-IIIT Pets13.511.0
FGVC Aircraft9.17.3
Stanford Cars6.45.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 %).

MethodHow policies are foundSearch spaceCIFAR-10 (PyramidNet)ImageNet (ResNet-50)
Standard augmentationNo searchβˆ’97.376.3
AutoAugmentSearch with reinforcement learning (separate stage)103210^{32}98.577.6
Fast AutoAugmentFast search by density matching (separate stage)103210^{32}98.377.6
PBASearch with Population Based Augmentation (separate stage)106110^{61}98.5βˆ’
RandAugmentOperations chosen uniformly; grid search only over the number NN and magnitude MM10210^{2}98.577.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 NN and the magnitude MM, 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.

References

  1. E. D. Cubuk, B. Zoph, D. ManΓ©, V. Vasudevan, and Q. V. Le, "AutoAugment: Learning Augmentation Strategies from Data," CVPR, 2019.
  2. E. D. Cubuk, B. Zoph, J. Shlens, and Q. V. Le, "RandAugment: Practical automated data augmentation with a reduced search space," CVPR Workshops, 2020.
  3. B. Zoph, V. Vasudevan, J. Shlens, and Q. V. Le, "Learning Transferable Architectures for Scalable Image Recognition," CVPR, 2018.
  4. PyTorch, torchvision.transforms.AutoAugment