AI Logic

Semi-Supervised Learning

MixMatch

Updated:

Training flow of MixMatch. The left side shows the overall flow: the cross-entropy on labeled images that are augmented and mixed with MixUp is added to the consistency loss on unlabeled images to update the model. The right side shows the inside: predictions on two augmentations of an unlabeled image are averaged and sharpened into a guessed label, and the squared error is taken between the MixUp-mixed label and the prediction on the mixed image

Background and Overview

MixMatch is a semi-supervised learning method that assigns "guessed labels" to unlabeled images and trains on them mixed with labeled images using MixUp. It was proposed in 2019 by Berthelot et al. at Google.

Earlier semi-supervised learning used three main ideas for exploiting unlabeled data.

  • Consistency regularization: Make predictions stay the same when the same image is slightly altered (Π-model, Mean Teacher, etc.).
  • Entropy minimization: Make the model output confident (low-uncertainty) predictions on unlabeled images.
  • Traditional regularization: Make it harder to memorize the training data, as with MixUp and weight decay.

MixMatch combines all three into a single procedure. It applies augmentation twice to each unlabeled image and averages the predictions (consistency), sharpens that average into a guessed label (entropy minimization), and mixes labeled and unlabeled images together with MixUp before training (traditional regularization).

For example, if two different crops of an unlabeled image are predicted as "cat 55%" and "cat 45%", the average is sharpened into a guessed label such as "cat 80%". Then, when this image is blended with another image in a 7:3 ratio, the target is the labels blended in the same 7:3 ratio.

In the paper's CIFAR-10 experiments, MixMatch reached an 11.08% error rate with 250 labels, which according to the paper's abstract reduces the error by about a factor of four from the previous roughly 38%. MixMatch is also a main baseline in later papers such as UDA and FixMatch.

Training Procedure and Loss

One training step of MixMatch proceeds in the following order, as in Algorithm 1 of the paper. The same number BB of labeled and unlabeled images is drawn.

  1. Apply augmentation (horizontal flip and crop) once to each labeled image xbx_b to obtain x^b\hat{x}_b.
  2. Apply augmentation KK times (K=2K = 2 in the paper) to each unlabeled image ubu_b to obtain u^b,1,…,u^b,K\hat{u}_{b,1}, \dots, \hat{u}_{b,K}.
  3. Pass each u^b,k\hat{u}_{b,k} through the model and compute the average prediction qˉb\bar{q}_b.
  4. Sharpen qˉb\bar{q}_b with temperature TT (0.5 in the paper) to obtain the guessed label qbq_b. No gradient flows through the guessed label.
  5. Gather all augmented labeled pairs (x^b,pb)(\hat{x}_b, p_b) and unlabeled pairs (u^b,k,qb)(\hat{u}_{b,k}, q_b), shuffle them, and form the pool of mixing partners W\mathcal{W}.
  6. Mix the labeled pairs and the unlabeled pairs each with examples from W\mathcal{W} using MixUp to form X′\mathcal{X}' and U′\mathcal{U}'.
  7. Compute the cross-entropy on X′\mathcal{X}' and the squared error on U′\mathcal{U}', and add them with a weight.

Steps 3 and 4 are given by the following equations (Eqs. (6)(7)).

qˉb=1K∑k=1Kpmodel(y∣u^b,k;θ),Sharpen(p,T)i=pi1/T∑j=1Lpj1/T\bar{q}_b = \frac{1}{K} \sum_{k=1}^{K} p_{\mathrm{model}}(y \mid \hat{u}_{b,k}; \theta), \qquad \mathrm{Sharpen}(p, T)_i = \frac{p_i^{1/T}}{\sum_{j=1}^{L} p_j^{1/T}}

LL is the number of classes. As TT approaches 0, the guessed label approaches a one-hot vector.

The MixUp in step 6 mixes two examples (x1,p1)(x_1, p_1) and (x2,p2)(x_2, p_2) as follows (Eqs. (8)–(11)).

