AI Wiki中文/EN

CutMix: replace the patch, recount the label

CutMix

Compute a clipped replacement mask, preserve pixel boundaries and use the actual patch area for soft targets.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

Mixup blends every input feature. CutMix keeps most of one image intact and replaces a rectangle with the corresponding region from another image. It combines the class targets according to the area contributed by each image. The visual splice and the target update are one augmentation operation.

Yun and colleagues, Section 3.1, define a binary mask for this replacement. A rectangle near an image edge may be clipped, so the area actually inserted can differ from the area requested. The example below makes that discrepancy large enough to check by counting four pixels.

Definitions and derivation

Let M equal one where image A is retained and zero in the replacement region. Apply the same spatial mask to all channels. With probability target vectors qA and qB:

x~=M⊙xA+(1−M)⊙xB,q~=λqA+(1−λ)qB,M∈{0,1}H×W.\tilde x=M\odot x_A+(1-M)\odot x_B,\qquad \tilde q=\lambda q_A+(1-\lambda)q_B,\quad M\in\{0,1\}^{H\times W}.

The paper samples a desired mixing proportion from a beta distribution and constructs a rectangular mask. Our implementation accepts an explicit rectangle, so geometric effects can be tested without random-box conventions. Coordinates are half-open: the left/top boundary is included and the right/bottom boundary is excluded. x indexes columns and y indexes rows.

Clip the ordered coordinates to the image bounds before computing the effective target coefficient:

Apatch=(x2′−x1′)(y2′−y1′),λ=1−ApatchHW,xi′=clip⁡(xi,0,W),yi′=clip⁡(yi,0,H).A_{\rm patch}=(x_2'-x_1')(y_2'-y_1'),\qquad \lambda=1-\frac{A_{\rm patch}}{HW},\quad x_i'=\operatorname{clip}(x_i,0,W),\quad y_i'=\operatorname{clip}(y_i,0,H).

Channel count does not appear in the area ratio because each spatial location replaces all channels. Empty or wholly out-of-bounds rectangles have zero area and retain qA. A full-image rectangle produces qB. Integer rounding during random-box construction can change area even before clipping.

For a 4×4 image, requesting the box (−1,−1,2,2) suggests nine pixels, but clipping inserts only the top-left 2×2 block. The resulting loss gradient uses the adjusted target:

∇zCE⁡(q~,softmax⁡(z))=p−q~,λactual=1−416=34,λrequested=1−916=716.\nabla_z\operatorname{CE}(\tilde q,\operatorname{softmax}(z))=p-\tilde q,\qquad \lambda_{\rm actual}=1-\frac4{16}=\frac34,\quad \lambda_{\rm requested}=1-\frac9{16}=\frac7{16}.

At fixed logits, changing the coefficient changes the supervision even though the pixels are identical. The fixed torchvision implementation explicitly calculates an adjusted coefficient from the clipped box before mixing labels. Its random-box rounding differs from our supplied-box contract; the shared principle is to use actual geometry.

Computed 4×4 images: the clipped top-left 2×2 region comes from B. Four of sixteen spatial positions are replaced; color encodes pixel value, not class probability.
Computed 4×4 images: the clipped top-left 2×2 region comes from B. Four of sixteen spatial positions are replaced; color encodes pixel value, not class probability.

Run the calculation

The complete Python 3.12 / NumPy 1.26.4 program uses all-one and all-zero images so the replacement is unambiguous. It returns the image, target, retained-A coefficient and clipped box. Cross-entropy at logits (2,−1) makes the consequence of a wrong area visible.

import numpy as np


def cutmix(a, b, qa, qb, box):
    a, b, qa, qb = [np.asarray(v, dtype=float) for v in (a, b, qa, qb)]
    if a.ndim != 3 or b.shape != a.shape or not all(1 <= d <= 16 for d in a.shape) or qa.ndim != 1 or qb.shape != qa.shape or not 2 <= qa.size <= 8:
        raise ValueError('Use matching small HWC images and target vectors.')
    if not all(np.isfinite(v).all() for v in (a, b, qa, qb)) or any(np.any(q < 0) or not np.isclose(q.sum(), 1) for q in (qa, qb)):
        raise ValueError('Use finite images and probability targets.')
    if len(box) != 4 or any(type(v) is not int or abs(v) > 64 for v in box):
        raise ValueError('Box coordinates must be four bounded integers.')
    x1, y1, x2, y2 = box
    if x2 < x1 or y2 < y1:
        raise ValueError('Use ordered half-open box coordinates.')
    h, w, _ = a.shape
    x1, x2 = np.clip([x1, x2], 0, w)
    y1, y2 = np.clip([y1, y2], 0, h)
    area = int((x2 - x1) * (y2 - y1))
    lam = 1 - area / (h * w)
    out = a.copy()
    out[y1:y2, x1:x2, :] = b[y1:y2, x1:x2, :]
    return out, lam * qa + (1 - lam) * qb, lam, (int(x1), int(y1), int(x2), int(y2))


