AI Logic

Semi-Supervised Learning

FixMatch

Updated:

FixMatch training flow. The left side shows the overall flow of adding the labeled-image loss and the unlabeled loss to update the model; the right side shows the details: a pseudo-label is created by thresholding the prediction on a weakly augmented unlabeled image, and the cross-entropy is taken against the prediction on a strongly augmented version

Background and Overview

FixMatch is a semi-supervised learning method that trains a classification model by combining a small amount of labeled data with a large amount of unlabeled data. It was proposed by Sohn et al. at Google in 2020.

The idea is simple. An unlabeled image first receives weak data augmentation (a horizontal flip and a small translation) and the model makes a prediction; only when the model is sufficiently confident (e.g., the maximum probability is 0.95 or higher) is that prediction adopted as a "pseudo-label." Next, strong data augmentation (transformations that heavily distort color and shape) is applied to the same image, and the model is trained to predict the same class as the pseudo-label on that image as well.

For example, if an unlabeled photo of a dog is only lightly flipped, the model may confidently answer "dog: 97%." "Dog" is then treated as the correct answer, and the model learns to answer "dog" even for the same photo with heavily altered colors and part of it blacked out. In this way, the model learns features that are robust to changes in appearance, even from images that have no labels.

This idea combines two pillars of earlier semi-supervised learning.

  • Consistency regularization: keep predictions unchanged when the same image is slightly altered (Π-model, Mean Teacher, etc.).
  • Pseudo-labeling: use the model's own confident predictions in place of labels.

FixMatch is simpler than earlier methods such as MixMatch and UDA, yet more accurate. On CIFAR-10 it reaches 94.93% accuracy with 250 labeled images (25 per class) and 88.61% with 40 labeled images (4 per class) (using CTAugment as the strong augmentation).

Training Procedure and Loss

One training step of FixMatch proceeds in the following order, as in Algorithm 1 of the paper.

  1. Sample BB labeled images and μB\mu B unlabeled images (μ\mu is the ratio of unlabeled images).
  2. Apply weak data augmentation α\alpha to the labeled images and compute the cross-entropy ℓs\ell_s against the ground truth.
  3. Apply weak data augmentation to the unlabeled image ubu_b, run the model, and obtain the class probabilities qb=pm(y∣α(ub))q_b = p_m(y \mid \alpha(u_b)).
  4. If the maximum of qbq_b is at least the threshold τ\tau, take the most probable class q^b=arg⁡max⁡(qb)\hat{q}_b = \arg\max(q_b) as the pseudo-label. If it is below τ\tau, the image is not used in this step.
  5. Apply strong data augmentation A\mathcal{A} to the same ubu_b, run the model, and compute the cross-entropy against the pseudo-label. This is ℓu\ell_u.
  6. Update the model weights to minimize ℓs+λuℓu\ell_s + \lambda_u \ell_u.

The losses in steps 2 and 5 are written as follows.

ℓs=1B∑b=1BH(pb, pm(y∣α(xb))),ℓu=1μB∑b=1μB1(max⁡(qb)≥τ) H(q^b, pm(y∣A(ub)))\ell_s = \frac{1}{B} \sum_{b=1}^{B} \mathrm{H}\bigl(p_b,\ p_m(y \mid \alpha(x_b))\bigr), \qquad \ell_u = \frac{1}{\mu B} \sum_{b=1}^{\mu B} \mathbb{1}\bigl(\max(q_b) \ge \tau\bigr)\ \mathrm{H}\bigl(\hat{q}_b,\ p_m(y \mid \mathcal{A}(u_b))\bigr)

Here xbx_b and pbp_b are a labeled image and its ground truth, pm(y∣⋅)p_m(y \mid \cdot) is the class probability output by the model, H\mathrm{H} is the cross-entropy, and 1(⋅)\mathbb{1}(\cdot) equals 1 when the condition holds and 0 otherwise.

Two kinds of data augmentation are used.

  • Weak augmentation: flip horizontally with 50% probability (no flipping for SVHN, which contains digit images) and translate by up to 12.5% vertically and horizontally.
  • Strong augmentation: apply transformations selected by RandAugment or CTAugment (rotation, color changes, distortion, etc.), then black out part of the image with Cutout. Unlike AutoAugment, neither requires learning an augmentation policy on labeled data in advance.

The key is to create pseudo-labels from the weak augmentation and to train on the strong augmentation. Weakly augmented images are close to the original, so predictions on them tend to be correct; strongly augmented images are hard to recognize, so there is more to learn from them. In the paper's analysis, creating pseudo-labels from the strong augmentation as well caused training to diverge early on, while using the weak augmentation on the training side as well made accuracy rise at first and then collapse.

