The Π-model and Temporal Ensembling are semi-supervised learning methods that train a model so that its answer does not change no matter how many times a slightly altered version of the same image is predicted. They were proposed together in a single paper by Laine and Aila of NVIDIA in 2017. Even with few labeled images, unlabeled images can be used directly for training.
Unlabeled images have no ground truth. Instead of a label, these methods use the property that "for the same image, the model's prediction should be the same even when the randomness of augmentation and dropout differs". For example, if a cat photo is shown twice with a slight shift and the model answers "cat 60%" the first time and "cat 40%, dog 25%" the second time, at least one of the answers is unstable. Training to reduce this discrepancy lets the model learn features that are robust to small changes in the image, even without labels.
The paper calls this idea "self-ensembling". Even a single network during training, when it predicts with different dropout and augmentation randomness, behaves like an ensemble that collects predictions from many slightly different networks.
The two methods differ in how the comparison partner (the target) is produced.
Π-model: Pass the same image through the model twice and pull the two predictions toward each other.
Temporal Ensembling: Pass the image through the model only once and pull the prediction toward the average of predictions for that image from past epochs.
This "consistency regularization" became the foundation for later methods such as Mean Teacher, UDA, MixMatch, and FixMatch.
Training Procedure and Loss
One training step of the Π-model proceeds in the following order, as in Algorithm 1 of the paper.
Pass each image xi in mini-batch B through the model fθ with stochastic augmentation g and dropout to obtain class probabilities zi=fθ(g(xi)).
Pass the same image through the model again with different augmentation and dropout randomness to obtain z~i.
On labeled images only, compute the cross-entropy with the label yi.
On all images, labeled or not, compute the squared error between zi and z~i.
Add the two losses with a weight w(t) and update the weights θ with Adam or a similar optimizer.
Here L is the set of labeled images, C is the number of classes, and zi[yi] is the probability of the correct class. Because zi and z~i are post-softmax probabilities, the second term is the mean squared error between probability vectors.
w(t) is the weight of the unlabeled loss. In the paper it is raised from 0 to its maximum over the first 80 epochs along the Gaussian curve exp[−5(1−T)2] (with T increasing linearly from 0 to 1).
Temporal Ensembling: Use the Average of Past Predictions as the Target
In Temporal Ensembling, each image passes through the model only once. The target z~i is built by accumulating that image's predictions from past epochs with the following equation (Algorithm 2 of the paper).
Zi←αZi+(1−α)zi,z~i=1−αtZi
Zi is an exponential moving average of the predictions; the larger α (0.6 in the paper), the longer predictions from older epochs persist. t is the epoch number. Because Z starts at 0, its values are biased toward small values during the first few epochs. Dividing by 1−αt corrects this bias, the same idea as the bias correction in Adam. In the first epoch there is no target yet, so w(t) is set to 0.
The following figure contrasts how the two methods build the consistency loss ℓu. The Π-model on the left passes the model twice and compares the two predictions; Temporal Ensembling on the right passes the model only once and compares the prediction with the average of past predictions.
The consistency loss compares the entire probability vector, not just the argmax (which class). The paper describes this as "pulling together the implicit knowledge of the two predictions" (what knowledge distillation calls dark knowledge). This is a much stronger constraint than only checking whether the predicted class matches. In the paper's experiments, squared error gave slightly but consistently better results than cross-entropy.
Why It Works
The paper explains why the consistency loss works as follows.
Prediction variation can be treated as an error: Since the underlying image is the same, two different predictions mean that at least one of them is wrong. Even without labels, reducing this discrepancy is a sensible objective.
The prediction function becomes flat near the data: The consistency loss keeps the output from changing when the input changes slightly near real images. As a result, decision boundaries avoid dense regions of the data, and images of the same class tend to cluster. The labeled images determine which class name each cluster gets.
It smooths only where the data is, not the whole input space: Unlike traditional regularization such as shrinking weights, it acts only near actual inputs.
The Temporal Ensembling target is more stable than that of the Π-model. The Π-model's target z~i is a single prediction and therefore noisy, whereas Temporal Ensembling averages predictions over many epochs, so the noise is smaller. Because the dropout randomness differs from epoch to epoch, this average approximates the prediction of an ensemble of many slightly different networks.
This property also brings robustness to label errors. In the paper's experiments (SVHN), standard supervised learning lost accuracy when only part of the labels was randomized. Temporal Ensembling, by contrast, was hardly affected even when half of the labels were random, and kept accuracy above 90% even when 80% were random.
Experimental Results
The paper measured error rates on CIFAR-10, SVHN, and CIFAR-100 using only part of the labels (average of 10 runs). Augmentation consists of horizontal flips (not used for SVHN) and translations of up to 2 pixels.
Dataset (number of labels)
Supervised only (with aug.)
Π-model (with aug.)
Temporal Ensembling (with aug.)
CIFAR-10 (4,000)
34.85%
12.36%
12.16%
SVHN (500)
31.59%
6.65%
5.12%
SVHN (1,000)
19.30%
4.82%
4.42%
CIFAR-100 (10,000)
44.56%
39.19%
38.65%
The fewer the labels, the larger the gap over supervised learning alone. On CIFAR-10 with 4,000 labels, the error rate dropped from 34.85% to 12.16%. Even the Π-model without augmentation reached 16.55%, beating the previous best at the time (18.63% from a GAN-based method).
With all labels, there was also a slight improvement. On CIFAR-10 with all 50,000 labels, the Π-model reached 5.56% compared with 6.05% for supervised learning with augmentation.
There is also an experiment adding unlabeled images from outside. Adding 500,000 randomly selected images from Tiny Images as unlabeled data to fully labeled CIFAR-100 lowered the Temporal Ensembling error rate from 26.30% to 23.62% (25.79% for the Π-model). Most of the added images did not belong to any CIFAR-100 class, yet they still helped. The paper suggests that inputs of the same kind (here, natural photos) are useful as unlabeled data.
Practical Considerations
It is important to raise the unlabeled loss weight w(t) slowly from 0. According to the paper, ramping up too quickly makes the model prone to a meaningless solution that "gives the same answer for every image", because the consistency loss can be driven to 0 by predicting the same output for all images. Keep the labeled loss dominant at the start of training.
Also keep the following in mind.
Dropout and augmentation are prerequisites: What makes the two predictions differ is the randomness of dropout and augmentation. Without either, the two predictions are identical, and the consistency loss teaches nothing. The paper's experiments use Gaussian input noise (standard deviation 0.15), dropout (probability 0.5), and flips and translations.
Scale the maximum weight by the label fraction: The paper sets the maximum of w(t) to wmax⋅M/N (M is the number of labeled images, N the total). wmax is 100 for the Π-model and usually 30 for Temporal Ensembling.
Temporal Ensembling needs storage for predictions: It stores one value per class for every training image (an N×C matrix). This grows with the dataset and the number of classes, but because it is read and written only once per epoch, the paper notes it can even be kept in a file on disk.
Temporal Ensembling updates targets slowly: Targets change only once per epoch, so on very large datasets it takes a long time for new learning to reach the targets. Mean Teacher later addressed this by "averaging weights instead of predictions".
Differences in flip randomness: The Π-model can use the same horizontal flip for both evaluations, while Temporal Ensembling flips independently each epoch. The paper reports that using the same flip was about 0.5 points better in its measurements.
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.
Method
Target prediction
Perturbation learned against
Distance between predictions
Forward passes per step (unlabeled images)
Π-model
Prediction from the same model with different noise
Prediction on weak augmentation (one-hot if above a threshold)
Strong augmentation
Cross-entropy
2
Guidelines for choosing:
Understanding the mechanism or starting with small experiments: The Π-model is the simplest. It can be written with a single model and squared error.
Reducing computation with a medium-sized dataset: Temporal Ensembling needs only one pass and has stable targets. However, it must store predictions for every image.
Large datasets, or targets updated every step: Averaging weights, as in Mean Teacher, is a better fit.
State-of-the-art accuracy: Methods such as FixMatch, which combine strong data augmentation with pseudo-labels, perform much better when labels are extremely scarce.
PyTorch example
▶Show code
python
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
"""
Losses of the Π-model and Temporal Ensembling (a small implementation following Algorithms 1 and 2 of the paper)
x: mini-batch of images (labeled and unlabeled mixed)
y: ground-truth classes; -1 for unlabeled images
idx: index of each image in the dataset (used by Temporal Ensembling)
"""
def rampup(epoch, length=80):
"""Ramp-up of w(t): from 0 to 1 along exp(-5(1-T)^2) over the first length epochs"""
if epoch >= length:
return 1.0
T = epoch / length
return math.exp(-5.0 * (1.0 - T) ** 2)
class Augment(nn.Module):
"""Stochastic augmentation g: horizontal flip, translation up to 2 pixels, Gaussian noise (σ = 0.15)"""
def forward(self, x):
flip = torch.rand(x.size(0), 1, 1, 1, device=x.device) < 0.5
x = torch.where(flip, x.flip(3), x)
pad = F.pad(x, (2, 2, 2, 2), mode="reflect")
dx, dy = torch.randint(0, 5, (2,)).tolist()
x = pad[:, :, dy:dy + x.size(2), dx:dx + x.size(3)]
return x + 0.15 * torch.randn_like(x)
def pi_model_loss(model, augment, x, y, w):
"""Π-model: pass the same images twice and take the squared error of post-softmax probabilities"""
z = model(augment(x)).softmax(dim=1) # 1st pass (augmentation and dropout noise A)
z_tilde = model(augment(x)).softmax(dim=1) # 2nd pass (noise B)
labeled = y >= 0
loss_s = F.nll_loss(z[labeled].clamp_min(1e-8).log(), y[labeled], reduction="sum") / x.size(0)
loss_u = ((z - z_tilde) ** 2).sum(dim=1).mean() / z.size(1) # 1/(C|B|) Σ ||z - z~||^2
return loss_s + w * loss_u
class TemporalEnsembling:
"""Temporal Ensembling: use the average Z of predictions from past epochs as the target"""
def __init__(self, num_images, num_classes, alpha=0.6, device="cpu"):
self.alpha = alpha
self.Z = torch.zeros(num_images, num_classes, device=device) # exponential moving average of predictions
self.z_epoch = torch.zeros(num_images, num_classes, device=device) # predictions in this epoch
self.z_tilde = torch.zeros(num_images, num_classes, device=device) # targets (after bias correction)
def loss(self, model, augment, x, y, idx, w):
z = model(augment(x)).softmax(dim=1) # pass through the model only once
self.z_epoch[idx] = z.detach()
labeled = y >= 0
loss_s = F.nll_loss(z[labeled].clamp_min(1e-8).log(), y[labeled], reduction="sum") / x.size(0)
loss_u = ((z - self.z_tilde[idx]) ** 2).sum(dim=1).mean() / z.size(1)
return loss_s + w * loss_u
def end_of_epoch(self, t):
"""t is the number of the epoch that just ended (counting from 1)"""
self.Z = self.alpha * self.Z + (1 - self.alpha) * self.z_epoch
self.z_tilde = self.Z / (1 - self.alpha ** t) # correct the bias from starting at 0
# Usage example (paper settings: Adam, max learning rate 0.003, 300 epochs, batch 100)
# num_labeled, num_images are the number of labeled images and the total
# w_max = 100 (Π-model; 30 for Temporal Ensembling)
# for epoch in range(1, 301):
# model.train() # enable dropout (so the two predictions differ)
# w = w_max * num_labeled / num_images * rampup(epoch - 1) # 0 in the first epoch
# for x, y, idx in loader:
# loss = pi_model_loss(model, augment, x, y, w)
# # for Temporal Ensembling: loss = te.loss(model, augment, x, y, idx, w)
# optimizer.zero_grad(); loss.backward(); optimizer.step()
# # for Temporal Ensembling: te.end_of_epoch(epoch)
# model.eval() # at evaluation, disable dropout and apply no augmentation
FAQ
Q. Which should be used, the Π-model or Temporal Ensembling?
A.
In the paper's experiments, for the same number of epochs, Temporal Ensembling was slightly more accurate and needed about half the computation (error rates of 12.36% versus 12.16% on CIFAR-10 with 4,000 labels, and 6.65% versus 5.12% on SVHN with 500 labels). However, it must store the predictions Z for every image (number of images × number of classes) and adds a new hyperparameter α. When the dataset is large and storage is difficult, or when a simpler mechanism is preferred, the Π-model is easier to handle.
Q. Why compare with squared error instead of cross-entropy?
A.
In the paper, squared error gave slightly but consistently better results than cross-entropy. The later MixMatch also uses squared error for the unlabeled loss, and its paper gives the reason that "unlike cross-entropy, it is bounded and less sensitive to completely incorrect predictions". On unlabeled images the target itself is uncertain, so this property helps.
Q. Is it useful even when all labels are available?
A.
In the paper, the error rate dropped slightly even with all labels (from 6.05% to 5.56% on CIFAR-10). It is also very effective on data with many label errors: on SVHN, Temporal Ensembling kept accuracy above 90% even when 80% of the labels were randomized. This is because the consistency loss acts as a regularizer that makes the model less likely to be dragged along by wrong labels.