Sub topic 3
Mixing samples: mixup and CutMix
This chapter assumes you can write a PyTorch training loop, that you know images are arrays shaped (height, width, channels), and that you understand the train, validation, and test split. It covers sample-mixing methods, automated policies, paired targets, tuning, and common errors.
Mixing samples: mixup and CutMix
Mixing methods create new training examples by combining two images and their labels. Mixup blends whole images. CutMix pastes a rectangular patch from one image onto another.
mixup
Mixup draws a weight lam from a Beta distribution, blends each image with a shuffled partner from the batch, and weights the two losses by the same amount.
import numpy as np
import torch
import torch.nn.functional as F
def mixup_batch(x, y, alpha=0.2):
lam = float(np.random.beta(alpha, alpha))
idx = torch.randperm(x.size(0))
x_mixed = lam * x + (1 - lam) * x[idx]
return x_mixed, y, y[idx], lam
def mixup_loss(logits, y_a, y_b, lam):
return lam * F.cross_entropy(logits, y_a) + (1 - lam) * F.cross_entropy(logits, y_b)
x = torch.rand(8, 3, 32, 32)
y = torch.randint(0, 10, (8,))
x_m, y_a, y_b, lam = mixup_batch(x, y)
logits = torch.randn(8, 10, requires_grad=True)
loss = mixup_loss(logits, y_a, y_b, lam)
loss.backward()
print(x_m.shape, round(lam, 3), loss.item())CutMix
CutMix replaces a rectangle of one image with the matching rectangle from another. The label weight equals the fraction of pixels that came from each image, so the label stays proportional to the visible content. CutMix preserves local texture better than mixup, which can produce ghosted images.
Automated policies: AutoAugment, RandAugment, TrivialAugment
Automated policies choose transform sequences for you. AutoAugment searches for a policy on a dataset. RandAugment replaces that search with two settings: num_ops (operations per image) and magnitude (strength). TrivialAugment picks one operation at a random strength. RandAugment works on PIL images, so place it before ToTensor.
Augmenting masks and bounding boxes together with images
A mask or box must receive the same geometry as its image. Use one random draw for the flip or crop, and apply it to every target. Masks need nearest-neighbor interpolation so label IDs do not blend. Photometric changes such as color jitter apply to the image only.
Inspecting, validating, and tuning augmentation strength
Save a grid of augmented samples before training and check that labels remain recognizable. Then run controlled experiments: change one setting at a time, such as magnitude, and compare validation accuracy over several seeds. Keep the validation pipeline deterministic.
Common pitfalls and how to avoid them
- Label-changing transforms: A horizontal flip turns a left-hand sign into a right-hand one. Remove flips for such classes.
- Mixing where exact location matters: Mixup can hurt detection or segmentation. Use it only for classification.
- Mask misalignment: Transforming the image and mask with separate random draws misaligns labels.
- Leakage: Fitting augmentation statistics on the full dataset leaks validation information.
- Domain mismatch: Heavy color changes can hurt a model deployed on consistent lighting.
Exercise
A CutMix patch covers 25 percent of the image area. What label weight should the pasted image's class receive?
Show answer
0.25 for the pasted class and 0.75 for the original class, so the weights sum to 1.