Hyperparameters and Training Tips

The paper uses nearly the same hyperparameters for all of CIFAR-10, CIFAR-100, SVHN, and STL-10.

ItemValueMeaning
Threshold τ\tau0.95Only predictions with at least this confidence become pseudo-labels
Weight of the unlabeled loss λu\lambda_u1Kept constant throughout training rather than ramped up
Ratio of unlabeled images μ\mu7448 unlabeled images for every 64 labeled images
Batch size BB64Number of labeled images
OptimizerSGD (Nesterov momentum 0.9), learning rate 0.03
Learning rate scheduleηcos⁡(7πk16K)\eta \cos\left(\frac{7 \pi k}{16 K}\right)kk is the current step and KK the total number of steps (2202^{20}). A cosine decay that does not go all the way to 0
Weight decay0.0005 (0.001 for CIFAR-100)

Evaluation uses a model whose weights are an exponential moving average.

The threshold has another role as well. Early in training the model's confidence is low and most images do not exceed τ\tau, so ℓu\ell_u is nearly 0. As training progresses and confidence rises, the number of usable images grows naturally. As a result, unlike many semi-supervised methods, there is no need to ramp up λu\lambda_u gradually. The paper calls this a "curriculum for free" (learning from easy examples first).

In the paper's analysis, the fewer the labels, the more strongly settings other than the semi-supervised method itself affect the results. A wrong weight decay value degrades performance significantly, and using Adam as the optimizer performed worse than SGD. When applying the method to your own data, it is safest to start from the paper's settings.

The paper also includes experiments with extremely few labels. With only one image per class on CIFAR-10 (10 images in total), accuracy varied widely from 48.58% to 85.32% depending on which images were chosen (median 64.28%). Choosing prototypical images that represent each class reached a median of 78%, while choosing only outlier-like images prevented training from progressing well. This shows that the choice of images to label also affects the results.

Comparison with Other Semi-Supervised Methods

Comparing semi-supervised methods that use consistency regularization by how they create artificial labels (the predictions used as training targets) gives the following (based on Table 1 of the paper).

MethodAugmentation for creating the artificial labelAugmentation for trainingPost-processing of the artificial label
Π-modelWeakWeakNone
Mean TeacherWeakWeakNone (predicted by an exponential-moving-average model)
VATNoneAdversarial perturbationNone
UDAWeakStrongSharpening (low-confidence predictions are not used)
MixMatchWeakWeakSharpening (averaging several predictions)
ReMixMatchWeakStrongSharpening
FixMatchWeakStrongPseudo-labeling (one-hot for predictions above the threshold)

FixMatch can be seen as a simplification of the "create targets with weak augmentation, learn with strong augmentation" scheme shared with UDA and ReMixMatch, achieved by using thresholded one-hot pseudo-labels instead of sharpening the probabilities. The difference shows up especially when labels are extremely scarce (e.g., 4 per class): in the 40-label CIFAR-10 setting, the error rate is 47.54% for MixMatch and 29.05% for UDA, versus 11.39% for FixMatch (with CTAugment).

PyTorch example

Show code
python
import math
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, models
from torch.utils.data import DataLoader, Dataset
from tqdm import tqdm

"""
Train FixMatch on CIFAR-10 with 250 labeled images (25 per class)
and the remaining images as unlabeled data
"""

# Hyperparameters (paper defaults; only the number of steps is reduced)
batch_size = 64        # Labeled batch size B
mu = 7                 # Ratio of unlabeled images μ
threshold = 0.95       # Threshold τ
lambda_u = 1.0         # Weight of the unlabeled loss λu
learning_rate = 0.03
weight_decay = 5e-4
total_steps = 20000    # The paper uses 2^20 steps
labels_per_class = 25

device = 'cuda' if torch.cuda.is_available() else 'mps' if torch.backends.mps.is_available() else 'cpu'

mean, std = (0.4914, 0.4822, 0.4465), (0.2471, 0.2435, 0.2616)
normalize = transforms.Compose([transforms.ToTensor(), transforms.Normalize(mean, std)])

# Weak augmentation: horizontal flip and translation of up to 12.5% (4 pixels) vertically and horizontally
weak = transforms.Compose([
  transforms.RandomHorizontalFlip(),
  transforms.RandomCrop(32, padding=4, padding_mode='reflect'),
])
# Strong augmentation: RandAugment followed by Cutout (substituted with RandomErasing)
strong = transforms.Compose([
  weak,
  transforms.RandAugment(num_ops=2, magnitude=10),
])
cutout = transforms.RandomErasing(p=1.0, scale=(0.02, 0.15), ratio=(1.0, 1.0), value=0)

