AI Logic

Semi-Supervised Learning

Mean Teacher

Updated:

Training flow of Mean Teacher. The left side shows the overall flow: the cross-entropy on labeled images and the consistency loss on all images are added to update the student's weights, and then the teacher's weights are updated as an exponential moving average of the student's weights. The right side shows the inside: the same image passes through the teacher and student models with different random noise, and the squared error between the two predictions is taken

Background and Overview

Mean Teacher is a semi-supervised learning method that also learns from unlabeled images by using as targets the predictions of a "teacher" model built by averaging the weights of the model being trained. It was proposed in 2017 by Tarvainen and Valpola at The Curious AI Company.

It builds on "consistency regularization", which trains a model so that its prediction does not change when the same image is slightly altered. The Π-model and Temporal Ensembling used as targets another prediction from the same model or the average of predictions from past epochs. Mean Teacher improved on this by making the model that produces the targets itself better.

The mechanism runs two models side by side.

  • Student model: The model trained in the usual way. Its weights are updated so that it matches the labels on labeled images and the teacher's predictions on all images.
  • Teacher model: Same architecture as the student, with weights equal to an exponential moving average of the student's weights. It is not trained; each time the student takes a step, its weights move slightly toward the student's.

As an analogy, the teacher is "the average of the student over the last few thousand steps". The student's weights at any single step fluctuate with mini-batch bias, but averaging cancels out the fluctuations and yields more accurate predictions. Using these stable predictions as targets lets the student learn from good targets, and the improved student in turn improves the teacher, creating a virtuous cycle.

In the paper, with the same network as Temporal Ensembling, it reached a 4.35% error rate on SVHN with 250 labels. This is lower than the 4.42% that Temporal Ensembling achieved with 1,000 labels. The idea of building the teacher from averaged weights was later adopted for the target network in self-supervised methods such as BYOL and DINO.

Training Procedure and Loss

One training step of Mean Teacher proceeds in the following order, as in Figure 2 of the paper.

  1. Apply student-side noise η\eta (augmentation, input noise, dropout) to the mini-batch images xx and pass them through the student model θ\theta to obtain class probabilities.
  2. Apply different noise η′\eta' to the same images and pass them through the teacher model θ′\theta' to obtain the teacher's predictions. The teacher's predictions are used only as targets, and no gradient flows through them.
  3. On labeled images only, compute the cross-entropy between the student's predictions and the labels.
  4. On all images, labeled or not, compute the squared error between the student's and the teacher's predictions (the consistency loss).
  5. Add the two losses with a weight w(t)w(t) and update the student's weights θ\theta with Adam or a similar optimizer.
  6. Update the teacher's weights as an exponential moving average using the updated student weights.

The consistency loss in step 4 and the teacher update in step 6 are written as follows.

