AI Logic

Semi-Supervised Learning

UDA

Updated:

Training flow of UDA. The left side shows the overall flow: the cross-entropy on labeled images and the consistency loss on unlabeled images are added to update the model. The right side shows the inside: from the predictions on simply augmented unlabeled images, only those whose confidence exceeds a threshold are sharpened with a temperature to become targets, and the cross-entropy with the predictions on strongly augmented images is taken

Background and Overview

UDA (Unsupervised Data Augmentation) is a semi-supervised learning method that applies strong data augmentation to unlabeled data and trains the model so that its predictions are the same before and after augmentation. It was published in 2019 by Xie et al. of Google and Carnegie Mellon University and accepted at NeurIPS 2020.

Earlier consistency regularization methods (Π-model, VAT, etc.) added simple noise such as Gaussian noise or small translations to unlabeled images and trained the model so that its predictions did not change. The UDA paper focused on this "quality of noise" and argued that using strong data augmentation, whose effectiveness had been established in supervised learning, as the noise would make semi-supervised learning much better.

The data augmentation used depends on the type of data:

  • Images: RandAugment (randomly selects and applies transformations such as rotation, color changes, and distortions).
  • Text: Back-translation (translates English into French and back into English to produce a paraphrase) and replacement of unimportant words (words with low TF-IDF are replaced with other words).

For example, if the model answers "cat 84%" for an unlabeled cat photo with only a light crop, it is trained to give the same answer for the same photo after a large rotation and a color change. The stronger the augmentation, the better the model learns to recognize "the same thing" across large differences in appearance.

With this simple substitution, the error rate on CIFAR-10 with 4,000 labels became 4.32%, nearly matching supervised learning with all labels (50,000 images). On text, UDA reached a 4.20% error rate on IMDb sentiment classification with only 20 labels, beating the previous best model trained on all labels. UDA's pattern of "build targets from weak augmentation and learn from strong augmentation" became the basis for the later FixMatch.

Training Procedure and Loss

As in Eq. (1) of the paper, the UDA objective is the sum of the cross-entropy on labeled data and the consistency loss on unlabeled data.

min⁡θ Ex1∼pL(x)[−log⁡pθ(f∗(x1)∣x1)]+λ Ex2∼pU(x) Ex^∼q(x^∣x2)[CE(pθ~(y∣x2) ∥ pθ(y∣x^))]\min_\theta\ \mathbb{E}_{x_1 \sim p_L(x)}\left[-\log p_\theta(f^*(x_1) \mid x_1)\right] + \lambda\, \mathbb{E}_{x_2 \sim p_U(x)}\, \mathbb{E}_{\hat{x} \sim q(\hat{x} \mid x_2)}\left[\mathrm{CE}\left(p_{\tilde{\theta}}(y \mid x_2) \,\|\, p_\theta(y \mid \hat{x})\right)\right]

Here f∗(x1)f^*(x_1) is the ground-truth label, q(x^∣x)q(\hat{x} \mid x) is the data augmentation, and θ~\tilde{\theta} is a fixed copy of the current weights θ\theta. No gradient flows through θ~\tilde{\theta}, so the target-side prediction is treated as a constant (following VAT). In most of the paper's experiments, λ=1\lambda = 1.

Combining Section 2 and the appendix settings of the paper, one training step in the image experiments proceeds in the following order.

  1. Apply simple augmentation (crop and flip) to 64 labeled images and compute the cross-entropy with the labels.
  2. Apply the same simple augmentation to 448 unlabeled images and predict them with the model at its current weights (no gradient).
  3. Exclude from the consistency loss any image whose maximum predicted probability is at or below a threshold β\beta (0.8 for CIFAR-10 and SVHN).
  4. Sharpen the predictions of the remaining images with temperature τ\tau (0.4) to make the targets.
  5. Apply RandAugment to the same unlabeled images, predict them, and compute the cross-entropy with the targets.
  6. Add the two losses and update the weights.

Including steps 3 and 4, the unlabeled loss for a mini-batch BB is as follows.

