Random Erasing is a data augmentation method that chooses one rectangle in a training image, with random size, aspect ratio, and position, and fills its pixels with random values. The label stays the same. It was proposed by Zhong et al. in 2017 and later presented at AAAI 2020.
The goal is to make models robust to images where part of the object is hidden (occlusion). Collected training data mostly contains images where objects are clearly visible, with little variety in how they are occluded. As a result, a model trained only on such data tends to make mistakes at test time when part of an object is hidden by something else. Random Erasing fills this gap by generating any number of images with different occlusions during training.
Each image has a rectangle filled with probability p and is used unchanged with probability 1โp (right side of the figure at the top). The rectangle's area, aspect ratio, and position change every time, producing a wide range of occlusions, from "slightly hidden" to "nearly half hidden."
The paper lists the following strengths of Random Erasing.
No extra learnable parameters: it can be used simply by adding it to data loading, without changing the model architecture or the training procedure.
Combinable with other augmentation: used together with cropping and horizontal flipping, it lowers the error rate further.
Useful beyond image classification: it also improved accuracy in object detection and person re-identification.
Cutout, proposed around the same time, is also an augmentation that "removes a rectangle from the image," but it comes from a separate paper. Cutout fills a square of fixed size with 0, while Random Erasing also randomizes the size and aspect ratio and fills with random values. The differences are summarized in the section "Comparison with similar methods and how to choose."
Procedure
For each training image, the following steps are performed (Algorithm 1 in the paper; left side of the figure at the top). Let the image width be W, the height H, and the area S=WรH.
Draw a random number in 0โ1; if it is p or greater, do nothing and return the original image.
Choose the area Seโ of the rectangle to erase uniformly from slโ to shโ times the image area.
Choose the aspect ratio reโ (height รท width) uniformly from r1โ to r2โ, and compute the height Heโ and width Weโ (formulas below).
Choose the rectangle's top-left point (xeโ,yeโ) uniformly within the image.
If the rectangle goes outside the image (xeโ+Weโ>W or yeโ+Heโ>H), go back to step 2 and choose again from the area.
Fill each pixel in the rectangle with a random value in 0โ255. The label stays the same.
The side lengths are determined from the area and aspect ratio so that HeโรWeโ=Seโ and Heโ/Weโ=reโ. The paper's image classification experiments used p=0.5, slโ=0.02, shโ=0.4, r1โ=0.3, and r2โ=1/r1โโ3.33. In other words, half of the images are left unchanged, and the other half have a rectangle covering 2% to 40% of the image area filled in.
Random Erasing is used only during training. For evaluation and inference, the original image is fed as is. The processing finishes inside data loading and adds no computation to the model.
In object detection, the positions of object boxes are known, so three ways of choosing where to erase were tried: from the whole image (IRE), from inside each object's box (ORE), and both (I+ORE). On PASCAL VOC 2007, I+ORE, which does both, gave the best results.
Hyperparameters and fill values
There are three hyperparameters: the probability p, the area range slโ to shโ, and the aspect ratio range r1โ to r2โ. On CIFAR-10 with ResNet-18 (pre-activation version), the paper fixed slโ=0.02 and r2โ=1/r1โ and varied the rest one at a time.
Every setting lowered the error rate compared with not using it. With p and shโ varied over 0.2โ0.8, the average error rate was 4.48%, well below 5.17% without it.
It is not very sensitive to the aspect ratio range. The best result was with r1โ=0.3, at an error rate of 4.31%.
Different fill values were also compared (test error rate on CIFAR-10 with ResNet-18, pre-activation version).
Fill value
Error rate (%)
Not used
5.17
Random value 0โ255 per pixel (RE-R)
4.31
ImageNet mean color (RE-M)
4.35
0 (black)
4.62
255 (white)
4.85
Every value improved on not using it; random values and the mean color were nearly the same and better than filling with black or white. The paper uses random values (RE-R) in its subsequent experiments.
Why it works
Random Erasing works because it trains the model to answer from the remaining parts or the overall shape even when part of the object is hidden. A model that always looks only at the same salient part cannot answer when that part is hidden. Showing images with varied occlusions during training reduces overfitting and makes the model robust to occlusion.
As an everyday analogy, it is like "practicing to identify what is in a photo that has several sticky notes on it." The size, shape, and position of the notes change every time, so the habit of relying on one particular spot never forms.
The paper distinguishes it from related methods as follows.
Difference from random cropping: cropping can cut off the edges of an object, while Random Erasing hides only part of the object and keeps its overall shape. The filled area can also be seen as "adding block-shaped noise to the image." The two complement each other.
Difference from dropout: rather than removing input pixels one by one, it removes a contiguous rectangular region and replaces it with random values.
Experiments confirm this difference. On CIFAR-10 with ResNet-18 (pre-activation version), applying "dropout" or "per-pixel random noise" to the images with the same probability of 0.5 actually raised the error rate (5.37%โ6.52% at every strength, versus 5.17% without them). Even with a setting where the number of noise pixels was about the same as the number of pixels Random Erasing fills, the error rate was 6.52%, far from Random Erasing's 4.31%. This shows that hiding a contiguous region, not scattered pixels, is what matters.
Combinations with other augmentation were also examined (test error rate on CIFAR-10 with ResNet-18, pre-activation version).
Horizontal flip
Cropping
Random Erasing
Error rate (%)
11.31
โ
8.30
โ
6.33
โ
10.13
โ
โ
5.17
โ
โ
7.19
โ
โ
5.21
โ
โ
โ
4.31
On its own, cropping helps the most, but combining all three is best: Random Erasing is not a replacement for other augmentation but something to add on top.
Results reported in the paper
Some of the image classification test error rates (%, average of 5 runs) are shown below. All models are compared with the standard augmentation of cropping and horizontal flipping applied.
For all 13 models tested in the paper, the error rate dropped on all three datasets. It also works on grayscale images (Fashion-MNIST).
Robustness to occlusion was also tested. When CIFAR-10 test images were occluded with randomly sized rectangles filled with random values and the occluded area was increased, the error rate of the model trained without Random Erasing rose sharply. With half the image occluded, the model without it had an error rate of 75.04%, while the model trained with Random Erasing had 56.36%.
For object detection (Fast R-CNN, VGG16, mAP on the PASCAL VOC 2007 test set), the results were as follows.
Training data
Not used
Whole image (IRE)
Inside object boxes (ORE)
Both (I+ORE)
VOC 2007
69.1
70.5
71.0
71.5
VOC 2007 + 2012
74.8
75.6
75.8
76.2
Random Erasing (I+ORE), which learns no parameters, scored 0.5 points higher than A-Fast-RCNN (71.0), which trains a separate adversarial network to generate occluded objects.
In person re-identification (the task of finding the same person captured by a different camera), rank-1 accuracy and mAP improved on all three datasets and with all three methods (including TriNet, trained with Triplet Loss). For example, rank-1 on Market-1501 rose from 84.41% to 87.08% with SVDNet (ResNet-50). On CUHK03, which has little training data, rank-1 of TriNet (ResNet-50) rose by 8.28 points (labeled setting).
Practical notes
Combine it with the standard augmentation. As the table above shows, Random Erasing alone falls short of cropping or horizontal flipping. Apply it after cropping and horizontal flipping.
Start with a probability p of 0.5. In the paper it was effective over a wide range of 0.2โ0.8. The premise is that not every image is filled, so original images also remain in training.
In images with small objects, the whole object can be hidden. Since the label does not change, the model is then trained on an image that shows no object at all but carries the original label. The paper also lowers the upper area limit to shโ=0.2 for object detection and person re-identification.
For tasks where object positions are known, also choose the erase location from inside object boxes. In the object detection experiments, choosing per object gave a higher mAP than choosing only from the whole image.
torchvision's transforms.RandomErasing differs from the paper's procedure in some details.
The defaults are p=0.5, scale=(0.02, 0.33), ratio=(0.3, 3.3), and value=0. The upper area limit is smaller than the paper's image classification setting (0.4), and the fill value is 0, not random. To use random values as in the paper, pass value='random' (note that it fills with standard normal random values, not uniform ones).
The aspect ratio is chosen uniformly on a log scale rather than uniformly as in the paper, so tall and wide rectangles are equally likely.
If no in-bounds rectangle is found after 10 tries, it returns the original image unchanged (the paper repeats until one is found).
It only works on tensors, so place it after ToTensor. Placing it after Normalize means value=0 fills with "the data's mean color," which is close to the paper's RE-M (mean color).
Comparison with similar methods and how to choose
The table below compares augmentation methods that "remove or replace part of an image" from the same viewpoints.
Method
Region removed
What fills the removed area
Out of bounds
Label
Random Erasing
One rectangle (random area, aspect ratio, and position)
To build a model robust to occlusion, or to also use it for person re-identification or object detection: use Random Erasing. In the paper it improved image classification, object detection, and person re-identification alike.
To have only one hyperparameter: use Cutout. The only value to tune is the side length of the square. In torchvision, fixing scale and ratio of RandomErasing gives a similar transformation.
To also use the pixels of the removed area for learning: use CutMix. It pastes another image into the removed area and mixes the labels by area ratio, so no pixels are wasted.
To remove regions inside the network rather than in the input: use DropBlock.
Random Erasing can also be combined with augmentation methods that select transformations, such as RandAugment.
PyTorch example
โถShow code
python
import random
import math
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 Random Erasing)
"""
# Hyperparameters
batch_size = 128 # batch size
epochs = 5 # number of epochs
learning_rate = 1e-3 # learning rate
# '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'
class RandomErasingPaper:
# Implementation following the paper's Algorithm 1. Place after ToTensor (values 0-1) and before Normalize
def __init__(self, p=0.5, sl=0.02, sh=0.4, r1=0.3):
self.p, self.sl, self.sh = p, sl, sh
self.r1, self.r2 = r1, 1 / r1 # aspect ratio range (the paper uses r2 = 1 / r1)
def __call__(self, img): # img: tensor of shape [C, H, W] (values 0-1)
if random.uniform(0, 1) >= self.p: # return unchanged with probability 1 - p
return img
_, H, W = img.shape
S = H * W
while True: # re-choose until an in-bounds rectangle is found
Se = random.uniform(self.sl, self.sh) * S # area
re = random.uniform(self.r1, self.r2) # aspect ratio (height / width)
He, We = int(round(math.sqrt(Se * re))), int(round(math.sqrt(Se / re)))
xe, ye = random.randint(0, W - 1), random.randint(0, H - 1) # top-left point
if He >= 1 and We >= 1 and xe + We <= W and ye + He <= H:
img = img.clone()
img[:, ye:ye + He, xe:xe + We] = torch.rand(img.size(0), He, We) # random value per pixel (0-255 scaled to 0-1)
return img # label stays unchanged
mean, std = (0.4914, 0.4822, 0.4465), (0.2470, 0.2435, 0.2616)
train_transform = transforms.Compose([
transforms.RandomCrop(32, padding=4), # combine with standard augmentation (crop, horizontal flip)
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
RandomErasingPaper(p=0.5, sl=0.02, sh=0.4, r1=0.3), # paper's image classification setting
transforms.Normalize(mean, std),
# When using torchvision's RandomErasing (place after Normalize):
# transforms.RandomErasing(p=0.5, scale=(0.02, 0.4), ratio=(0.3, 3.3), value='random'),
# p: probability of applying (default 0.5)
# scale: range of erased area as a fraction of image area (default (0.02, 0.33); the paper uses up to 0.4 for classification)
# ratio: aspect ratio range (default (0.3, 3.3); sampled uniformly on a log scale)
# value: fill value (default 0; 'random' for standard normal noise, 3 values for a per-channel color)
# if no in-bounds rectangle is found in 10 tries, returns the original image
])
test_transform = transforms.Compose([ # no Random Erasing 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: Random Erasing is applied while loading data. Labels are used as is
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. Is Random Erasing also applied at test or inference time?
A.
No. Random Erasing is used only during training; for evaluation and inference the original image is fed as is. Unlike dropout, there is also no need to rescale outputs at test time.
Q. Should the erased area be filled with random values or with 0?
A.
In the paper's CIFAR-10 experiments, per-pixel random values (error rate 4.31%) and the ImageNet mean color (4.35%) were nearly the same and better than black (4.62%) or white (4.85%). torchvision's default is value=0, so placing it after Normalize fills with the mean color, which is close to the paper's mean-color setting.
Q. Which should be used, Random Erasing or Cutout?
A.
Both are augmentations that "hide part of the image," and the main difference is how they are tuned. Cutout only needs the side length of a square, while Random Erasing takes ranges for area and aspect ratio and hides a different shape each time. To use the same method for object detection and person re-identification as well, Random Erasing, whose effect is verified in the paper, is the easy choice.