AI Wiki中文/EN

Mixup: interpolate the example and its target

Mixup

Fit soft targets from convexly mixed examples and test the assumption that labels should interpolate.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Overlay two training images. If one contributes a quarter of the pixels’ intensity and the other contributes three quarters, what should the target be? Mixup uses the same coefficients for the inputs and their target vectors. The result is a training constraint between examples, not a claim that the blended image belongs to one crisp class.

Zhang and colleagues introduce this construction through vicinal risk minimization: train on a specified neighborhood distribution around observed data. The neighborhood is defined by the augmentation rule. It is not independently verified ground truth. This distinction matters when blending creates an implausible input or when the true target varies nonlinearly between endpoints.

Definitions and derivation

Take two compatible input arrays and probability target vectors qᵢ,qⱼ. A coefficient in [0,1] forms convex combinations:

x~=λxi+(1−λ)xj,q~=λqi+(1−λ)qj,λ∼Beta⁡(α,α),α>0.\tilde x=\lambda x_i+(1-\lambda)x_j,\qquad \tilde q=\lambda q_i+(1-\lambda)q_j,\qquad \lambda\sim\operatorname{Beta}(\alpha,\alpha),\quad\alpha>0.

The symmetric beta distribution governs the strength of mixing. With α=1 it is uniform; small positive α concentrates near endpoints, while large α concentrates near the midpoint. The limiting endpoint behavior recovers ordinary examples, but α=0 is not a valid beta-distribution parameter. Pairing and whether one coefficient is shared by a batch are implementation choices.

For fixed predicted probabilities p=softmax(z), cross-entropy is linear in the target:

CE⁡(q~,p)=λCE⁡(qi,p)+(1−λ)CE⁡(qj,p),∇zCE⁡(q~,p)=p−q~.\operatorname{CE}(\tilde q,p)=\lambda\operatorname{CE}(q_i,p)+(1-\lambda)\operatorname{CE}(q_j,p),\qquad \nabla_z\operatorname{CE}(\tilde q,p)=p-\tilde q.

Both terms on the right must use predictions on the same mixed input. Averaging losses from separate predictions f(xᵢ) and f(xⱼ) is not the same operation. Taking argmax of the soft target also discards the intended proportions.

The training objective averages the loss over the chosen pair and coefficient distribution:

Rmix(θ)=Ei,j,λ ⁣[ℓ ⁣(fθ(λxi+(1−λ)xj),λqi+(1−λ)qj)].R_{\rm mix}(\theta)=\mathbb E_{i,j,\lambda}\!\left[ \ell\!\left(f_\theta(\lambda x_i+(1-\lambda)x_j),\lambda q_i+(1-\lambda)q_j\right)\right].

This expresses an inductive bias: predictions should behave compatibly with target interpolation along these input segments. It does not make the network globally linear. Unlike label smoothing, the soft target depends on another example, and the input changes too. Mixing two examples of the same class leaves their one-hot target unchanged.

Run the calculation

The complete Python 3.12 / NumPy 1.26.4 program fixes λ=0.25 and swaps two four-feature examples. It then trains a two-class linear softmax model on the mixed pair for 200 steps. Keeping this tiny augmented dataset fixed makes the calculation inspectable; it does not reproduce the paper’s random resampling at every training iteration.

import numpy as np


def mixup(x, targets, permutation, lam):
    x, q = np.asarray(x, dtype=float), np.asarray(targets, dtype=float)
    order = np.asarray(permutation)
    if x.ndim != 2 or q.ndim != 2 or not 2 <= len(x) <= 16 or len(q) != len(x) or not 1 <= x.shape[1] <= 64 or not 2 <= q.shape[1] <= 8:
        raise ValueError('Use matching small feature and class matrices.')
    if not np.isfinite(x).all() or not np.isfinite(q).all() or np.any(q < 0) or not np.allclose(q.sum(axis=1), 1):
        raise ValueError('Features must be finite and targets must be probability rows.')
    if order.dtype.kind not in 'iu' or order.shape != (len(x),) or sorted(order.tolist()) != list(range(len(x))):
        raise ValueError('Pairing must be a permutation of row indices.')
    if not np.isfinite(lam) or not 0 <= lam <= 1:
        raise ValueError('Mixing coefficient must be in [0, 1].')
    return lam * x + (1 - lam) * x[order], lam * q + (1 - lam) * q[order]


def loss_gradient(x, q, weights):
    z = x @ weights
    shifted = z - z.max(axis=1, keepdims=True)
    logp = shifted - np.log(np.exp(shifted).sum(axis=1, keepdims=True))
    p = np.exp(logp)
    return float(-np.sum(q * logp) / len(x)), x.T @ (p - q) / len(x), p