1∣B∣∑x∈B1(max⁡y′pθ~(y′∣x)>β)CE(pθ~(sharp)(y∣x) ∥ pθ(y∣x^)),pθ~(sharp)(y∣x)=exp⁡(zy/τ)∑y′exp⁡(zy′/τ)\frac{1}{|B|} \sum_{x \in B} \mathbb{1}\left(\max_{y'} p_{\tilde{\theta}}(y' \mid x) > \beta\right) \mathrm{CE}\left(p^{(\mathrm{sharp})}_{\tilde{\theta}}(y \mid x) \,\|\, p_\theta(y \mid \hat{x})\right), \qquad p^{(\mathrm{sharp})}_{\tilde{\theta}}(y \mid x) = \frac{\exp(z_y / \tau)}{\sum_{y'} \exp(z_{y'} / \tau)}

zyz_y is the logit (pre-softmax value) of class yy. Dividing by τ<1\tau < 1 makes high-probability classes higher and low-probability classes lower, so the target becomes sharper.

Because the target-side prediction is a constant with no gradient, the cross-entropy here differs from the KL divergence between target and prediction only by a constant. Either way, the quantity updated during training is the same.

A Training Technique to Compensate for Scarce Labels: TSA

When labeled data is extremely scarce, the model tends to quickly overfit the labeled data before it has learned anything from the unlabeled data. As a countermeasure, the paper also proposes TSA (Training Signal Annealing). A threshold ηt\eta_t is set for each training step tt, and labeled examples whose probability for the correct class already exceeds ηt\eta_t are removed from the loss. With KK classes, ηt\eta_t is raised from 1/K1/K to 1 according to the following equation.

ηt=αt(1−1K)+1K\eta_t = \alpha_t \left(1 - \frac{1}{K}\right) + \frac{1}{K}

There are three schedules for αt\alpha_t: logarithmic (1−exp⁡(−5t/T)1 - \exp(-5t/T)), linear (t/Tt/T), and exponential (exp⁡(5(t/T−1))\exp(5(t/T - 1))), where TT is the total number of steps. The more prone the model is to overfitting, the better the exponential schedule, which holds back the training signal until late in training, is said to work.

Why It Works

The paper summarizes why strong data augmentation is good noise for consistency regularization in three points.

  • Valid noise: Data augmentation that works well in supervised learning produces natural images with the same label as the original. Making predictions agree before and after augmentation is therefore safe.
  • Diverse noise: Strong data augmentation can change the input substantially without changing the label. Gaussian noise only produces small nearby changes. The more diverse the images on which predictions are made to agree, the more can be learned from little data.
  • Task-appropriate inductive bias: Each task needs a different inductive bias (for images, for example, "a rotated object is still the same object"). Augmentations that work in supervised learning supply the inductive bias that the task lacks.

The paper explains this with a graph. If data points are nodes and two points reachable from each other by data augmentation are connected by an edge, points of the same class form connected components. If a component contains even one labeled point, the consistency loss spreads the label over the whole component. Strong and diverse augmentation adds edges and reduces the number of components, which reduces the number of labels needed. The paper proves as a theorem that the number of labels needed is determined by the number of components.

Experiments also support this idea. Changing the type of augmentation on CIFAR-10, augmentations with lower error rates in supervised learning (all 50,000 images) also gave lower error rates in semi-supervised learning (4,000 labels).

AugmentationSupervised (50,000)Semi-supervised (4,000)
Crop and flip5.36%10.94%
Cutout4.42%5.43%
RandAugment4.23%4.32%

Reducing the number of transformation types used in RandAugment also increased the error rate, showing that diversity matters.

Experimental Results

The paper compared methods on CIFAR-10 with different numbers of labels using the same network (Wide-ResNet-28-2) (error rate). The values for the compared methods are taken by the paper from the MixMatch paper.

Number of labelsVATMean TeacherMixMatchUDA
25036.03%47.32%11.08%5.43%
1,00018.68%17.32%7.75%4.75%
4,00011.05%10.36%6.24%4.32%

