CutMix is a data augmentation method that replaces a rectangular region of a training image with the same region of another image and mixes the ground-truth labels in proportion to the pasted area. It was proposed by Yun et al. in 2019 and presented at ICCV 2019.
For example, the top-right quarter of a "dog" image is replaced with the top-right quarter of a "cat" image, and the label becomes "dog 0.75, cat 0.25." The model learns to recognize the two objects in one image, each from only part of it.
CutMix was designed to make up for the weaknesses of two closely related methods.
Cutout fills a region with 0, so the pixels in that region are not used for training and that information is wasted.
Mixup adds two images pixel by pixel, producing unnatural, semi-transparent overlays.
CutMix puts real pixels from another image where pixels were removed, so no pixels are wasted and training proceeds on images that remain locally natural.
In equations:
x~=M⊙xA+(1−M)⊙xB,y~=λyA+(1−λ)yB
Here, (xA,yA) and (xB,yB) are two training samples, y is a one-hot vector with 1 only for the correct class, M is a mask that is 0 inside the box and 1 outside, and ⊙ is element-wise multiplication. λ is the fraction of the area where xA remains, and the labels are mixed in this ratio.
Checking the label mixing on the example in the diagram at the top (the box covers 1/4 of the image, λ=0.75) gives the following.
Class A (circle)
Class B (triangle)
yA (label of the circle image)
1
0
yB (label of the triangle image)
0
1
y~=0.75yA+0.25yB
0.75
0.25
Training procedure
One training step (one mini-batch) proceeds as follows (left side of the diagram at the top).
Load a mini-batch (images x and labels y).
Randomly shuffle the order of the mini-batch, and pair each original image (A) with the image at the same index after shuffling (B).
Draw one mixing ratio λ from a Beta distribution Beta(α,α). The paper uses α=1, i.e., a uniform distribution on 0 to 1, in all experiments.
Decide the center and size of the box to paste. With image width W and height H:
rx∼Unif(0,W),ry∼Unif(0,H),rw=W1−λ,rh=H1−λ
- The box has the same aspect ratio as the original image, and its area is $1 - \lambda$ times that of the image.
5. Clip the part of the box that sticks out of the image, and recompute λ from the actual box area (λ=1−WHbox area).
6. Replace the inside of the box in A with the pixels at the same location in B, and mix the labels with λ (the equation above).
7. Pass the pasted image through the model, use the cross-entropy between the prediction and y~ as the loss, and update the weights.
As with Mixup, the loss in step 7 equals the λ-weighted sum of the losses for the two labels.
ℓ(f(x~),y~)=λℓ(f(x~),yA)+(1−λ)ℓ(f(x~),yB)
Pasting is done only during training. At evaluation and inference time, the original images are fed to the model as is. The only extra computation is the shuffle and the pixel copy, so training time hardly increases.
λ is recomputed in step 5 so that the label ratio matches the fraction of the area actually visible in the image. When the box sticks out of the edge as on the right of the diagram at the top, the replaced area is smaller than the initially chosen 1−λ (in the example, λ changes from 0.75 to 0.82).
Why it works
The paper summarizes the differences among CutMix, Cutout, and Mixup from the following three perspectives.
Removes part of the image so the model attends to other parts
×
○
○
Mixes images and labels
○
×
○
The model learns to recognize objects from only part of them: Because the box hides part of an object, the model, as with Cutout, learns to use not only the most salient part (such as the face) but also less salient parts such as the body as cues.
No pixels are wasted: The hidden region is filled with real pixels from another image, and that class's label is attached in proportion, so this region is also used for training.
It becomes easier to capture what is where: When the paper draws CAM (the attention region for each class), CutMix attends to the correct location in the image for each of the two classes. With Mixup, the unnatural overlays seemed to confuse the model about which class's cues to use.
In the paper's learning curves, with standard training the validation error began to rise after epoch 150, when the learning rate was lowered (overfitting). With CutMix, the validation error kept decreasing after that.
Results reported in the paper
The results of comparing CutMix with other regularizers on ImageNet classification (ResNet-50, 300 epochs, top-1 error) are as follows.
On CIFAR-100 (PyramidNet-200, top-1 error), compared with 16.45% for standard training, Cutout gave 16.53%, Mixup (α=1) 15.63%, and CutMix 14.47%. Combining CutMix with ShakeDrop gave 13.81%. On CIFAR-10, the error also dropped from 3.85% to 2.88%.
The following effects were also reported on tasks other than classification.
Task (ResNet-50)
Standard
Mixup
Cutout
CutMix
Weakly supervised object localization on ImageNet (accuracy %)
Mixup and Cutout sometimes got worse at object localization or when transferred to object detection, even though they improved ImageNet classification. CutMix improved every task. In addition, in an experiment detecting "images of kinds not in the training data" with models trained on CIFAR-100 (AUROC), Mixup dropped to 49.3% and Cutout to 68.7% compared with 87.3% for standard training, while CutMix rose to 94.4%.
Choosing settings (the paper's ablations)
The paper compares different CutMix settings on CIFAR-100 (PyramidNet-200).
α: Any of 0.1, 0.25, 0.5, 1.0, 2.0, and 4.0 lowered the error compared with standard training, and α=1 gave the best result.
Where to mix: Mixing in the feature maps of intermediate layers instead of the input images (Feature CutMix) was also tried, and mixing in the input images gave the best result.
Variants that changed part of the procedure all had higher error than the original CutMix (top-1 error; original CutMix is 14.47%).
What was changed
Variant
Error (%)
Box position
Choose the center from a normal distribution centered on the image center
15.95
Box size
Fix it to 16 × 16 (λ=0.75)
14.97
Labeling
Assign only the label of the larger area (one-hot)
15.89
Labeling
Always mix 0.5 each regardless of area
15.17
Application probability
Increase from 0 to 1 as training progresses
14.72
Mixing labels by area ratio matters. The variants that assign only the larger area's label or always split half and half gave smaller improvements.
Practical notes
Train for longer. The paper found that regularizers such as Cutout, Mixup, and CutMix require more epochs to converge, so all ImageNet models were trained for 300 epochs.
Apply it per mini-batch. Because the partner image is chosen from within the mini-batch, apply it after per-image augmentations (cropping, flipping, and so on), once the mini-batch has been formed.
Labels become probabilities (soft labels). Use a cross-entropy loss that accepts probability labels. PyTorch's nn.CrossEntropyLoss accepts probability labels of shape (batch, classes) directly.
When using torchvision's transforms.v2.CutMix, keep the following in mind.
Apply it to mini-batches (4D tensors). It cannot be used on a single image or a PIL image. Apply it after the data loader.
If the labels are class indices of shape (batch,), always pass num_classes. The output labels are probabilities of shape (batch, num_classes).
The partner is the neighboring image in the mini-batch (the order shifted by one). Set shuffle=True in the data loader.
There is no argument for the application probability (it is applied every time). To alternate with Mixup, use v2.RandomChoice([v2.CutMix(...), v2.MixUp(...)]).
It does not support bounding boxes or segmentation masks. For tasks whose targets have locations, you need to decide separately how to build the targets for mixed images.
Comparison with similar augmentations and how to choose
The table below compares CutMix with methods it is often compared with, from the same angles.
Method
How the input is built
How the label is built
Suitable use
CutMix
Replace a rectangle in one image with the same region of another image
Mix by pasted area ratio
Image classification; pretraining for tasks where object location matters
You want the best accuracy in image classification: Use CutMix. In the paper's ImageNet and CIFAR comparisons, it outperformed Cutout and Mixup.
You want to transfer the trained model to object detection and similar tasks: Use CutMix. In the paper, pretraining with Mixup or Cutout sometimes lowered object detection accuracy, while CutMix raised it.
Non-image data: Use Mixup. CutMix "pastes a rectangular region," so it assumes inputs where position is meaningful, as in images.
You cannot decide between Mixup and CutMix: You can also randomly choose one of them for each mini-batch (v2.RandomChoice above).
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
from torchvision.transforms import v2
from torch.utils.data import DataLoader
'''
CIFAR-10 image classification (trained with CutMix)
'''
# Hyperparameters
batch_size = 128 # Batch size
epochs = 5 # Number of epochs
learning_rate = 1e-3 # Learning rate
alpha = 1.0 # α of Beta(α, α) (1 in all of the paper's experiments)
num_classes = 10
# 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 = v2.Compose([ # Per-image augmentation (CutMix does not go here)
v2.RandomCrop(32, padding=4),
v2.RandomHorizontalFlip(),
v2.ToImage(),
v2.ToDtype(torch.float32, scale=True),
v2.Normalize(mean, std),
])
test_transform = v2.Compose([v2.ToImage(), v2.ToDtype(torch.float32, scale=True), v2.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) # The partner is the neighboring image, so shuffle the order
test_loader = DataLoader(test_dataset, batch_size=batch_size)
# torchvision's CutMix: applied to mini-batches. num_classes is required for class-index labels
# Output labels are probabilities of shape (batch, num_classes). There is no application-probability argument (always applied)
cutmix = v2.CutMix(alpha=alpha, num_classes=num_classes)
# To use it half and half with Mixup: mix = v2.RandomChoice([v2.CutMix(num_classes=num_classes), v2.MixUp(num_classes=num_classes)])
def cutmix_manual(x, y, alpha):
# Same processing as Algorithm A1 in the paper (for reference). y is class indices
lam = float(np.random.beta(alpha, alpha))
index = torch.randperm(x.size(0), device=x.device) # Shuffle to choose partners
H, W = x.size(2), x.size(3)
rx, ry = np.random.randint(W), np.random.randint(H) # Box center is uniform
rw, rh = int(W * np.sqrt(1 - lam)), int(H * np.sqrt(1 - lam)) # Area is 1 - λ
x1, x2 = np.clip(rx - rw // 2, 0, W), np.clip(rx + rw // 2, 0, W)
y1, y2 = np.clip(ry - rh // 2, 0, H), np.clip(ry + rh // 2, 0, H)
x = x.clone()
x[:, :, y1:y2, x1:x2] = x[index, :, y1:y2, x1:x2] # Replace the inside of the box with the partner image
lam = 1 - (x2 - x1) * (y2 - y1) / (W * H) # Correct λ with the actual area, excluding the part outside
return x, y, y[index], lam # Loss is lam * CE(out, y) + (1 - lam) * CE(out, y[index])
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(num_classes).to(device)
criterion = nn.CrossEntropyLoss() # Also accepts probability labels of shape (B, num_classes) directly
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training: apply CutMix after forming the mini-batch
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
images, labels = cutmix(images, labels) # labels: (B,) -> probabilities of shape (B, num_classes)
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 without pasting
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 CutMix also applied at test or inference time?
A.
No. CutMix is used only during training; at evaluation and inference time, the original images are fed to the model as is.
Q. Should I use Mixup or CutMix?
A.
For image classification, CutMix had lower error in the paper's comparisons and was also advantageous when transferred to object detection. For non-image data (audio, tabular), position has no meaning, so use Mixup. You can also switch randomly between the two for each mini-batch.
Q. Can I skip mixing labels and assign only the label of the larger pasted area?
A.
In the paper's ablation (CIFAR-100), assigning only the larger area's label raised the error from 14.47% to 15.89%. Mix the labels by λ, the fraction of the area visible in the image.