def cross_entropy(logits, q):
    z = np.asarray(logits, dtype=float)
    shifted = z - z.max()
    logp = shifted - np.log(np.exp(shifted).sum())
    return float(-np.asarray(q) @ logp)


if __name__ == '__main__':
    a, b = np.ones((4, 4, 1)), np.zeros((4, 4, 1))
    out, q, lam, clipped = cutmix(a, b, [1, 0], [0, 1], (-1, -1, 2, 2))
    print('clipped box', clipped, 'actual source weight', lam, 'target', q.tolist())
    print('mixed pixels', out[:, :, 0].tolist())
    nominal = 1 - 9 / 16
    print('unclipped-area weight', nominal)
    print('correct / wrong target loss', round(cross_entropy([2, -1], q), 9),
          round(cross_entropy([2, -1], [nominal, 1 - nominal]), 9))
    same, same_q, _, _ = cutmix(a, a, [1, 0], [0, 1], (-1, -1, 2, 2))
    print('same-image changed pixels', int(np.count_nonzero(same != a)), 'policy target', same_q.tolist())

Actual output:

clipped box (0, 0, 2, 2) actual source weight 0.75 target [0.75, 0.25]
mixed pixels [[0.0, 0.0, 1.0, 1.0], [0.0, 0.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0]]
unclipped-area weight 0.4375
correct / wrong target loss 0.798587352 1.736087352
same-image changed pixels 0 policy target [0.75, 0.25]

The correct target is (0.75,0.25), yielding loss 0.798587352. Using the requested rather than clipped area gives 1.736087352. No model was trained to produce these numbers; they are augmentation and loss calculations. The last case deliberately replaces an image region with identical pixels while supplying a different target: geometry still changes the policy target, although no pixel changes. Area weighting is a supervision rule, not semantic recognition.

Copying the image costs O(HWC); inserting a patch costs O(Apatch C), and mixing K target entries costs O(K). Returning a new image protects the originals from accidental modification. A production pipeline should also specify dtype, value range, layout and whether augmentation happens before or after normalization.

When the method fails

A patch can cover background, hide the only object or contain parts of several objects. Pixel area need not equal class evidence. Classifying a pasted fragment may demand different cues from classifying the original image. These are assumptions to test, not reasons to treat every synthetic target as a factual annotation.

Detection boxes and segmentation masks need their own spatial rules; simply mixing a global class vector is insufficient. Mixup changes all intensities, CutMix preserves intensities outside the splice, and erasing a patch without replacing it is another operation. Compare these policies under matched training budgets and inspect failure slices. The original paper’s localization and classification results belong to its model/data setups, and are not reproduced by this four-by-four calculation.

Exercises with answers

  1. What target follows a four-pixel replacement in a 4×4 image?

Answer 1: 0.75qA+0.25qB, independently of channel count.

  1. Why can a sampled λ differ from the final label coefficient?

Answer 2: Integer box construction and boundary clipping can change the replaced area.

  1. Does an unchanged pixel array imply that the target cannot change?

Answer 3: No. Identical source pixels with distinct supplied labels still trigger the area-based target rule. That reveals a semantic assumption.

  1. What does a wholly outside rectangle do in this implementation?

Answer 4: Its clipped area is zero, so both image A and qA are retained.

Sources and next steps

The paper’s Equation 1 supplies the mask and target mixture. The official versioned source supplies the adjusted-area implementation check. The explicit-box API, boundary tests and same-pixel counterexample are original. Revisit Mixup for target-linear cross-entropy and convolution for how local image structure enters a model.

Make a prediction, then check

Which area determines the final CutMix label coefficient?

Choose one answer

Learning objectives

  • Compute the target from the actual clipped patch area.
  • Separate geometric supervision from semantic class evidence.

Prerequisites & connections

Explore related knowledge →

References

  1. CutMix: Regularization Strategy to Train Strong Classifiers With Localizable Features
    Sangdoo Yun; Dongyoon Han; Seong Joon Oh; Sanghyuk Chun; Junsuk Choe; Youngjoon Yoo · 2019
  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.
  • Bilingual SVGs generated with Matplotlib 3.9.1 from executed article functions: actual pixel replacement, conditional-risk quantiles and absolute/relative loss profiles. Captions distinguish probability from pixels, interquartile ranges from confidence intervals and separate plot scales. Locale figures and sample data are hash-bound.

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.