The fewer the labels, the larger the gap, and even with 250 labels the error rate was 5.43%. On SVHN (1,000 labels), UDA reached 2.23%, below the 2.84% of the paper's supervised learning with all labels (73,257 images, without RandAugment). With larger networks on CIFAR-10 with 4,000 labels, Shake-Shake reached 3.7% and PyramidNet (with ShakeDrop) 2.7%. The 2.7% equals the value of the same network trained supervised on all labels (50,000 images, without RandAugment).

UDA was also effective on ImageNet (ResNet-50).

SettingResNet-50ResNet-50 with RandAugmentUDA
10% labels (top-1 / top-5 accuracy)55.09% / 77.26%58.84% / 80.56%68.78% / 88.80%
100% labels + 1.3M external unlabeled images77.28% / 93.73%78.43% / 94.37%79.05% / 94.49%

For text classification, UDA was evaluated in combination with BERT. On IMDb sentiment classification with 20 labels, UDA starting from BERT further pretrained on unlabeled text reached an error rate of 4.20%, beating the previous best (4.32%) trained on all 25,000 labels.

Practical Considerations

The effectiveness of UDA depends on the quality of the data augmentation. If the augmentation changes the label (for example, horizontally flipping images of digits, or a paraphrase reversing the meaning of a sentence), the model learns the wrong consistency. The paper also notes a trade-off between "diversity" and "validity (not changing the label)" in augmentation, and that tuning it helps. For back-translation, a sampling temperature of 0.7–0.9 gave the best results.

Also keep the following in mind.

  • The amount of unlabeled data matters: In the paper's study, reducing unlabeled data hurt performance more than reducing labeled data by the same proportion. On CIFAR-10 with 4,000 labels, reducing the unlabeled images from 50,000 to 5,000 raised the error rate from 4.32% to 13.19%.
  • Use a large unlabeled batch: The paper's CIFAR-10 and SVHN settings use 448 unlabeled images for every 64 labeled images. Most of the computation is on the unlabeled side.
  • Confidence masking and sharpening are auxiliary techniques: The threshold β\beta and temperature τ\tau are additional techniques that the paper reports as "helpful": β=0.8\beta = 0.8 and τ=0.4\tau = 0.4 for CIFAR-10 and SVHN, and β=0.5\beta = 0.5 for ImageNet.
  • Select unlabeled data with a different distribution: Using data with a different class distribution as is can hurt performance. The paper uses a method that selects examples with high per-class probability under a trained model (selecting in-domain data).
  • When generating augmentations in advance: To reduce training time, the paper precomputed and stored 100 augmentations for each unlabeled CIFAR-10 image. However, it notes that generating them on the fly during training is equal or better in terms of diversity.

Comparison with Other Semi-Supervised Methods

Semi-supervised methods based on consistency regularization compare as follows in how targets are built and how the input is changed on the training side.

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 several weak augmentationsWeak augmentation + MixUpSharpeningSquared error
UDAPrediction on weak augmentationStrong augmentation (RandAugment, back-translation)Sharpening (low-confidence ones are discarded)Cross-entropy
FixMatchPrediction on weak augmentationStrong augmentationOne-hot if above a thresholdCross-entropy

The UDA paper states that the essential difference from VAT is only how the noise is generated, and since UDA outperformed VAT under every label count, it argues for the superiority of data augmentation noise. VAT noise tends to contain fine patterns that do not appear in real images, whereas data augmentation produces diverse, natural images.

Guidelines for choosing:

  • Images or text with good data augmentation available: UDA and FixMatch are a good fit. UDA has also been shown to work on text (back-translation).
  • A simpler mechanism is wanted: FixMatch combines UDA's sharpening and confidence masking into thresholded one-hot pseudo-labels, which reduces the number of hyperparameters.
  • Data for which label-preserving augmentations are hard to define: Methods such as VAT, which do not require designing augmentations, are candidates.

PyTorch example

Show code
python
import math
import torch
import torch.nn.functional as F
from torchvision import transforms

"""
UDA loss (a small implementation following Eq. (1) of the paper, confidence masking and sharpening in Section 2.4, and TSA in Appendix A.1)
Image example. For text, replace strong with back-translation or similar
"""