def train(steps=200):
    if type(steps) is not int or not 0 <= steps <= 500:
        raise ValueError('Use 0 to 500 training steps.')
    x = np.array([[1, 1, 0, 0], [0, 0, 1, 1]], dtype=float)
    q = np.eye(2)
    mixed_x, mixed_q = mixup(x, q, [1, 0], 0.25)
    w = np.zeros((4, 2))
    for _ in range(steps):
        _, grad, _ = loss_gradient(mixed_x, mixed_q, w)
        w -= 0.5 * grad
    return x, q, mixed_x, mixed_q, w


if __name__ == '__main__':
    x, q, mx, mq, w = train()
    print('mixed features', mx.tolist(), 'mixed targets', mq.tolist())
    value, _, p = loss_gradient(mx, mq, w)
    print('mixed predictions', p.round(9).tolist(), 'loss', round(value, 9))
    print('original predictions', loss_gradient(x, q, w)[2].round(9).tolist())
    print('target entropy', round(float(-mq[0] @ np.log(mq[0])), 9))
    print('parabola counterexample: mixed input', 0.5 * (-1) + 0.5 * 1,
          'mixed label', 0.5 * 1 + 0.5 * 1, 'true squared value', 0 ** 2)

Actual output:

mixed features [[0.25, 0.25, 0.75, 0.75], [0.75, 0.75, 0.25, 0.25]] mixed targets [[0.25, 0.75], [0.75, 0.25]]
mixed predictions [[0.250011008, 0.749988992], [0.749988992, 0.250011008]] loss 0.562335145
original predictions [[0.899989432, 0.100010568], [0.100010568, 0.899989432]]
target entropy 0.562335145
parabola counterexample: mixed input 0.0 mixed label 1.0 true squared value 0

The mixed predictions approach (0.25,0.75), while predictions on the original endpoints approach (0.9,0.1). The latter are extrapolations of the fitted logit relationship, not target probabilities guaranteed by Mixup. The mixed target entropy is about 0.562335145, so a nonzero cross-entropy is expected even at p=q. The final counterexample mixes x=−1 and x=1 with target x². Their average input is zero but the mixed label is one, whereas the true square is zero.

For a batch with B examples, d features and K classes, materializing mixed arrays costs O(Bd+BK) time and storage, before the model’s own forward/backward cost. Our helpers return new arrays and validate the pairing and probability rows.

When the method fails

Mixing assumes compatible representations and target semantics. Pixel intensities can be combined numerically, but two categorical IDs cannot be averaged into a meaningful category. Object detection, segmentation and sequences require task-specific target handling; a classification vector is not a universal substitute.

The torchvision v0.23.0 implementation mixes batch labels into probability vectors and pairs rows through a batch roll. Its documentation notes that pairing is an implementation detail and that the batch should be shuffled. Compare augmentation against a no-mixing baseline on the same untouched evaluation data, with the same total training budget. Our example demonstrates mechanics and a failed interpolation assumption; it does not establish accuracy gains.

Exercises with answers

  1. Mix targets (1,0) and (0,1) with λ=0.25. What is the result?

Answer 1: (0.25,0.75), with total mass one.

  1. May the two cross-entropy terms use predictions on two original images?

Answer 2: Not in the displayed decomposition. Both use the prediction on the same mixed image.

  1. Why does optimal mixed cross-entropy not approach zero?

Answer 3: A non-one-hot target has positive entropy. Its minimum cross-entropy is that entropy when p=q.

  1. What does the squared-target counterexample refute?

Answer 4: It refutes the assumption that linearly mixed labels always equal the true target at the mixed input, not the possibility that Mixup can help as regularization.

Sources and next steps

The paper’s physical page 3 defines the vicinal distribution, beta sampling and paired interpolation. The fixed official implementation supplies a concrete batch-label convention. This chapter’s softmax fit, entropy check and parabola counterexample are original. Continue with CutMix, which replaces a region instead of blending every feature.

Make a prediction, then check

Where must predictions be evaluated in Mixup’s weighted loss?

Choose one answer

Learning objectives

  • Derive target-linear cross-entropy for mixed inputs.
  • Test endpoint behavior and failures of label interpolation.

Prerequisites & connections

Explore related knowledge →

References

  1. mixup: Beyond Empirical Risk Minimization — arXiv v2
    Hongyi Zhang; Moustapha Cisse; Yann N. Dauphin; David Lopez-Paz · 2018
  2. MixUp and CutMix implementation — torchvision v0.23.0
    Torchvision contributors

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-06 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter, including independent derivatives, integrals, normal equations or exact/literal trajectory references as appropriate. All eight programs use NumPy 1.26.4. Tests include augmentation geometry, exact quadratic certificates, finite differences, spectral solutions, conditional risk decompositions and masked neural-network training. CPU teaching calculations, not framework or GPU benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.