AI Logic

Data Augmentation

RandAugment

Updated:

RandAugment diagram. Left: AutoAugment (searches a policy with reinforcement learning on a small proxy task, fixes it, then trains the target model; search space about 10^32). Middle: RandAugment (grid-searches N and M on the target task and applies N transformations at magnitude M to each image; search space about 10^2). Right: the list of 14 transformations and an example of a triangle image with Rotate and ShearX applied at M = 3 and M = 9

What is RandAugment

RandAugment is a data augmentation method that randomly picks NN of 14 image transformations each time and applies all of them at the same magnitude MM. Only two values, NN and MM, are tuned, so no separate policy search stage is needed. It was proposed by Cubuk et al. at Google in 2019 and presented at a CVPR 2020 workshop.

AutoAugment uses reinforcement learning to search, over thousands of GPU hours, for which transformations to apply with what probability and magnitude (the policy). Because the search is so expensive, it was run on a "proxy task" built from a small model and a subset of the data, and the policy found there was then used for the large target model. The RandAugment paper showed that the optimal augmentation magnitude depends on model size and dataset size, and pointed out that a policy found on a proxy task may not be optimal on the target task.

RandAugment therefore makes the policy extremely simple (see the figure at the top).

AutoAugmentRandAugment
How transformations are chosenFrom 25 searched sub-policiesUniformly from 14 types
Probability of applying a transformationSearched per transformationNone (a chosen transformation is always applied)
Transformation magnitudeSearched per transformationThe same MM for all
Values to tune30 or moreTwo: NN and MM
Search space (number of policies)About 103210^{32}About 10210^{2}
Where the search runsA small proxy taskDirectly on the target task

Because the search space is so small, a simple grid search over NN and MM on the target model was enough to match or exceed AutoAugment's accuracy.

Procedure

For each training image, RandAugment does the following (right side of the figure at the top).

  1. Pick one of the following 14 transformations uniformly (with probability 1/141/14). Repeat this NN times (the same transformation can be picked twice).
    • Identity, AutoContrast, Equalize, Rotate, Solarize, Color, Posterize
    • Contrast, Brightness, Sharpness, ShearX, ShearY, TranslateX, TranslateY
  2. Apply all the chosen transformations in the order they were picked. Every transformation uses the same magnitude MM.

Since NN picks are made from K=14K = 14 types, there are KNK^N possible sequences of transformations for one image.

The magnitude MM is expressed on the same integer scale of 0 to 10 as in AutoAugment, where 10 is the maximum of the range AutoAugment used. For example, M=10M = 10 corresponds to 30 degrees for Rotate and a shear of 0.3 for ShearX. The paper tried four schedules for MM during training ("constant", "random", "linearly increasing", and "random with an increasing upper bound"); all performed about the same, so it adopts "constant", which needs only one value.

The paper's implementation (Figure 2) is just two lines.

sampled_ops = np.random.choice(transforms, N)
return [(op, M) for op in sampled_ops]

Increasing either NN or MM strengthens regularization. Both have an intuitive meaning, so a person can adjust them to the situation, for example "the model got bigger, so raise MM".

Why searching on a proxy task was dropped

On CIFAR-10, the paper trained Wide-ResNets while varying a magnitude MM shared by all transformations, and examined how the best MM changes (N=1N = 1).

  • Larger models have a larger optimal MM: across seven Wide-ResNet-28 models of different widths, the wider the model, the larger the optimal magnitude. Larger models need stronger regularization.
  • More data means a larger optimal MM: when the number of training images was varied, the optimal magnitude grew with the amount of data. This is the opposite of the intuition that "less data needs stronger regularization." The paper suggests that strong augmentation on a small dataset may make the noise too large relative to the signal.
  • AutoAugment's magnitudes are fixed: the magnitudes in AutoAugment's policy stay the same regardless of model or dataset size, and they were off from the optimum under every condition.

In other words, magnitudes found on a proxy task with a small model and little data may be too weak for the target task with a large model and the full data.

Optimizing the magnitude for each transformation separately also brought almost no improvement. When the best magnitude was searched for just one transformation, the difference in accuracy from a common MM for all transformations was 0.19% for Rotate and 0.07% for TranslateX. The paper therefore concludes that collapsing the magnitude into a single MM costs little.

Choosing N and M