J(θ)=Ex,η′,η[∥f(x,θ′,η′)−f(x,θ,η)∥2],θt′=α θt−1′+(1−α) θtJ(\theta) = \mathbb{E}_{x, \eta', \eta}\left[ \left\| f(x, \theta', \eta') - f(x, \theta, \eta) \right\|^2 \right], \qquad \theta'_t = \alpha\, \theta'_{t-1} + (1-\alpha)\, \theta_t

Here f(x,θ,η)f(x, \theta, \eta) is the post-softmax probability output by the model, tt is the training step, and α\alpha is the coefficient that controls the degree of averaging. The closer α\alpha is to 1, the longer the teacher remembers past student weights. In the paper's CIFAR-10 experiments, α=0.999\alpha = 0.999, which corresponds roughly to averaging the student over the most recent 1,000 steps.

As in the Π-model, the consistency weight w(t)w(t) starts at 0 and is raised to its maximum over the first 40,000 steps following e−5(1−x)2e^{-5(1-x)^2} (with xx increasing from 0 to 1).

The only difference among the Π-model, Temporal Ensembling, and Mean Teacher is how the teacher prediction f(x,θ′,η′)f(x, \theta', \eta') is produced. The Π-model uses θ′=θ\theta' = \theta (the same weights) and backpropagates through both sides. Temporal Ensembling substitutes the average of predictions from past epochs. Mean Teacher sets θ′\theta' to an exponential moving average of the student's weights and, like Temporal Ensembling, treats the teacher as a constant.

Why It Works

The paper explains the effectiveness of Mean Teacher in terms of "target quality".

  • Reduces the problem of believing its own mistakes: In consistency regularization, the model creates its own targets. If a target is wrong and its weight is too large, the model keeps fitting the error and stops learning new things (the paper calls this "confirmation bias"). Better targets ease this problem.
  • Averaged weights tend to be more accurate than the final weights: Averaging weights over training steps is known to often yield a more accurate model than using the final weights directly. The teacher is this averaged model, so it can produce better targets than the student.
  • Targets are refreshed every step: In Temporal Ensembling, each image's target is updated only once per epoch. Mean Teacher's teacher is updated every step, so what has been learned is reflected in the targets immediately. The larger the dataset, the wider this gap.
  • Intermediate representations are averaged too, not just outputs: Because weights are averaged, not only the final predictions but also the representations in intermediate layers come from the averaged model.

In the paper's learning curves (SVHN, 500 labels), the teacher's error rate stayed below the student's, showing a cycle in which the teacher improves the student and the student improves the teacher. Breaking this cycle slowed learning and made overfitting start earlier. On the other hand, when all labels were used, Mean Teacher and the Π-model behaved almost identically. Mean Teacher helps when labels are scarce.

Experimental Results

The paper first compared methods using the same 13-layer convolutional network as the Π-model and Temporal Ensembling (error rate, average of 10 runs, with augmentation).

Dataset (number of labels)Supervised onlyΠ-modelTemporal EnsemblingMean Teacher
SVHN (250)27.77%9.69%—4.35%
SVHN (500)16.88%6.83%5.12%4.18%
SVHN (1,000)12.32%4.95%4.42%3.95%
CIFAR-10 (1,000)46.43%27.36%—21.55%
CIFAR-10 (4,000)20.66%13.20%12.16%12.31%

The supervised-only and Π-model values are the paper authors' reimplementations, and the Temporal Ensembling values come from the paper by Laine and Aila. On SVHN, Mean Teacher was lowest in every setting, and on CIFAR-10 with 4,000 labels it was about the same as Temporal Ensembling. In the same table, virtual adversarial training (VAT) combined with entropy minimization outperforms Mean Teacher, with 3.86% on SVHN with 1,000 labels and 10.55% on CIFAR-10 with 4,000 labels. The paper regards VAT and Mean Teacher as separate improvements that can be combined.

With stronger networks, the results improved substantially.

SettingPrevious bestMean Teacher
CIFAR-10 (4,000 labels), 26-layer ResNet (with Shake-Shake regularization)10.55%6.28%
ImageNet 2012 (10% labels), 152-layer ResNeXt35.24%9.11%

In an experiment adding more unlabeled images (SVHN, 500 labels), the error rate fell from 4.18% to 3.02% and 2.46% as 100,000 and then 500,000 unlabeled images were added. Large amounts of unlabeled data can be used as is.

Practical Considerations

The consistency loss weight and the moving-average coefficient α\alpha strongly affect the results. In the paper's study (SVHN, 250 labels), the good range for each spanned roughly one order of magnitude, and performance dropped sharply outside it. When applying the method to your own data, it is safest to search near the paper's values.

Also keep the following in mind.

  • Noise is necessary: Even with an averaged teacher, performance was poor without either augmentation or dropout. Gaussian input noise had no effect when augmentation was used. Dropout on the teacher side gave only a slight improvement over using it on the student side alone.
  • Change α\alpha during training: Early in training the student improves quickly, so the teacher should forget old weights quickly; later it is better to remember longer. In the paper's SVHN experiments, α=0.99\alpha = 0.99 during the first 40,000 ramp-up steps and 0.9990.999 afterward.
  • Use the teacher for evaluation: The paper evaluates with the exponential-moving-average model (the teacher), because at the end of training the teacher's predictions are more often correct.
  • Memory grows by the teacher's weights: The teacher is the same size as the student, so a second set of weights is kept. Unlike Temporal Ensembling, however, no storage proportional to the number of training images is needed.
  • Squared error is the default distance: In an experiment that gradually varied the distance between teacher and student predictions from squared error to KL divergence, squared error gave the best results. The paper states that the reason is not clear. The ImageNet experiments, however, use KL divergence.

Comparison with Other Semi-Supervised Methods

Semi-supervised methods based on consistency regularization compare as follows in how targets are built and how much computation they need.

MethodTarget predictionPerturbation learned againstDistance between predictionsHow often the target is refreshed
Π-modelPrediction from the same model with different noiseAugmentation and dropoutSquared errorEvery step (gradient also flows)
Temporal EnsemblingAverage of predictions from past epochsAugmentation and dropoutSquared errorOnce per epoch for each image
Mean TeacherPrediction of the model with exponentially averaged weightsAugmentation and dropoutSquared errorEvery step
VATPrediction on the unperturbed imageSmall perturbation in the direction that changes the prediction mostKL divergenceEvery step
FixMatchPrediction on weak augmentation (one-hot if above a threshold)Strong augmentationCross-entropyEvery step

Guidelines for choosing:

  • Large datasets, or data arriving during training: Mean Teacher is a good fit. Unlike Temporal Ensembling, it does not need to store predictions for every image, and its targets are refreshed every step.
  • Designing how noise is injected: VAT focuses on "how to perturb" rather than on the target side. The paper says it can be combined with Mean Teacher.
  • Extremely few labels, or state-of-the-art accuracy: Methods such as FixMatch, which use strong data augmentation and pseudo-labels, achieve higher accuracy. Evaluating with an exponential-moving-average model is also used in FixMatch.

PyTorch example

Show code
python
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
One Mean Teacher step (a small implementation following Figure 2 and the equations of the paper)
x: mini-batch of images (labeled and unlabeled mixed)
y: ground-truth classes; -1 for unlabeled images
"""


def sigmoid_rampup(step, length=40000):
  """Ramp-up of the consistency loss weight: exp(-5(1-x)^2), x from 0 to 1"""
  if step >= length:
    return 1.0
  x = step / length
  return math.exp(-5.0 * (1.0 - x) ** 2)


def make_teacher(student):
  """The teacher has the same architecture as the student. Its weights are not trained (no gradient)"""
  teacher = copy.deepcopy(student)
  for p in teacher.parameters():
    p.requires_grad_(False)
  return teacher


@torch.no_grad()
def update_teacher(teacher, student, alpha):
  """θ' ← α θ' + (1 - α) θ (call after updating the student's weights)"""
  for t, s in zip(teacher.parameters(), student.parameters()):
    t.mul_(alpha).add_(s, alpha=1 - alpha)
  # copy statistics such as batch norm running averages
  for t, s in zip(teacher.buffers(), student.buffers()):
    t.copy_(s)


def train_step(student, teacher, augment, optimizer, x, y, step, w_max=1.0):
  student.train()
  teacher.train()  # apply dropout and noise to the teacher too (noise η')

  student_logits = student(augment(x))           # noise η
  with torch.no_grad():
    teacher_prob = teacher(augment(x)).softmax(dim=1)   # noise η'. Used only as the target

  # ℓs: cross-entropy on labeled images only
  labeled = y >= 0
  loss_s = F.cross_entropy(student_logits[labeled], y[labeled]) if labeled.any() else student_logits.sum() * 0

  # ℓu: squared error between post-softmax probabilities on all images
  loss_u = F.mse_loss(student_logits.softmax(dim=1), teacher_prob)

  loss = loss_s + w_max * sigmoid_rampup(step) * loss_u
  optimizer.zero_grad()
  loss.backward()
  optimizer.step()

  # SVHN setting: α = 0.99 for the first 40,000 steps, 0.999 afterward
  alpha = 0.99 if step < 40000 else 0.999
  update_teacher(teacher, student, alpha)
  return loss.item()


# Usage example
# student = MyConvNet()                     # model with dropout
# teacher = make_teacher(student)
# optimizer = torch.optim.Adam(student.parameters(), lr=0.003, betas=(0.9, 0.999))
# for step, (x, y) in enumerate(loader):
#   train_step(student, teacher, augment, optimizer, x, y, step)
# teacher.eval()                            # evaluate with the teacher (the weight-averaged model)

FAQ

Q. How should the moving-average coefficient $\alpha$ be chosen?
A.

The paper uses 0.9990.999 in the convolutional network experiments (0.990.99 only for the first 40,000 steps on SVHN), 0.970.97 (1,000 labels) and 0.990.99 (4,000 labels) for ResNet on CIFAR-10, and 0.99970.9997 on ImageNet. A larger α\alpha makes the teacher more stable but slows down how quickly the student's progress is reflected. The good range spans about one order of magnitude, so trying 0.990.99 and 0.9990.999 first is a reasonable starting point.

Q. Why apply different augmentations to the same image for the teacher and the student?
A.

According to the paper, adding noise to the teacher as well makes each individual prediction fluctuate, but their average tends to be closer to the correct answer. The student then learns toward the average of the fluctuating teacher predictions, which reduces bias in the targets. In the experiments, however, teacher-side dropout had only a small effect when augmentation was used.

Q. How does it differ from [knowledge distillation](/model-compression/knowledge-distillation)?
A.

Both use the teacher's softmax output as the student's target. The paper describes the difference as follows: knowledge distillation is performed after the teacher has finished training, whereas consistency regularization is performed during training. Mean Teacher's teacher is not a separately trained model but the average of the student's weights during training, and it improves together with the student.

References

  1. Tarvainen, A., & Valpola, H. (2017). Mean teachers are better role models: Weight-averaged consistency targets improve semi-supervised deep learning results. Advances in Neural Information Processing Systems 30 (NIPS 2017).
  2. Laine, S., & Aila, T. (2017). Temporal Ensembling for Semi-Supervised Learning. International Conference on Learning Representations (ICLR 2017).