Sub topic 7
Occlusion Transforms: Random Erasing and Cutout
This chapter assumes you know basic Python, can treat an image as an array of shape (height, width, channels), and have trained a classifier in PyTorch. You should also know what overfitting is and why we keep a separate validation set.
What occlusion transforms do
An occlusion transform hides a rectangular patch of the image. The patch is filled with a constant, noise, or the dataset mean. The label does not change.
The goal is to simulate real occlusion: a hand covering part of a face, a fence in front of an animal, a truncated object at the frame edge. It also pushes the model to use several cues instead of one. If a network learns to classify dogs only from the head, erasing the head forces it to look at the fur, the legs, and the context as well.
Two names appear in the literature, and they are close relatives:
- Cutout (DeVries and Taylor, 2017) masks a fixed-size square at a random center. The center may lie near the border, so the square can be partly clipped by the image edge.
- Random Erasing (Zhong et al., 2017) picks a random area fraction and aspect ratio for the rectangle, fills it with random values or the mean, and applies it with some probability.
In practice, Random Erasing is the more general version, and torchvision implements it as RandomErasing.
Using RandomErasing in torchvision
RandomErasing operates on tensors, not PIL images. That has one consequence for ordering: it must come after ToTensor. It is usually placed after Normalize as well, which affects what the fill value means (see below).
import torch
from torchvision import transforms
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
train_tf = transforms.Compose([
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean, std),
transforms.RandomErasing(
p=0.5,
scale=(0.02, 0.25),
ratio=(0.3, 3.3),
value=0,
),
])
x = torch.rand(3, 256, 256)
from PIL import Image
import numpy as np
img = Image.fromarray((x.permute(1, 2, 0).numpy() * 255).astype(np.uint8))
out = train_tf(img)
print(out.shape)The parameters are:
| Parameter | Meaning | Default |
|---|---|---|
| `p` | Probability that any erasing happens | 0.5 |
| `scale` | Range of the erased area as a fraction of the image area | (0.02, 0.33) |
| `ratio` | Range of the rectangle's aspect ratio (width / height) | (0.3, 3.3) |
| `value` | Fill: a number, a per-channel tuple, or the string `"random"` | 0 |
| `inplace` | Modify the tensor in place instead of copying | False |
Choosing the fill value
The fill value matters more than it looks.
value=0afterNormalize: zero in normalized space equals the dataset mean color in pixel space. This is a neutral fill, and it is the usual choice when erasing comes last.value=0beforeNormalize: zero is black in pixel space. After normalization it becomes a strongly negative value, a conspicuous patch the network can learn to recognize as "an erased region."value="random": each erased pixel gets noise drawn from a normal distribution. This removes the information but leaves texture-like noise.- A per-channel tuple: lets you fill with a chosen color, such as the mean in pixel space.
Writing Cutout by hand
Cutout differs from Random Erasing in two ways. The square has a fixed side length, and its center is sampled anywhere in the image, so patches near the border are clipped. This keeps the expected erased area slightly below the nominal one. Here is a minimal NumPy version for an (H, W, C) image:
import numpy as np
rng = np.random.default_rng(0)
def cutout(image, size=64, fill=0):
h, w = image.shape[:2]
cy = rng.integers(0, h)
cx = rng.integers(0, w)
y1 = max(cy - size // 2, 0)
y2 = min(cy + size // 2, h)
x1 = max(cx - size // 2, 0)
x2 = min(cx + size // 2, w)
out = image.copy()
out[y1:y2, x1:x2] = fill
return out
img = np.full((224, 224, 3), 200, dtype=np.uint8)
aug = cutout(img, size=64)
print((aug == 0).any(axis=2).sum())Note the copy(). Without it you would modify the caller's array, which in a dataset that caches decoded images would corrupt every later epoch.
Choosing the size and probability
Occlusion is a stronger transform than a small color shift, so its settings need care.
- Match object scale. On CIFAR-10 (32×32 images) the original Cutout paper used a 16×16 square, which hides a quarter of the image. On 224×224 ImageNet crops, erasing a similar fraction would often remove the entire object. A
scaleupper bound of 0.2 to 0.33 is a common starting range. - Keep
pmoderate. Values around 0.25 to 0.5 mean most images are untouched, so the network still sees clean examples. - Watch small objects. For an object that fills 5 percent of the frame, a patch of 10 percent area can erase it completely. The image is then labeled "cat" and contains no cat. This is label noise, and it hurts more as the object gets smaller.
- Consider the dataset's occlusion rate. If test images rarely show occlusion, heavy erasing spends model capacity on a condition that never occurs.
Interaction with other transforms
Occlusion composes with the geometric and photometric transforms from earlier chapters, but order and combination matter.
- After geometric transforms. Crop and flip first so the patch lands in the final-sized image. If you erase and then crop, the crop may discard the patch.
- With RandAugment.
RandAugmentworks on PIL images or uint8 tensors, so it runs beforeToTensor.RandomErasingruns after. The two are commonly used together in modern recipes. - With mixing methods. Cutout and CutMix both paste rectangles, but CutMix fills the box with a patch from another image and mixes the labels in proportion to area. Cutout fills with a constant and keeps the label whole. Using strong erasing and CutMix at once can leave too little of the original image.
Batch-level erasing and boxes
RandomErasing applied inside a dataset transform draws one patch per sample. That is usually what you want. Be aware of two cases:
- Batched tensors. If you call it on a tensor of shape
(N, C, H, W), the same patch is used for every image in the batch in some versions and settings. Apply it per sample, in the dataset, to get independent patches. - Detection and segmentation. Erasing changes pixels only. A bounding box or mask still claims an object is there. For detection, a box that is fully erased becomes a label with no visible evidence. Either keep patches small, drop boxes whose visible fraction falls below a threshold, or accept the noise knowingly. Masks are not erased by default, which is usually the intended behavior: the model should still predict the hidden region from context.
Inspecting the result
Always look at samples before training. Erasing bugs are visible at a glance, such as patches that cover everything, black rectangles from a wrong fill order, or patches that never appear.
import torch
from torchvision import transforms
torch.manual_seed(0)
erase = transforms.RandomErasing(p=1.0, scale=(0.05, 0.2), value=0)
x = torch.ones(3, 64, 64)
fractions = []
for _ in range(1000):
y = erase(x.clone())
fractions.append((y == 0).float().mean().item())
print(min(fractions), max(fractions))With p=1.0 every sample is erased, and the printed range should sit inside the scale bounds you set. A maximum well above your upper bound, or a minimum of zero, points to a configuration or ordering error. The scale bound is approximate when the sampled rectangle is clipped to fit, so expect small deviations at the edges.
Common errors
- Placing
RandomErasingbeforeToTensor, which raises a type error because it expects a tensor. - Erasing before normalization and then assuming the fill is the mean color.
- Applying it in the validation pipeline. Evaluation transforms must be deterministic, so leave occlusion out of them.
- Using a large
scaleon small-object tasks and training on labels with no visible object. - Forgetting
clone()orcopy()when testing by hand, so repeated runs erase the same tensor cumulatively.
Exercise
You train a classifier on 224×224 images where the target object usually fills about 10 percent of the frame. You set RandomErasing with p=0.5 and scale=(0.1, 0.4) and put it before Normalize with value=0. Validation accuracy drops compared with no erasing. Name two problems with this setup and give a fix for each.
Show answer
First, the scale is too large for the object size. A patch of 10 to 40 percent of the image can cover the whole object, which leaves a label with no visible evidence. Lower the upper bound (for example scale=(0.02, 0.1)) and consider a lower p. Second, the erasing comes before Normalize, so value=0 is black in pixel space and becomes a strongly negative, easily recognized value after normalization. Move RandomErasing after Normalize so that 0 equals the dataset mean, or set a per-channel mean fill. Also confirm the transform is not in the validation pipeline.
Exercise
What are the two main differences between Cutout and Random Erasing?
Show answer
Cutout uses a fixed-size square whose center is sampled anywhere in the image (so border patches get clipped) and always fills with a constant. Random Erasing samples a random area fraction and aspect ratio, applies the erasure only with probability p, and can fill with a constant, per-channel values, or random noise.