Consistency, Label Spreading and Teacher-Student Training
Pseudo-labelling turns a model's confident guesses into labels. The methods in this lesson use unlabelled data more gently. They do not ask "what is the label of this point?" but "should these two predictions agree?". A digit shifted by one pixel is the same digit; two points joined by a chain of close neighbours probably share a class. Asking the model to be consistent across such pairs uses the unlabelled data without committing to hard labels too early. Three families follow from that idea: graph-based label spreading, consistency regularisation, and teacher-student training.
Label spreading: consistency over a graph
Build a graph whose nodes are all the points, labelled and unlabelled, with edge weights (and ). Let be the diagonal matrix of row sums, the normalised graph, and the matrix with a one-hot row for every labelled point and a zero row for every unlabelled one. Label spreading (Zhou et al., 2004) iterates
Each step, every node takes a weighted average of its neighbours' label scores () and is pulled back towards its own original label (). For the iteration converges to , which minimises a trade-off between smoothness over the graph (connected points get similar scores) and fitting the given labels. sets the balance: near 1, labels travel far along the graph; near 0, they barely leave their own node. (Label propagation, the older variant, clamps the labelled points exactly instead of pulling them back.)
The classic test is two interleaved moons with one label per moon: no straight line and no nearest-neighbour rule can get the shape from two points, but the unlabelled points draw the moons for you.
import numpy as np
from sklearn.datasets import make_moons
from sklearn.semi_supervised import LabelSpreading
from sklearn.neighbors import KNeighborsClassifier
X, y = make_moons(n_samples=300, noise=0.1, random_state=0)
rng = np.random.default_rng(0)
lab = np.array([rng.choice(np.where(y == c)[0]) for c in (0, 1)]) # one label per moon
y_semi = np.full(len(y), -1); y_semi[lab] = y[lab]
unl = y_semi == -1
def label_spreading(X, y_semi, gamma=20.0, alpha=0.99, tol=1e-3, max_iter=1000):
W = np.exp(-gamma * ((X[:, None, :] - X[None, :, :]) ** 2).sum(-1)) # RBF affinities
np.fill_diagonal(W, 0.0)
d = W.sum(1)
S = W / np.sqrt(d[:, None] * d[None, :]) # D^-1/2 W D^-1/2
classes = np.unique(y_semi[y_semi >= 0])
Y = (y_semi[:, None] == classes[None, :]).astype(float) # one-hot, zero rows if unlabelled
F = Y.copy()
for it in range(1, max_iter + 1):
F_new = alpha * S @ F + (1 - alpha) * Y # spread, then pull back to Y
done = np.abs(F_new - F).sum() < tol
F = F_new
if done:
break
return classes[F.argmax(1)], it
pred, iters = label_spreading(X, y_semi)
print(f"from scratch: {iters} iterations, accuracy on the 298 unlabelled points {np.mean(pred[unl] == y[unl]):.3f}")
ls = LabelSpreading(kernel="rbf", gamma=20, alpha=0.99, max_iter=1000).fit(X, y_semi)
print(f"scikit-learn: {ls.n_iter_} iterations, accuracy {np.mean(ls.transduction_[unl] == y[unl]):.3f}, "
f"same labels as ours: {np.mean(ls.transduction_ == pred):.3f}")
knn = KNeighborsClassifier(1).fit(X[lab], y[lab])
print(f"1-nearest neighbour on the 2 labels only: accuracy {knn.score(X[unl], y[unl]):.3f}")
for alpha in (0.2, 0.5, 0.9, 0.99):
ls = LabelSpreading(kernel="rbf", gamma=20, alpha=alpha, max_iter=1000).fit(X, y_semi)
print(f"alpha = {alpha:4}: {ls.n_iter_:3d} iterations, accuracy {np.mean(ls.transduction_[unl] == y[unl]):.3f}")from scratch: 164 iterations, accuracy on the 298 unlabelled points 0.980
scikit-learn: 164 iterations, accuracy 0.980, same labels as ours: 1.000
1-nearest neighbour on the 2 labels only: accuracy 0.732
alpha = 0.2: 4 iterations, accuracy 0.762
alpha = 0.5: 7 iterations, accuracy 0.782
alpha = 0.9: 32 iterations, accuracy 0.849
alpha = 0.99: 164 iterations, accuracy 0.980
The from-scratch version and scikit-learn's LabelSpreading agree on every one of the 300 points and need the same 164 iterations: the code above is what the library does (affinities without self-loops, symmetric normalisation, stop when changes by less than tol = 0.001 in total). One label per moon gives 0.980 on the 298 unlabelled points; a 1-nearest-neighbour classifier with the same two labels gets 0.732, because it splits the plane by distance to the two labelled points and ignores the moon shapes. The sweep shows why scikit-learn's default (, 0.762 here) is not always right: with so few labels, the labels must travel far along the graph, and only lets them reach the other end of each moon.
LabelSpreading(kernel="knn", n_neighbors=k) uses a sparse -nearest-neighbour graph instead, which scales to more points; the dense RBF graph above needs memory. Both are transductive: they label the points they were given. For a new point, predict reuses the graph's affinities to it, which works but is slower than an ordinary classifier.
Consistency regularisation
Graphs become impractical for images or text: distances between raw inputs are not meaningful and edges are too many. Consistency regularisation moves the idea into the network itself. For an unlabelled input, two random perturbations and (augmentation, noise, dropout) should get the same prediction:
The weight is ramped up from 0, so that the model first learns something from the labels. The second network is the target: no gradient flows through it. The methods differ in what the target is:
| Method | Target | Consistency term |
|---|---|---|
| -model | the same network, another perturbation | squared difference of probabilities |
| Temporal ensembling | the running average of each example's past predictions | squared difference |
| Mean teacher | a teacher whose weights are the exponential moving average of the student's | squared difference |
| FixMatch | the same network on a weakly augmented view, turned into a hard label if confident | cross-entropy on a strongly augmented view, only when |
The mean teacher's weights follow
so the teacher is an average of the student over the last hundred or so steps. An average of weights along the training path predicts more smoothly and more accurately than any single student, which makes it a better target than the student itself; and because it changes slowly, a single bad student step cannot corrupt the targets.
From scratch: a mean teacher in NumPy
Back to the digits with 30 labels (3 per class) and 1,227 unlabelled images, as in the pseudo-labelling lesson. The student is a small MLP (64 to 64 tanh units to 10), trained for 1,500 steps of gradient descent. The perturbation is the augmentation a digit's class survives: a random shift of up to one pixel plus a little noise. Three runs: supervised only (the labelled images are augmented too, so the comparison is fair), the mean teacher with the squared-difference loss, and a FixMatch-like variant in which the teacher's confident predictions () become hard pseudo-labels for the student. Test accuracy is on the usual 540 images.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_pool, X_test, y_pool, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=0)
rng = np.random.default_rng(0)
lab = np.concatenate([rng.choice(np.where(y_pool == c)[0], 3, replace=False) for c in range(10)])
unl = np.setdiff1d(np.arange(len(y_pool)), lab) # 30 labelled, 1227 unlabelled
def augment(X, r):
"""Shift by up to one pixel and add a little noise: a digit's class does not change."""
n, ar = len(X), np.arange(8)
padded = np.pad(X.reshape(n, 8, 8), ((0, 0), (1, 1), (1, 1)))
oy, ox = r.integers(0, 3, n), r.integers(0, 3, n)
out = padded[np.arange(n)[:, None, None], (oy[:, None] + ar)[:, :, None], (ox[:, None] + ar)[:, None, :]]
return out.reshape(n, 64) + r.normal(0, 0.1, (n, 64))
def init(seed, H=64):
r = np.random.default_rng(seed)
return [r.normal(0, np.sqrt(1 / 64), (64, H)), np.zeros(H), r.normal(0, np.sqrt(1 / H), (H, 10)), np.zeros(10)]
def forward(p, X):
h = np.tanh(X @ p[0] + p[1]); z = h @ p[2] + p[3]
e = np.exp(z - z.max(1, keepdims=True)); return h, e / e.sum(1, keepdims=True)
def backward(p, X, h, gz): # gradients of W1, b1, W2, b2 from dL/dlogits
gh = gz @ p[2].T * (1 - h ** 2)
return [X.T @ gh, gh.sum(0), h.T @ gz, gz.sum(0)]
def accuracy(p):
return (forward(p, X_test)[1].argmax(1) == y_test).mean()
def train(lam_max, mode="mse", ema=0.99, steps=1500, lr=0.5, threshold=0.8, seed=0):
student = init(seed)
teacher = [w.copy() for w in student]
r = np.random.default_rng(seed + 100)
for step in range(steps):
xl = augment(X_pool[lab], r) # supervised part: the 30 labels
h, p = forward(student, xl)
gz = p.copy(); gz[np.arange(len(lab)), y_pool[lab]] -= 1; gz /= len(lab)
grads = backward(student, xl, h, gz)
lam = lam_max * min(1.0, step / 500) # ramp the consistency weight up
if lam > 0:
xb = X_pool[r.choice(unl, 64, replace=False)]
xs, xt = augment(xb, r), augment(xb, r) # two different views
hs, ps = forward(student, xs)
pt = forward(teacher, xt)[1] # teacher's prediction: a fixed target
if mode == "mse": # mean teacher: squared difference
d = 2 * (ps - pt) / len(xb)
gz_u = ps * (d - (ps * d).sum(1, keepdims=True)) # back through the softmax
else: # confident teacher pseudo-labels (FixMatch-like)
keep = (pt.max(1) > threshold)[:, None]
gz_u = (ps - np.eye(10)[pt.argmax(1)]) * keep / len(xb)
for g, g_u in zip(grads, backward(student, xs, hs, lam * gz_u)):
g += g_u
for w, g in zip(student, grads):
w -= lr * g
for wt, ws in zip(teacher, student): # teacher = exponential moving average
wt *= ema; wt += (1 - ema) * ws
return accuracy(student), accuracy(teacher)
for name, lam, mode in (("supervised only", 0, "mse"), ("mean teacher (MSE)", 5, "mse"),
("teacher pseudo-labels", 2, "ce")):
s, t = train(lam, mode)
print(f"{name:22s} lambda={lam}: student {s:.3f}, teacher {t:.3f} (test, 540 images)")supervised only lambda=0: student 0.800, teacher 0.804 (test, 540 images)
mean teacher (MSE) lambda=5: student 0.857, teacher 0.874 (test, 540 images)
teacher pseudo-labels lambda=2: student 0.867, teacher 0.870 (test, 540 images)
The mean teacher lifts the student from 0.800 to 0.857 and the teacher itself to 0.874: 7 points from unlabelled images, with nothing hand-labelled beyond the 30. Using the teacher's confident predictions as hard pseudo-labels gives about the same (0.867 and 0.870). That combination of ideas, consistency across augmentations, an EMA teacher and a confidence threshold, is what most modern semi-supervised recipes (FixMatch, Mean Teacher, Noisy Student) are made of. For comparison, plain self-training with a logistic regression reached 0.830 on the same split in the previous lesson. The numbers are one seed on one split; with another seed the gains in our runs were similar but not identical, so read them as "clearly better", not as exact differences.
Two details in the code matter. The teacher's prediction is a constant target: its weights only move through the EMA line, never through a gradient. And the consistency weight lam grows linearly over the first 500 steps; at full strength from the start, the student would be pushed to agree with a teacher that knows nothing yet.
Teacher-student training beyond semi-supervision
The teacher-student pattern appears throughout this course in other forms:
- Noisy Student (Xie et al., 2020): train a teacher on the labelled data, pseudo-label a large unlabelled set, train an equal or larger student on both with strong noise (augmentation, dropout, stochastic depth), make the student the new teacher, repeat.
- Knowledge distillation: a large trained teacher's soft probabilities (at a raised temperature) train a small student; the goal is compression, not using unlabelled data.
- Self-distillation with an EMA teacher is how negative-free self-supervised methods such as BYOL and DINO avoid collapse (contrastive learning).
Advantages and limits
| Advantages | Limits |
|---|---|
| Uses unlabelled data without committing to hard labels early | The perturbations must preserve the label; choosing them needs domain knowledge |
| Label spreading needs only a similarity measure and works with one label per cluster | Graph methods need affinities (or a -NN graph) and are transductive |
| Mean teacher targets are stable and better than the student | Extra hyperparameters: and its ramp-up, EMA decay , threshold |
| State of the art for small label budgets in vision and speech when combined with strong augmentation | Gains shrink as labels grow, and vanish if the unlabelled data is from another distribution |
Pitfalls
- Collapse from too much consistency. A constant prediction is perfectly consistent. With too large relative to the supervised term, the student and teacher agree on a useless constant output (see Practice 2).
- Label-changing perturbations. Flipping a 6 can make a 9; cropping a medical image can remove the lesion. Every augmentation used for consistency must keep the class.
- No ramp-up. Early in training the teacher is random; a full-strength consistency term then teaches the student to agree with noise.
- A graph built on the wrong distance. Label spreading is only as good as its similarity: raw pixels or unscaled features make neighbours that do not share labels. Scale features first, or build the graph on embeddings (feature extraction).
- Reporting the student when the teacher is better. In mean teacher, the EMA teacher is usually the model to deploy.
Practice
- In the label-spreading example, why does a small (0.2) leave most of each moon wrongly labelled when there is one label per moon?
- Run the NumPy mean teacher with
lambda=30instead of 5. What do you expect, and why? - Why must no gradient flow through the teacher's prediction?
Answers
- With , each node keeps 80 % of its own (zero) score and gets only 20 % of its neighbours' each step, so the label scores decay quickly with distance along the graph. The iteration also converges after 4 steps, before the label of one end of the moon has reached the other end; distant points are then decided by tiny numbers. With the labels spread along the whole moon.
- The consistency term dominates the 30 labels, and the easiest way to make two predictions agree is to make them constant. Our run collapsed: student 0.124 and teacher 0.100, chance level for 10 classes.
- The teacher is a target. If gradients flowed through it, the loss could be reduced by moving the teacher towards the student as well as the student towards the teacher, which encourages both to collapse to the same trivial output and removes the stabilising effect of the slow average.
Test yourself
In label spreading, what does control?
- The number of classes
- The balance between spreading scores to neighbours and staying close to the original labels
- The learning rate of a neural network
- The test split
How are the mean teacher's weights obtained?
- By gradient descent on the consistency loss
- As an exponential moving average of the student's weights
- By copying the student every epoch
- They are fixed at initialisation
Why is a constant prediction a danger for consistency regularisation?
- It is slow to compute
- It is perfectly consistent under every perturbation, so a strong consistency term can push the model towards it
- It needs more labels
- It breaks the EMA
In the moons example, one label per moon gave 0.980 with label spreading and 0.732 with 1-nearest neighbour. What did label spreading use that kNN did not?
- More labels
- The unlabelled points, which form a graph that follows the shape of each moon
- A deeper model
- The test labels