Mixup is a data augmentation method that picks two examples from the training data and trains on an "intermediate example" created by mixing their inputs and their labels in the same proportion. It was proposed by Zhang et al. in 2017 and presented at ICLR 2018.
For example, a "cat" image and a "dog" image are added pixel by pixel at 70% and 30%, and the label becomes "cat 0.7, dog 0.3" as well. Because the model learns to "answer mixed images with confidence matching the mixing ratio," its predictions change smoothly even between training examples.
In equations:
x~=λxi+(1−λ)xj,y~=λyi+(1−λ)yj,λ∼Beta(α,α)
Here, (xi,yi) and (xj,yj) are two examples chosen at random from the training data, y is a one-hot vector with 1 only for the correct class, and λ is the mixing ratio in 0 to 1. λ is redrawn from a Beta distribution Beta(α,α) at every training step. α is a hyperparameter set by hand.
Checking the label mixing on the example in the diagram at the top (λ=0.7) gives the following.
Class A (circle)
Class B (triangle)
yi (label of the circle image)
1
0
yj (label of the triangle image)
0
1
y~=0.7yi+0.3yj
0.7
0.3
Conventional data augmentations such as rotation and flipping required a person to decide, for each kind of data, "which changes keep the same class." Mixup needs only addition, so it can be used in the same way on any data whose inputs can be represented as vectors, such as images, audio, and tabular data.
Training procedure
One training step (one mini-batch) proceeds as follows.
Load a mini-batch (inputs x and labels y).
Randomly shuffle the order of the mini-batch, and pair the original i-th example with the i-th example after shuffling (j).
Instead of preparing two data loaders, the paper's implementation also forms pairs by shuffling a single mini-batch. This adds no loading overhead and is reported to work equally well.
Draw one mixing ratio λ from Beta(α,α).
Mix the inputs and labels with the same λ (the equations above).
Pass the mixed input x~ through the model, use the cross-entropy between the prediction and y~ as the loss, and update the weights.
The loss in step 5 equals the λ-weighted sum of the losses for each ground-truth label.
ℓ(f(x~),y~)=λℓ(f(x~),yi)+(1−λ)ℓ(f(x~),yj)
Here, f(x~) is the model's prediction and ℓ is cross-entropy. Because cross-entropy is linear in the ground-truth label, the two are equal. Implementations often compute the right-hand side without building one-hot vectors (the implementation example below also uses this form).
Mixing is done only during training. At evaluation and inference time, the original inputs are fed to the model as is. The only extra computation is addition and shuffling, so training time hardly increases.
It is important to mix the labels as well as the inputs. In the paper's ablation experiments (CIFAR-10, PreAct ResNet-18), mixing only the inputs and using the label of the example with the larger mixing ratio, or mixing only examples of the same class, did not improve results as much as Mixup, which also mixes the labels.
Choosing the mixing strength α
α determines how likely λ is to take values close to 0.5, that is, how strongly to mix.
α
Shape of the λ distribution
Mixing
Close to 0
Mostly near 0 or 1
Almost no mixing (as α→0, it becomes standard training)
All ratios equally likely (the paper's CIFAR setting)
Greater than 1
Concentrated near 0.5
Strong mixing
The bottom right of the diagram at the top shows the distribution of λ for α=0.2 and α=1. With α=0.2, most values of λ are near 0 or 1, so most examples become "an image with a little of the other mixed in."
The paper reports that on ImageNet, setting α to 0.1 to 0.4 lowered the error compared with standard training, and that making α too large makes the model fail to fit the training data (underfitting). The values used were α=0.2 for ResNet-50 and ResNet-101, α=0.4 for ResNeXt-101, and α=1 for CIFAR-10 and CIFAR-100.
Because Mixup acts as a regularizer, the strength of other regularizers needs to be readjusted. In the paper's ablation experiments, standard training worked best with stronger weight decay (5×10−4), while Mixup worked best with weaker weight decay (10−4). The effect is also small with short training or small models; in the paper's ImageNet experiments, the improvement was larger for bigger models and longer training.
Why it works and results reported in the paper
Mixup encourages the model to behave linearly between training examples. Because the model learns to predict 7:3 for an input mixing two examples at 7:3, its predictions are less likely to change abruptly or show unfounded high confidence in regions without data. The paper explains that this linear behavior reduces undesirable oscillations in predictions outside the training data.
The main effects reported in the paper are as follows.
Better generalization: The CIFAR-10 error with PreAct ResNet-18 dropped from 5.6% to 4.2%, and CIFAR-100 from 25.6% to 21.1%. On ImageNet, the top-1 error of ResNet-50 trained for 200 epochs dropped from 23.6% to 22.1%.
Robustness to label errors: In experiments where some CIFAR-10 labels were randomly swapped, the model was less prone to memorizing incorrect labels and achieved lower error than dropout (combining the two improved results further).
Robustness to adversarial examples: Feeding adversarial examples created with FGSM to ResNet-101 on ImageNet gave a top-1 error of 90.7% with standard training and 75.2% with Mixup. Against an iterative attack (I-FGSM), however, both were wrong almost 100% of the time.
Effects beyond images: In speech command recognition (mixing spectrograms), the error dropped for a larger model (VGG-11) (it rose slightly for the small LeNet). On tabular data, the error dropped on 4 of 6 datasets, and Mixup was also shown to stabilize GAN training.
In addition, models trained with Mixup have been reported to have predicted confidence closer to their actual accuracy (better calibration) (Thulasidasan et al., 2019).
Comparison with similar augmentations and how to choose
The table below compares Mixup with methods it is often compared with, from the same angles.
Make the correct label slightly less than 1 and spread the rest over other classes
Classification in general (Transformer and others)
Rough guidelines for choosing are as follows.
You want something easy to try first, regardless of data type: Use Mixup. It needs only addition, so it works on non-image data as is.
For images, you want to keep cues about object shape and position: Use CutMix. Images mixed by Mixup are unnatural, semi-transparent overlays of two images, whereas CutMix keeps the pixels of the pasted region intact.
You only want the label-softening effect: Use Label Smoothing. In the ablation experiments of the Mixup paper, Mixup had lower error than mixing inputs and applying Label Smoothing to the labels.
It is not suited to tasks where mixed inputs are meaningless. For example, adding two sentences as word indices does not produce a meaningful input, so for text, techniques that mix embedding vectors or intermediate features are used. Also, for tasks whose targets have locations, such as object detection and segmentation, you need to decide separately how to build the targets for mixed images.
PyTorch example
▶Show code
python
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
# Example of mixing inputs and labels (λ = 0.7, as in the diagram at the top)
lam = 0.7
y_i = F.one_hot(torch.tensor(0), num_classes=2).float() # Class A: [1, 0]
y_j = F.one_hot(torch.tensor(1), num_classes=2).float() # Class B: [0, 1]
print(lam * y_i + (1 - lam) * y_j) # tensor([0.7000, 0.3000])
'''
Image classification task on MNIST data (trained with Mixup)
'''
# Hyperparameters
batch_size = 64 # Batch size
epochs = 5 # Number of epochs
learning_rate = 1e-3 # Learning rate
alpha = 0.2 # α of Beta(α, α). Larger means stronger mixing
# 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'
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize((0.1307,), (0.3081,))
])
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
test_dataset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=batch_size)
def mixup(x, y, alpha):
# Shuffle the mini-batch to choose partners, and mix inputs with the same λ
lam = float(np.random.beta(alpha, alpha))
index = torch.randperm(x.size(0), device=x.device)
mixed_x = lam * x + (1 - lam) * x[index]
return mixed_x, y, y[index], lam
class SmallCNN(nn.Module):
def __init__(self, num_classes=10):
super().__init__()
self.features = nn.Sequential(
nn.Conv2d(1, 32, kernel_size=3, padding=1), # [B, 1, 28, 28] -> [B, 32, 28, 28]
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 32, 14, 14]
nn.Conv2d(32, 64, kernel_size=3, padding=1), # -> [B, 64, 14, 14]
nn.ReLU(),
nn.MaxPool2d(2), # -> [B, 64, 7, 7]
nn.Flatten(),
)
self.classifier = nn.Linear(64 * 7 * 7, num_classes)
def forward(self, x):
return self.classifier(self.features(x))
model = SmallCNN().to(device)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
# Training: predict on mixed inputs and add the losses for the two labels weighted by λ
for epoch in range(epochs):
model.train()
for images, labels in train_loader:
images, labels = images.to(device), labels.to(device)
mixed, y_a, y_b, lam = mixup(images, labels, alpha)
outputs = model(mixed)
loss = lam * criterion(outputs, y_a) + (1 - lam) * criterion(outputs, y_b)
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Evaluation: check on the original images without mixing
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. Are inputs also mixed at test or inference time?
A.
No. Mixup is used only during training; at evaluation and inference time, the original inputs are fed to the model as is.
Q. Does mixing examples of the same class help?
A.
In the paper's ablation experiments, mixing only examples of the same class did not improve results as much as Mixup. It is important to form pairs at random, including examples of different classes, and to mix the labels too.
Q. What value of α should I start with?
A.
The paper uses 0.2 to 0.4 for ImageNet and 1 for CIFAR. Larger values mix more strongly, but values that are too large keep the model from fitting the training data, so start around 0.2 and adjust based on validation results.