Sub topic 10
Mixing Samples: Mixup and CutMix
This chapter assumes basic Python, image tensors, classification labels, and a PyTorch training loop. Mixup and CutMix are sample-mixing methods. They regularize a model by training it on combinations of examples instead of only on individual images.
Why mix training samples?
A classifier can memorize small details in the training set. Mixing examples makes the training task harder and encourages smoother decision boundaries.
Both methods require two training examples, usually selected by shuffling a batch:
- Mixup blends the pixel values of two images.
- CutMix replaces a rectangle in one image with a rectangle from another.
- Both methods combine the corresponding labels.
The labels become weighted targets. If an image is 70% from class A and 30% from class B, the loss uses those same weights.
Mixup
Mixup uses a coefficient lambda between zero and one:
mixed_image = lambda * image_A + (1 - lambda) * image_B
The coefficient usually comes from a Beta distribution. The alpha parameter controls how strongly examples are mixed. A small value produces many examples close to one original image. A larger value creates more balanced blends.
import torch
import torch.nn.functional as F
def mixup_step(model, x, y, alpha=0.2):
if alpha <= 0:
return F.cross_entropy(model(x), y)
lam = torch.distributions.Beta(alpha, alpha).sample().item()
permutation = torch.randperm(x.size(0), device=x.device)
mixed_x = lam * x + (1 - lam) * x[permutation]
logits = model(mixed_x)
loss_a = F.cross_entropy(logits, y)
loss_b = F.cross_entropy(logits, y[permutation])
return lam * loss_a + (1 - lam) * loss_bMixup can create ghost-like images. This is expected for classification, where the model learns the relationship between image content and class probability. It is less suitable when blending produces unrealistic training examples.
CutMix
CutMix copies a rectangular region from one image into another. The label weight is based on the fraction of pixels that remain from each source. If the pasted rectangle covers 25% of the image, the original label receives weight 0.75 and the pasted label receives weight 0.25.
Unlike Mixup, CutMix keeps most pixels unchanged. It can teach the model to use multiple parts of an object and can reduce reliance on one highly predictive patch.
| Method | Image operation | Label weighting |
|---|---|---|
| Mixup | Blend every pixel | Blend coefficient |
| CutMix | Paste one rectangular region | Visible pixel area |
A basic CutMix implementation looks like this:
import torch
def cutmix_batch(x, y, alpha=1.0):
batch_size, _, height, width = x.shape
permutation = torch.randperm(batch_size, device=x.device)
lam = torch.distributions.Beta(alpha, alpha).sample().item()
cut_ratio = (1.0 - lam) ** 0.5
cut_w = int(width * cut_ratio)
cut_h = int(height * cut_ratio)
cx = torch.randint(width, (1,), device=x.device).item()
cy = torch.randint(height, (1,), device=x.device).item()
x1 = max(cx - cut_w // 2, 0)
y1 = max(cy - cut_h // 2, 0)
x2 = min(cx + cut_w // 2, width)
y2 = min(cy + cut_h // 2, height)
x_mixed = x.clone()
x_mixed[:, :, y1:y2, x1:x2] = x[permutation, :, y1:y2, x1:x2]
pasted_area = (x2 - x1) * (y2 - y1)
lam_actual = 1.0 - pasted_area / (width * height)
return x_mixed, y, y[permutation], lam_actualUse the returned lam_actual when calculating the two cross-entropy losses. The actual rectangle can be clipped by image borders, so the requested lam may differ from the correct area ratio.
Tuning and common errors
Start with Mixup alpha=0.2 or CutMix alpha=1.0. Compare validation accuracy with a baseline that uses ordinary augmentation. Excessive mixing can make images unrealistic and cause underfitting.
Do not mix images while leaving one original label unchanged. Do not use the requested Mixup coefficient after CutMix clips the rectangle. For multilabel tasks, detection, or segmentation, label handling needs a task-specific design.
Exercise
A CutMix rectangle covers 40% of the image. What weights should the two classification losses receive?
Show answer
The original image receives 0.60, and the pasted image receives 0.40.