RandAugment is a data augmentation method that randomly picks N of 14 image transformations each time and applies all of them at the same magnitude M. Only two values, N and M, 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).
AutoAugment
RandAugment
How transformations are chosen
From 25 searched sub-policies
Uniformly from 14 types
Probability of applying a transformation
Searched per transformation
None (a chosen transformation is always applied)
Transformation magnitude
Searched per transformation
The same M for all
Values to tune
30 or more
Two: N and M
Search space (number of policies)
About 1032
About 102
Where the search runs
A small proxy task
Directly on the target task
Because the search space is so small, a simple grid search over N and M 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).
Pick one of the following 14 transformations uniformly (with probability 1/14). Repeat this N times (the same transformation can be picked twice).
Apply all the chosen transformations in the order they were picked. Every transformation uses the same magnitude M.
Since N picks are made from K=14 types, there are KN possible sequences of transformations for one image.
The magnitude M 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=10 corresponds to 30 degrees for Rotate and a shear of 0.3 for ShearX. The paper tried four schedules for M 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 N or M strengthens regularization. Both have an intuitive meaning, so a person can adjust them to the situation, for example "the model got bigger, so raise M".
Why searching on a proxy task was dropped
On CIFAR-10, the paper trained Wide-ResNets while varying a magnitude M shared by all transformations, and examined how the best M changes (N=1).
Larger models have a larger optimal M: 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 M: 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 M for all transformations was 0.19% for Rotate and 0.07% for TranslateX. The paper therefore concludes that collapsing the magnitude into a single M costs little.
Choosing N and M
N and M 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}, Mβ{2,6,10,14}).
Even on the same dataset, larger models get a larger M.
M can exceed 10. The values M=14, 17, and 28 in the table above are stronger transformations beyond the maximum of the range used by AutoAugment (M=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).
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=3, M=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 M 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 M.
The arguments are num_ops (= N, 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=9 corresponds to 27 degrees.
To match the paper's M, 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 %.
For image classification, when strong augmentation is wanted with little effort: use RandAugment. There is no search stage; trying a few combinations of N and M is enough.
When model or dataset size changes: use RandAugment. Raising or lowering M 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 N 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=2 and M=9 were chosen for ResNet-50 on ImageNet, and N=3 with M=4 to 9 on CIFAR-10. Larger models and more data favored a larger M, 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=9 (with 10 as the maximum) corresponds to 27 degrees. To match the paper, set num_magnitude_bins=11.