base = datasets.CIFAR10(root='./data', train=True, download=True)
targets = np.array(base.targets)
rng = np.random.default_rng(0)
labeled_idx = np.concatenate([rng.choice(np.where(targets == c)[0], labels_per_class, replace=False) for c in range(10)])


class Labeled(Dataset):
  def __init__(self, idx):
    self.idx = idx

  def __len__(self):
    return len(self.idx)

  def __getitem__(self, i):
    img, y = base[self.idx[i]]
    return normalize(weak(img)), y


class Unlabeled(Dataset):
  """Return no label, only a weak and a strong augmentation (labeled images are included too)"""
  def __len__(self):
    return len(base)

  def __getitem__(self, i):
    img, _ = base[i]
    return normalize(weak(img)), cutout(normalize(strong(img)))


labeled_loader = DataLoader(Labeled(np.repeat(labeled_idx, 100)), batch_size=batch_size, shuffle=True, drop_last=True)
unlabeled_loader = DataLoader(Unlabeled(), batch_size=batch_size * mu, shuffle=True, drop_last=True, num_workers=4)
test_loader = DataLoader(datasets.CIFAR10('./data', train=False, transform=normalize), batch_size=256)


def endless(loader):
  while True:
    for batch in loader:
      yield batch


# Model (the paper uses Wide ResNet-28-2; here a ResNet-18 adapted to small images)
model = models.resnet18(num_classes=10)
model.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=1, padding=1, bias=False)
model.maxpool = nn.Identity()
model = model.to(device)

optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, nesterov=True, weight_decay=weight_decay)
# Learning rate: η cos(7πk / 16K)
scheduler = optim.lr_scheduler.LambdaLR(optimizer, lambda k: math.cos(7 * math.pi * k / (16 * total_steps)))

labeled_iter, unlabeled_iter = endless(labeled_loader), endless(unlabeled_loader)
model.train()
for step in tqdm(range(total_steps)):
  x, y = next(labeled_iter)
  u_weak, u_strong = next(unlabeled_iter)
  x, y, u_weak, u_strong = x.to(device), y.to(device), u_weak.to(device), u_strong.to(device)

  # Pass all three in a single forward pass (to keep batch normalization statistics consistent)
  logits = model(torch.cat([x, u_weak, u_strong]))
  logits_x = logits[:batch_size]
  logits_weak, logits_strong = logits[batch_size:].chunk(2)

  # ℓs: cross-entropy on labeled images
  loss_s = F.cross_entropy(logits_x, y)

  # ℓu: build pseudo-labels from weak-augmentation predictions and use only those with confidence ≥ τ
  with torch.no_grad():
    probs = logits_weak.softmax(dim=1)
    max_probs, pseudo = probs.max(dim=1)
    mask = (max_probs >= threshold).float()
  loss_u = (F.cross_entropy(logits_strong, pseudo, reduction='none') * mask).mean()

  loss = loss_s + lambda_u * loss_u
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()
  scheduler.step()

# Evaluation (the paper evaluates an exponential moving average of the weights)
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. How should the threshold τ be chosen?
A.

The paper's default is 0.95. In the paper's analysis (CIFAR-10, 250 labels), lowering the threshold increases the number of pseudo-labels but also their errors, and 0.95 gave the lowest error rate. Raising it to 0.97 or 0.99 does not change much. For pseudo-labels, quality matters more than quantity.

Q. Can it be used for data other than images?
A.

The idea carries over, but it assumes that a strong augmentation that "changes the appearance substantially without changing the meaning" is available. For images, RandAugment and Cutout can be used, but for text or audio an augmentation suited to the data (back-translation, SpecAugment, etc.) must be chosen. The paper also discusses replacing the strong augmentation with data-type-agnostic methods such as MixUp or adversarial perturbations.

Q. If a pseudo-label is wrong, won't the model learn the error?
A.

That risk exists. FixMatch reduces errors by using only high-confidence predictions. However, the paper's experiments also show that when labeled images are extremely few and atypical, training heads in the wrong direction from the start and does not work well.

References

  1. 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).
  2. Cubuk, E. D., Zoph, B., Shlens, J., & Le, Q. V. (2020). RandAugment: Practical Automated Data Augmentation with a Reduced Search Space. CVPR Workshops 2020.
  3. DeVries, T., & Taylor, G. W. (2017). Improved Regularization of Convolutional Neural Networks with Cutout. arXiv:1708.04552.