NN and MM are chosen by grid search on the target model and data, based on validation results. In the paper, trying a few to a dozen or so combinations was enough (for example, 8 combinations on CIFAR-100: N∈{1,2}N \in \{1, 2\}, M∈{2,6,10,14}M \in \{2, 6, 10, 14\}).

The values selected in the paper are as follows.

DatasetModelNNMM
CIFAR-10Wide-ResNet-28-234
CIFAR-10Wide-ResNet-28-1035
CIFAR-10PyramidNet + ShakeDrop37
CIFAR-100Wide-ResNet-28-212
CIFAR-100Wide-ResNet-28-10214
ImageNetResNet-5029
ImageNetEfficientNet-B52 or 317
ImageNetEfficientNet-B7228
COCO (object detection)ResNet-101 / ResNet-20015 / 6

Even on the same dataset, larger models get a larger MM.

MM can exceed 10. The values M=14M = 14, 17, and 28 in the table above are stronger transformations beyond the maximum of the range used by AutoAugment (M=10M = 10). The paper keeps 10 as the maximum of that range and extends the scale beyond it. Check whether your library can represent magnitudes above 10.

Results reported in the paper

The table below compares image classification test accuracy (%) with other automated augmentation methods. "Baseline" is the standard augmentation for each dataset (flips, crops, and Cutout for CIFAR).

DatasetModelBaselineAutoAugmentRandAugment
CIFAR-10Wide-ResNet-28-294.995.995.8
CIFAR-10PyramidNet + ShakeDrop97.398.598.5
CIFAR-100Wide-ResNet-28-1081.282.983.3
SVHN (73,000 images only)Wide-ResNet-28-296.798.098.3
ImageNet (top-1)ResNet-5076.377.677.6
ImageNet (top-1)EfficientNet-B583.283.383.9
ImageNet (top-1)EfficientNet-B784.084.485.0

For small models RandAugment is on par with AutoAugment, and the gap widens as models grow. The 85.0% of EfficientNet-B7 on ImageNet was the state of the art at the time of publication. For Wide-ResNet-28-2 on SVHN, training with RandAugment on only 73,000 images (98.3%) outperformed training with baseline augmentation on an additional 531,000 images (98.2%).

For COCO object detection (RetinaNet, mAP) with ResNet-101, the baseline scored 38.8, AutoAugment 40.4, and RandAugment 40.1. AutoAugment uses transformations specific to bounding boxes and searched for about 15,000 GPU hours, while RandAugment tried only six values.

The effect of each transformation was also measured (CIFAR-10, Wide-ResNet-28-2, N=3N = 3, M=4M = 4). The average change in validation accuracy when one transformation is added to a randomly chosen set was large for Rotate (+1.3%) and ShearX and ShearY (+0.9%), while Posterize (βˆ’0.3%) and Solarize (βˆ’0.1%) lowered it. Even so, using all 14 types together gave good results as a combination.

Practical notes

  • Combine it with the standard augmentation. In the paper, RandAugment is applied after horizontal flips and crops on ImageNet, and Cutout is also used on CIFAR and SVHN.
  • Retune MM when the model or data changes. The optimal magnitude depends on model size and dataset size.
  • For object detection, transform the boxes too. In the paper's COCO experiments, the bounding boxes are transformed along with geometric transformations such as rotation and translation.

The magnitude of torchvision's transforms.RandAugment uses a different scale from the paper's MM.

  • The arguments are num_ops (= NN, default 2), magnitude (default 9), and num_magnitude_bins (default 31).
  • The magnitude is an index on a scale that divides "0 to maximum" into num_magnitude_bins steps. With the default 31 steps the maximum is magnitude=30, so Rotate with magnitude=9 is 9 degrees. On the paper's scale (10 is the maximum), M=9M = 9 corresponds to 27 degrees.
  • To match the paper's MM, set num_magnitude_bins=11 and pass magnitude=M. However, this implementation cannot represent magnitudes beyond the maximum (such as 30 degrees for Rotate).
  • Apply it to PIL images or uint8 tensors. Place it before ToTensor and Normalize.

Comparison with similar methods and how to choose

The table below lists methods that determine data augmentation automatically, following the comparison in the RandAugment paper (Table 1). The search space is the order of magnitude of the number of policies, and accuracy is in %.

