AI Logic

Data Augmentation

CutMix

Updated:

Diagram of CutMix. The left side shows one training step: shuffle the mini-batch, draw λ, decide the box position and size, replace the inside of the box with the partner image and mix the labels by area ratio, model, loss. The right side shows an example of pasting part of a triangle image (class B) onto a circle image (class A), comparing the label ratios when the box is inside the image (λ = 0.75) and when it sticks out of the edge so λ is corrected using the actual area (0.82)

What is CutMix?

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\tilde{x} = M \odot x_A + (1 - M) \odot x_B, \qquad \tilde{y} = \lambda\, y_A + (1 - \lambda)\, y_B

Here, (xA,yA)(x_A, y_A) and (xB,yB)(x_B, y_B) are two training samples, yy is a one-hot vector with 1 only for the correct class, MM is a mask that is 0 inside the box and 1 outside, and ⊙\odot is element-wise multiplication. λ\lambda is the fraction of the area where xAx_A 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\lambda = 0.75) gives the following.

Class A (circle)Class B (triangle)
yAy_A (label of the circle image)10
yBy_B (label of the triangle image)01
y~=0.75 yA+0.25 yB\tilde{y} = 0.75\, y_A + 0.25\, y_B0.750.25

Training procedure

One training step (one mini-batch) proceeds as follows (left side of the diagram at the top).

  1. Load a mini-batch (images xx and labels yy).
  2. Randomly shuffle the order of the mini-batch, and pair each original image (AA) with the image at the same index after shuffling (BB).
  3. Draw one mixing ratio λ\lambda from a Beta distribution Beta(α,α)\mathrm{Beta}(\alpha, \alpha). The paper uses α=1\alpha = 1, i.e., a uniform distribution on 0 to 1, in all experiments.
  4. Decide the center and size of the box to paste. With image width WW and height HH:
rx∼Unif(0,W),ry∼Unif(0,H),rw=W1−λ,rh=H1−λr_x \sim \mathrm{Unif}(0, W),\quad r_y \sim \mathrm{Unif}(0, H),\quad r_w = W\sqrt{1 - \lambda},\quad r_h = H\sqrt{1 - \lambda}
- 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 λ\lambda from the actual box area (λ=1−box areaWH\lambda = 1 - \frac{\text{box area}}{WH}). 6. Replace the inside of the box in AA with the pixels at the same location in BB, and mix the labels with λ\lambda (the equation above). 7. Pass the pasted image through the model, use the cross-entropy between the prediction and y~\tilde{y} as the loss, and update the weights.

As with Mixup, the loss in step 7 equals the λ\lambda-weighted sum of the losses for the two labels.

ℓ(f(x~), y~)=λ ℓ(f(x~), yA)+(1−λ) ℓ(f(x~), yB)\ell\big(f(\tilde{x}),\, \tilde{y}\big) = \lambda\, \ell\big(f(\tilde{x}),\, y_A\big) + (1 - \lambda)\, \ell\big(f(\tilde{x}),\, y_B\big)

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.

λ\lambda 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−λ1 - \lambda (in the example, λ\lambda 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.

PerspectiveMixupCutoutCutMix
Uses every pixel of the image for training○×○
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.

MethodTop-1 error (%)
ResNet-50 (baseline)23.68
+ Cutout (112 × 112)22.93
+ Stochastic Depth22.46
+ Mixup (α=1\alpha = 1)22.58
+ Manifold Mixup22.50
+ DropBlock (value from the original paper)21.87
+ CutMix21.40

On CIFAR-100 (PyramidNet-200, top-1 error), compared with 16.45% for standard training, Cutout gave 16.53%, Mixup (α=1\alpha = 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)StandardMixupCutoutCutMix
Weakly supervised object localization on ImageNet (accuracy %)46.3045.8446.6947.25
Pretraining → object detection with Faster R-CNN (Pascal VOC, mAP)75.673.975.076.7
Pretraining → image captioning (MS-COCO, BLEU-4)22.923.224.024.9
Top-1 accuracy under FGSM attack (%)8.224.411.531.0

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).

  • α\alpha: Any of 0.1, 0.25, 0.5, 1.0, 2.0, and 4.0 lowered the error compared with standard training, and α=1\alpha = 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 changedVariantError (%)
Box positionChoose the center from a normal distribution centered on the image center15.95
Box sizeFix it to 16 × 16 (λ=0.75\lambda = 0.75)14.97
LabelingAssign only the label of the larger area (one-hot)15.89
LabelingAlways mix 0.5 each regardless of area15.17
Application probabilityIncrease from 0 to 1 as training progresses14.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.

MethodHow the input is builtHow the label is builtSuitable use
CutMixReplace a rectangle in one image with the same region of another imageMix by pasted area ratioImage classification; pretraining for tasks where object location matters
CutoutFill a square in one image with 0UnchangedImage classification (simplest to implement)
MixupAdd two images pixel by pixel at λ:(1−λ)\lambda : (1-\lambda)Mix with λ\lambdaClassification, including non-image data (audio, tabular)
Manifold MixupMix features of intermediate layersMix with λ\lambdaWhen you want smoother feature representations
DropBlockDrop squares in intermediate feature mapsUnchangedRegularization inside convolutional networks

Rough guidelines for choosing are as follows.

  • 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 λ\lambda, the fraction of the area visible in the image.

References

  1. S. Yun, D. Han, S. J. Oh, S. Chun, J. Choe, and Y. Yoo, "CutMix: Regularization Strategy to Train Strong Classifiers with Localizable Features," ICCV, 2019.
  2. clovaai/CutMix-PyTorch (official implementation of the paper)
  3. T. DeVries and G. W. Taylor, "Improved Regularization of Convolutional Neural Networks with Cutout," arXiv:1708.04552, 2017.
  4. H. Zhang, M. Cisse, Y. N. Dauphin, and D. Lopez-Paz, "mixup: Beyond Empirical Risk Minimization," ICLR, 2018.
  5. PyTorch, torchvision.transforms.v2.CutMix