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.
Sample B labeled images and μB unlabeled images (μ is the ratio of unlabeled images).
Apply weak data augmentation α to the labeled images and compute the cross-entropy ℓs against the ground truth.
Apply weak data augmentation to the unlabeled image ub, run the model, and obtain the class probabilities qb=pm(y∣α(ub)).
If the maximum of qb is at least the threshold τ, take the most probable class q^b=argmax(qb) as the pseudo-label. If it is below τ, the image is not used in this step.
Apply strong data augmentation A to the same ub, run the model, and compute the cross-entropy against the pseudo-label. This is ℓu.
Update the model weights to minimize ℓs+λuℓu.
The losses in steps 2 and 5 are written as follows.
Here xb and pb are a labeled image and its ground truth, pm(y∣⋅) is the class probability output by the model, H is the cross-entropy, and 1(⋅) 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.
Item
Value
Meaning
Threshold τ
0.95
Only predictions with at least this confidence become pseudo-labels
Weight of the unlabeled loss λu
1
Kept constant throughout training rather than ramped up
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 τ, so ℓ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 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).
Method
Augmentation for creating the artificial label
Augmentation for training
Post-processing of the artificial label
Π-model
Weak
Weak
None
Mean Teacher
Weak
Weak
None (predicted by an exponential-moving-average model)
Sharpening (low-confidence predictions are not used)
MixMatch
Weak
Weak
Sharpening (averaging several predictions)
ReMixMatch
Weak
Strong
Sharpening
FixMatch
Weak
Strong
Pseudo-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.