MethodHow the policy is foundSearch spaceCIFAR-10 (PyramidNet)ImageNet (ResNet-50)
Baseline augmentationNo searchβˆ’97.376.3
AutoAugmentReinforcement learning (separate stage)103210^{32}98.577.6
Fast AutoAugmentFast search by density matching (separate stage)103210^{32}98.377.6
PBAPopulation Based Augmentation (separate stage)106110^{61}98.5βˆ’
RandAugmentGrid search over only NN and MM on the target task10210^{2}98.577.6

Rules of thumb for choosing:

  • For image classification, when strong augmentation is wanted with little effort: use RandAugment. There is no search stage; trying a few combinations of NN and MM is enough.
  • When model or dataset size changes: use RandAugment. Raising or lowering MM is enough to adjust the strength.
  • When a published policy should be used as is: for data similar to CIFAR, SVHN, or ImageNet, AutoAugment's policies (torchvision's AutoAugment) are also easy to use.

The paper also tried learning the probabilities of choosing transformations by differentiation, which slightly improved accuracy over RandAugment on CIFAR-10 (95.8% β†’ 96.1% with Wide-ResNet-28-2). However, it requires applying every transformation NN times per image, which becomes expensive for large images.

PyTorch example

Show code
python
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader

'''
CIFAR-10 image classification (trained with RandAugment)
'''

# The paper's Figure 2 implementation (the idea): pick uniformly N times from 14 types and apply all at magnitude M
paper_transforms = ['Identity', 'AutoContrast', 'Equalize', 'Rotate', 'Solarize', 'Color', 'Posterize',
                    'Contrast', 'Brightness', 'Sharpness', 'ShearX', 'ShearY', 'TranslateX', 'TranslateY']


def randaugment(N, M):
  sampled_ops = np.random.choice(paper_transforms, N)
  return [(op, M) for op in sampled_ops]


print(randaugment(2, 9))  # e.g. [('Rotate', 9), ('Equalize', 9)]

# Hyperparameters
batch_size = 128      # batch size
epochs = 5            # number of epochs
learning_rate = 1e-3  # learning rate
N, M = 3, 5           # Paper's values for CIFAR-10 / Wide-ResNet-28-10. In practice, grid-search on validation data

# '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),   # standard augmentation
  transforms.RandomHorizontalFlip(),
  transforms.RandAugment(                 # works on PIL images or uint8 tensors, so place it before ToTensor
    num_ops=N,                            # number of transformations per image (default 2)
    magnitude=M,                          # index on the magnitude scale (default 9)
    num_magnitude_bins=11,                # default 31; 11 gives a 0-10 scale matching the paper's M (10 is the maximum)
  ),
  transforms.ToTensor(),
  transforms.Normalize(mean, std),
])
test_transform = transforms.Compose([     # no 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)


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: 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. Which values of N and M should be tried first?
A.

The paper's values are a good guide. N=2N = 2 and M=9M = 9 were chosen for ResNet-50 on ImageNet, and N=3N = 3 with M=4M = 4 to 9 on CIFAR-10. Larger models and more data favored a larger MM, so start from values close to the paper's and compare a few combinations on validation data.

Q. Is it really fine for every transformation to have the same probability of being chosen?
A.

In the paper, uniform selection alone reached about the same accuracy as AutoAugment. Learning the probabilities was also tried and gave a small improvement on CIFAR-10, but at a higher computational cost. Looking at individual transformations, Rotate and Shear tend to help and Posterize less so, yet using all 14 types together gave good results.

Q. Is torchvision RandAugment's default (magnitude=9) the same as the paper's M = 9?
A.

No. torchvision's default divides the magnitude into 31 steps, so magnitude=9 is 9/30 of the maximum, which is 9 degrees for Rotate. The paper's M=9M = 9 (with 10 as the maximum) corresponds to 27 degrees. To match the paper, set num_magnitude_bins=11.

References

  1. E. D. Cubuk, B. Zoph, J. Shlens, and Q. V. Le, "RandAugment: Practical automated data augmentation with a reduced search space," CVPR Workshops, 2020.
  2. E. D. Cubuk, B. Zoph, D. ManΓ©, V. Vasudevan, and Q. V. Le, "AutoAugment: Learning Augmentation Strategies from Data," CVPR, 2019.
  3. tensorflow/tpu (the paper's implementation, models/official/efficientnet)
  4. PyTorch, torchvision.transforms.RandAugment