λ∼Beta(α,α),λ′=max⁡(λ,1−λ),x′=λ′x1+(1−λ′)x2,p′=λ′p1+(1−λ′)p2\lambda \sim \mathrm{Beta}(\alpha, \alpha), \quad \lambda' = \max(\lambda, 1-\lambda), \quad x' = \lambda' x_1 + (1-\lambda') x_2, \quad p' = \lambda' p_1 + (1-\lambda') p_2

Unlike standard MixUp, λ′=max⁡(λ,1−λ)\lambda' = \max(\lambda, 1-\lambda) ensures that the mixed result always stays closer to x1x_1. This way, after mixing, labeled examples can still be handled by the labeled loss and unlabeled examples by the unlabeled loss.

Finally, the loss in step 7 is as follows (Eqs. (3)–(5)).

LX=1∣X′∣∑x,p∈X′H(p, pmodel(y∣x;θ)),LU=1L∣U′∣∑u,q∈U′∥q−pmodel(y∣u;θ)∥22,L=LX+λULU\mathcal{L}_{\mathcal{X}} = \frac{1}{|\mathcal{X}'|} \sum_{x, p \in \mathcal{X}'} \mathrm{H}\left(p,\ p_{\mathrm{model}}(y \mid x; \theta)\right), \qquad \mathcal{L}_{\mathcal{U}} = \frac{1}{L |\mathcal{U}'|} \sum_{u, q \in \mathcal{U}'} \left\| q - p_{\mathrm{model}}(y \mid u; \theta) \right\|_2^2, \qquad \mathcal{L} = \mathcal{L}_{\mathcal{X}} + \lambda_{\mathcal{U}} \mathcal{L}_{\mathcal{U}}

H\mathrm{H} is the cross-entropy, and λU\lambda_{\mathcal{U}} is the weight of the unlabeled loss, which is raised linearly from 0 over the first 16,000 steps.

According to the paper, the unlabeled loss uses squared error (MSE) rather than cross-entropy because it is bounded and less sensitive to completely wrong predictions. Guessed labels are uncertain targets built from the model's own predictions, so a loss that does not blow up when they are wrong is helpful.

Why It Works

What each component of MixMatch does can be read from the paper's ablation study, which removes components one at a time (CIFAR-10, error rate).

Change250 labels4,000 labels
MixMatch (unchanged)11.80%6.00%
No prediction averaging (K=1K = 1)17.09%8.06%
No sharpening (T=1T = 1)27.83%10.59%
Guess labels with an exponential-moving-average model11.86%6.47%
No MixUp39.11%10.97%
MixUp on labeled data only32.16%9.22%
MixUp on unlabeled data only12.35%6.83%

This shows the following.

  • MixUp matters most: Without MixUp, the error with 250 labels jumped from 11.80% to 39.11%. Applying MixUp to unlabeled examples is especially important. By learning that predictions on mixed images change linearly along with the mixed labels, the model's predictions between examples become smooth.
  • Sharpening also has a large effect: Without sharpening, the error worsened to 27.83%. Sharpening the guessed labels teaches the model to output confident predictions on unlabeled images. This is the effect of entropy minimization, which keeps decision boundaries from passing through dense regions of the data.
  • Averaging over multiple augmentations stabilizes the targets: Guessing from a single augmentation increased the error. Averaging reduces the variance of the guessed labels.
  • A weight-averaged model is not necessarily needed: Generating guessed labels with an exponential-moving-average model, as in Mean Teacher, actually made MixMatch slightly worse.

The paper states that every component contributes to performance, and that the differences grow as labels become scarcer.

Experimental Results

The paper compared methods using the same network (Wide ResNet-28, 1.5 million parameters), reimplementing the other methods in the same codebase (error rate).

MethodCIFAR-10 (250)CIFAR-10 (4,000)SVHN (250)SVHN (4,000)
Π-model53.02%17.41%17.65%5.57%
Pseudo-labeling49.98%16.21%21.16%5.71%
MixUp47.43%13.15%39.97%7.96%
VAT36.03%11.05%8.41%4.20%
Mean Teacher47.32%10.36%6.45%3.39%
MixMatch11.08%6.24%3.78%2.89%

The same network trained fully supervised on all labels has error rates of 4.17% on CIFAR-10 and 2.59% on SVHN. On CIFAR-10, MixMatch with 4,000 labels reaches about the same performance as Mean Teacher with roughly 16 times fewer labels.

Results under other settings:

  • Larger network (26 million parameters): 4.95% on CIFAR-10 (4,000 labels) and 25.88% on CIFAR-100 (10,000 labels).
  • STL-10: 10.18% with 1,000 labels and 5.59% with all 5,000 labels.
  • SVHN with the additional unlabeled data (extra): 2.22% with 250 labels, close to the 1.71% of supervised training with all labels (604,388 images).

MixMatch was also applied in a differential privacy framework (PATE). On SVHN, it achieved a higher accuracy of 95.21% with a stronger privacy guarantee (ε=0.97\varepsilon = 0.97) than the previous VAT-based method (91.6% accuracy at privacy loss ε=4.96\varepsilon = 4.96). This is an example of learning from fewer labels translating directly into stronger privacy.

Practical Considerations

MixMatch has many hyperparameters (temperature TT, number of augmentations KK, MixUp α\alpha, and unlabeled loss weight λU\lambda_{\mathcal{U}}). The paper fixed T=0.5T = 0.5 and K=2K = 2 in all experiments and changed only α\alpha and λU\lambda_{\mathcal{U}} per dataset. A starting point for tuning is α=0.75\alpha = 0.75 and λU=100\lambda_{\mathcal{U}} = 100. Note that with few labels, the validation set is also small, so tuning results can be noisy.

Also keep the following in mind.

  • λU\lambda_{\mathcal{U}} varies widely across datasets: In the paper it is 75 for CIFAR-10, 150 for CIFAR-100, 250 for SVHN, and 50 for STL-10. In every case it is raised linearly from 0 over the first 16,000 steps.
  • Unlabeled images cost KK times the computation: To create guessed labels, each unlabeled image passes through the model KK times. The mixed images then pass through once more, so each step is heavier than standard training.
  • Preserve the order before and after mixing: If λ′=max⁡(λ,1−λ)\lambda' = \max(\lambda, 1-\lambda) is dropped in favor of standard MixUp, it is no longer clear whether an example should be handled by the labeled or the unlabeled loss. Do not forget this one line in implementations.
  • Evaluate with an exponential moving average of the weights: Instead of decaying the learning rate, the paper evaluates with an exponential-moving-average model of the weights (decay rate 0.999). Weight decay is 0.0004.
  • Only weak augmentation is used: The paper's augmentation is only horizontal flip and crop. In later work, methods combining strong augmentation (UDA, FixMatch, etc.) outperform it when labels are even scarcer.

Comparison with Other Semi-Supervised Methods

Semi-supervised methods based on consistency regularization compare as follows along the same axes.

MethodTarget predictionPrediction being trained (how the input is changed)Target post-processingDistance between predictions
Π-modelPrediction from the same model with different noiseWeak augmentation and dropoutNoneSquared error
Mean TeacherPrediction of the model with exponentially averaged weightsWeak augmentation and dropoutNoneSquared error
VATPrediction on the unperturbed imageSmall perturbation in the direction that changes the prediction mostNoneKL divergence
MixMatchAverage of predictions over KK weak augmentationsWeak augmentation + MixUpSharpeningSquared error
UDAPrediction on weak augmentationStrong augmentation (RandAugment, etc.)Sharpening (low-confidence ones are discarded)Cross-entropy
FixMatchPrediction on weak augmentationStrong augmentationOne-hot if above a thresholdCross-entropy

Guidelines for choosing:

  • Strong data augmentation is hard to use: MixMatch achieves high accuracy with only weak augmentation and MixUp. MixUp is a regularizer that depends little on the type of image.
  • Extremely few labels (a few per class): In the FixMatch paper, with 40 labels on CIFAR-10, MixMatch had a 47.54% error rate, compared with 29.05% for UDA and 11.39% for FixMatch. Methods using strong augmentation are a better fit.
  • Fewer hyperparameters are wanted: FixMatch needs only a few values such as a threshold and is easier to tune than MixMatch.

PyTorch example

Show code
python
import numpy as np
import torch
import torch.nn.functional as F

"""
One MixMatch step (a small implementation following Algorithm 1 and Eqs. (2)-(11) of the paper)
x: labeled images [B, ...], y: ground-truth classes [B], u: unlabeled images [B, ...]
augment: weak augmentation (horizontal flip and crop), a function that uses different randomness per image in the batch
"""


def sharpen(p, T):
  """Sharpen(p, T)_i = p_i^(1/T) / Σ_j p_j^(1/T)"""
  p = p ** (1 / T)
  return p / p.sum(dim=1, keepdim=True)


def mixup(x1, p1, x2, p2, alpha):
  lam = np.random.beta(alpha, alpha)
  lam = max(lam, 1 - lam)                 # λ' = max(λ, 1-λ): stay closer to x1
  return lam * x1 + (1 - lam) * x2, lam * p1 + (1 - lam) * p2


def mixmatch_step(model, optimizer, augment, x, y, u, num_classes,
                  step, T=0.5, K=2, alpha=0.75, lambda_u_max=75.0, rampup_steps=16000):
  model.train()
  B = x.size(0)
  p = F.one_hot(y, num_classes).float()

  # 1-4: augment, average K predictions, sharpen into guessed labels (no gradient)
  x_hat = augment(x)
  u_hat = [augment(u) for _ in range(K)]
  with torch.no_grad():
    q_bar = sum(model(uk).softmax(dim=1) for uk in u_hat) / K
    q = sharpen(q_bar, T)

  # 5: shuffle labeled and unlabeled together to form the mixing partners W
  all_x = torch.cat([x_hat] + u_hat)
  all_p = torch.cat([p] + [q] * K)
  idx = torch.randperm(all_x.size(0))
  w_x, w_p = all_x[idx], all_p[idx]

  # 6: MixUp (labeled examples mix with the first part of W, unlabeled with the rest)
  mixed_x, mixed_p = mixup(all_x, all_p, w_x, w_p, alpha)

  # 7: loss. Cross-entropy for labeled, squared error for unlabeled
  logits = model(mixed_x)
  loss_x = -(mixed_p[:B] * logits[:B].log_softmax(dim=1)).sum(dim=1).mean()
  loss_u = F.mse_loss(logits[B:].softmax(dim=1), mixed_p[B:])   # 1/(L|U'|) Σ ||q - p||^2
  lambda_u = lambda_u_max * min(step / rampup_steps, 1.0)        # raised linearly over the first 16,000 steps
  loss = loss_x + lambda_u * loss_u

  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  return loss.item()

# Note: for simplicity, a single λ is used for the whole batch. Evaluate with an exponential-moving-average (0.999) model of the weights.

FAQ

Q. How should the temperature $T$ and the number of augmentations $K$ be chosen?
A.

The paper fixes T=0.5T = 0.5 and K=2K = 2 in all experiments. In the ablation study (CIFAR-10), K=3K = 3 or K=4K = 4 gave no large improvement, while T=1T = 1 (no sharpening) made results much worse. A reasonable approach is to start with the paper's values and tune the MixUp α\alpha and the unlabeled loss weight λU\lambda_{\mathcal{U}} per dataset.

Q. Doesn't mixing labeled and unlabeled images break the meaning of the labels?
A.

Images and labels (guessed labels) are mixed in the same proportion λ′\lambda', so the target changes together with the mixed image. In addition, λ′=max⁡(λ,1−λ)\lambda' = \max(\lambda, 1-\lambda) keeps the mixed image closer to the original example. In the ablation study, mixing labeled and unlabeled data together gave slightly better results than mixing them separately (6.00% versus 6.50% with 4,000 labels).

Q. How much does adding more unlabeled data help?
A.

In the paper's SVHN experiments, keeping 250 labeled images and increasing the unlabeled images from about 70,000 to about 600,000 (adding SVHN extra) lowered the error rate from 3.78% to 2.22%. This is lower than the 2.59% from supervised training with all 73,257 images labeled and no additional images. The paper notes that collecting unlabeled data and using MixMatch can sometimes be more efficient than collecting labels.

References

  1. Berthelot, D., Carlini, N., Goodfellow, I., Oliver, A., Papernot, N., & Raffel, C. (2019). MixMatch: A Holistic Approach to Semi-Supervised Learning. Advances in Neural Information Processing Systems 32 (NeurIPS 2019).
  2. Sohn, K., Berthelot, D., Carlini, N., Zhang, Z., Zhang, H., Raffel, C. A., Cubuk, E. D., Kurakin, A., & Li, C.-L. (2020). FixMatch: Simplifying Semi-Supervised Learning with Consistency and Confidence. Advances in Neural Information Processing Systems 33 (NeurIPS 2020).