# Simple augmentation (target side and labeled images) and strong augmentation (training side)
weak = transforms.Compose([
  transforms.RandomCrop(32, padding=4, padding_mode="reflect"),
  transforms.RandomHorizontalFlip(),
])
strong = transforms.Compose([
  weak,
  transforms.RandAugment(num_ops=2, magnitude=10),
])


def tsa_threshold(step, total_steps, num_classes, schedule="exp"):
  """TSA threshold η_t = α_t (1 - 1/K) + 1/K"""
  r = step / total_steps
  if schedule == "log":
    alpha = 1 - math.exp(-r * 5)
  elif schedule == "linear":
    alpha = r
  else:  # "exp"
    alpha = math.exp((r - 1) * 5)
  return alpha * (1 - 1 / num_classes) + 1 / num_classes


def uda_loss(model, x_l, y_l, u_weak, u_strong, step, total_steps,
             lam=1.0, beta=0.8, tau=0.4, use_tsa=False):
  """x_l, y_l: labeled (already simply augmented). u_weak, u_strong: simple and strong augmentations of the same unlabeled images"""
  model.train()
  logits_l = model(x_l)
  logits_strong = model(u_strong)
  with torch.no_grad():                     # θ~: a fixed copy of the current weights. No gradient
    logits_weak = model(u_weak)

  # supervised loss (with TSA, drop examples whose correct-class probability exceeds η_t)
  loss_s = F.cross_entropy(logits_l, y_l, reduction="none")
  if use_tsa:
    eta = tsa_threshold(step, total_steps, logits_l.size(1))
    p_correct = logits_l.softmax(dim=1).gather(1, y_l[:, None]).squeeze(1)
    keep = (p_correct < eta).float()
    loss_s = (loss_s * keep).sum() / keep.sum().clamp_min(1.0)
  else:
    loss_s = loss_s.mean()

  # consistency loss: only for images with confidence above β, use the prediction sharpened with temperature τ as the target
  probs = logits_weak.softmax(dim=1)
  mask = (probs.max(dim=1).values > beta).float()
  target = (logits_weak / tau).softmax(dim=1)
  ce = -(target * logits_strong.log_softmax(dim=1)).sum(dim=1)
  loss_u = (ce * mask).mean()

  return loss_s + lam * loss_u


# Paper's CIFAR-10 setting (Wide-ResNet-28-2): 64 labeled and 448 unlabeled images,
# SGD (Nesterov momentum 0.9), learning rate decayed with cos(7πt / 16T), 500k steps,
# evaluation with an exponential-moving-average (0.9999) model of the weights

FAQ

Q. How do UDA and FixMatch differ?
A.

Both "use the prediction on weak augmentation as the target and match the prediction on strong augmentation to it". UDA makes the target a probability distribution sharpened with temperature τ\tau and excludes images whose confidence is at or below the threshold β\beta. FixMatch simplifies this by turning predictions above a threshold into one-hot pseudo-labels. In the FixMatch paper, FixMatch greatly outperforms UDA under very low-label settings such as 40 labels on CIFAR-10.

Q. How is it used on text data?
A.

As strong augmentation, it uses back-translation (English → French → English to produce paraphrases) and replacement of words with low TF-IDF. For back-translation, it is important to produce diverse paraphrases with random sampling at a temperature rather than beam search, and a temperature of 0.7–0.9 gave the best results. The paper shows that even starting from BERT, UDA further lowers the error rate, so it can be combined with pretraining.

Q. Which helps more: adding labeled images or adding unlabeled images?
A.

In the paper's study on CIFAR-10 and SVHN, when both were reduced by the same proportion, reducing unlabeled images hurt performance more. For example, on CIFAR-10 with 50,000 unlabeled images, even 250 labels gave a 5.43% error rate, but with only 5,000 unlabeled images, even 4,000 labels gave 13.19%. Collecting enough unlabeled data is especially important for UDA.

References

  1. Xie, Q., Dai, Z., Hovy, E., Luong, M.-T., & Le, Q. V. (2020). Unsupervised Data Augmentation for Consistency Training. 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. 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).