Mix a batch with mixup
Why it matters Mixup and its relatives are standard regularisers for vision and audio classifiers.
Mixup (Zhang et al., 2018) trains on convex combinations of pairs of examples and their labels.
Write mixup(x, y_onehot, lam, perm). x is (n, ...), y_onehot is (n, k), lam is a float in [0, 1], perm is a permutation of range(n). Return (x_mix, y_mix) with x_mix = lam * x + (1 - lam) * x[perm] and y_mix = lam * y + (1 - lam) * y[perm].
def mixup(x, y_onehot, lam, perm)Example
x [[0], [10]], y [[1, 0], [0, 1]], lam 0.7, perm [1, 0] gives x [[3], [7]] and y [[0.7, 0.3], [0.3, 0.7]].
Understand the idea
Mixup is a data augmentation trick: blend two training examples and blend their labels by the same amount. If an image is 75 percent cat and 25 percent dog pixels, its label should be 75 percent cat and 25 percent dog. This smooths the model's decisions between classes and reduces overconfidence. Worked example: x = [[2], [6], [10]], one-hot labels for classes 0, 1, 2, lam 0.75, perm [2, 0, 1]. Row 0 mixes with row 2: x = 0.75 * 2 + 0.25 * 10 = 4, y = 0.75 * [1, 0, 0] + 0.25 * [0, 0, 1] = [0.75, 0, 0.25]. Row 1 mixes with row 0: x = 0.75 * 6 + 0.25 * 2 = 5. Row 2 mixes with row 1: x = 7.5 + 1.5 = 9. Rule: x_mix = lam * x + (1 - lam) * x[perm]; y_mix = lam * y + (1 - lam) * y[perm]. Use exactly the same lam and the same perm for inputs and labels. x can have any shape after the batch axis, so plain broadcasting works. Used in: image classification training recipes, and variants such as CutMix in vision models.