TExcelTAD
Home › Training Strategies: Transfer, Fine-Tuning, Semi-Supervised, Active, Online & Distributed › Semi-Supervised Learning: Pseudo-Labelling and Self-Training

Semi-Supervised Learning: Pseudo-Labelling and Self-Training

A radiology department has 30 reports a doctor has labelled and 1,200 that nobody has. A support team has 50 tagged tickets and a year of untagged ones. Semi-supervised learning trains on both: a few labelled examples and many unlabelled ones from the same distribution. The oldest and simplest method is self-training: train on the labels you have, let the model label the unlabelled examples it is sure about, add those pseudo-labels to the training set, and repeat.

ML Foundations introduced the idea. This lesson writes the loop from scratch, checks it against scikit-learn's SelfTrainingClassifier, and shows how it fails.

Why unlabelled data can help at all

Unlabelled examples carry no answers, but they show where the data lives. Semi-supervised methods rest on three related assumptions:

  • Smoothness: points close to each other in a dense region have the same label.
  • Cluster assumption: the data forms clusters, and a cluster tends to be one class.
  • Low-density separation: the decision boundary should pass through regions with few points, not cut through a cluster.

When they hold, unlabelled points show where clusters are, and a confident prediction deep inside a cluster is probably right. When they do not hold (classes overlap heavily, or the unlabelled data comes from a different distribution), semi-supervised learning can make a model worse.

The self-training loop

labelled settrue + pseudo labels 1 trainmodel f 2 predictunlabelled pool 3 confident?max p above tau 4 add them with label argmax pthe rest stays unlabelled for the next round repeat stop when nothing passes the threshold, the pool is empty, or after max_iter rounds

With a model ff that outputs class probabilities p=f(x)\mathbf{p} = f(\mathbf{x}), the pseudo-label of an unlabelled point and the rule for keeping it are

y^=arg⁡max⁡cpc(x),keep (x,y^) if max⁡cpc(x)>τ\hat{y} = \arg\max_c p_c(\mathbf{x}), \qquad \text{keep } (\mathbf{x}, \hat{y}) \text{ if } \max_c p_c(\mathbf{x}) > \tau

Deep-learning versions do the same inside one training run instead of in rounds: each mini-batch has a labelled part and an unlabelled part, and the loss adds a weighted pseudo-label term,

L=1nl∑i=1nlCE⁡(yi,f(xi))+λ 1nu∑j=1nu1[max⁡cpc(xj)>τ]CE⁡(y^j,f(xj))L = \frac{1}{n_l} \sum_{i=1}^{n_l} \operatorname{CE}\big(y_i, f(\mathbf{x}_i)\big) + \lambda \, \frac{1}{n_u} \sum_{j=1}^{n_u} \mathbb{1}\big[\max_c p_c(\mathbf{x}_j) > \tau\big] \operatorname{CE}\big(\hat{y}_j, f(\mathbf{x}_j)\big)

where λ\lambda is usually ramped up from 0 over the first epochs, so that early, unreliable predictions do not dominate. FixMatch (2020) is this loss with one twist: the pseudo-label comes from a weakly augmented view and the loss is computed on a strongly augmented one (next lesson).

From scratch

The digits again: 30 labelled images (3 per digit), 1,227 unlabelled ones from the same training pool, and a fixed test split of 540. The base model is a logistic regression with C=10C = 10, the threshold τ=0.9\tau = 0.9. Because the "unlabelled" images really have labels, the loop can also report how many pseudo-labels are correct, a number you never have in a real project.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression

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)          # 1227 images whose labels we pretend not to know
print(f"{len(lab)} labelled, {len(unl)} unlabelled, {len(y_test)} test images")

def make_model():
    return LogisticRegression(C=10, max_iter=3000)

threshold = 0.9
X_l, y_l, remaining = X_pool[lab], y_pool[lab], unl.copy()
model = make_model().fit(X_l, y_l)
print(f"iteration 0: {len(y_l):4d} training labels, test accuracy {model.score(X_test, y_test):.3f}")
correct = 0
for it in range(1, 11):
    proba = model.predict_proba(X_pool[remaining])
    take = proba.max(1) > threshold                       # confident predictions only
    if not take.any():
        print("no prediction above the threshold: stop"); break
    new, pseudo = remaining[take], model.classes_[proba[take].argmax(1)]
    correct += (pseudo == y_pool[new]).sum()             # only possible because this is a demo
    X_l, y_l = np.vstack([X_l, X_pool[new]]), np.concatenate([y_l, pseudo])
    remaining = remaining[~take]
    model = make_model().fit(X_l, y_l)
    print(f"iteration {it}: +{take.sum():3d} pseudo-labels, {len(y_l):4d} training labels, "
          f"pseudo-label accuracy so far {correct / (len(y_l) - len(lab)):.3f}, test accuracy {model.score(X_test, y_test):.3f}")
30 labelled, 1227 unlabelled, 540 test images
iteration 0:   30 training labels, test accuracy 0.789
iteration 1: +224 pseudo-labels,  254 training labels, pseudo-label accuracy so far 1.000, test accuracy 0.796
iteration 2: +408 pseudo-labels,  662 training labels, pseudo-label accuracy so far 0.975, test accuracy 0.802
iteration 3: +167 pseudo-labels,  829 training labels, pseudo-label accuracy so far 0.956, test accuracy 0.820
iteration 4: + 81 pseudo-labels,  910 training labels, pseudo-label accuracy so far 0.947, test accuracy 0.826
iteration 5: + 41 pseudo-labels,  951 training labels, pseudo-label accuracy so far 0.941, test accuracy 0.835
iteration 6: + 26 pseudo-labels,  977 training labels, pseudo-label accuracy so far 0.936, test accuracy 0.841
iteration 7: +  9 pseudo-labels,  986 training labels, pseudo-label accuracy so far 0.934, test accuracy 0.837
iteration 8: +  6 pseudo-labels,  992 training labels, pseudo-label accuracy so far 0.931, test accuracy 0.833
iteration 9: +  4 pseudo-labels,  996 training labels, pseudo-label accuracy so far 0.929, test accuracy 0.828
iteration 10: +  6 pseudo-labels, 1002 training labels, pseudo-label accuracy so far 0.926, test accuracy 0.830

The first round adds 224 pseudo-labels and every one is correct: the model's most confident predictions are reliable. Each later round adds the next most confident ones, and both the pseudo-label accuracy (down to 0.926 by round 10) and the gain shrink. Test accuracy rises from 0.789 to a peak of 0.841 at round 6 and ends at 0.830: about 4 points for free, from images nobody labelled. The peak at round 6 cannot be used to choose the number of rounds, because that would be tuning on the test set; a validation split, or a fixed small max_iter, is the honest way.

With scikit-learn: SelfTrainingClassifier

SelfTrainingClassifier wraps any classifier with predict_proba and runs the same loop. Unlabelled rows are marked with the label -1. Its threshold criterion adds every prediction above τ\tau; the k_best criterion adds the kk most confident each round, whatever their confidence.

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.semi_supervised import SelfTrainingClassifier

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)])
y_semi = np.full(len(y_pool), -1)                         # -1 means "unlabelled" in scikit-learn
y_semi[lab] = y_pool[lab]

supervised = LogisticRegression(C=10, max_iter=3000).fit(X_pool[lab], y_pool[lab])
print(f"supervised, 30 labels:           test accuracy {supervised.score(X_test, y_test):.3f}")
for kw in ({"threshold": 0.9}, {"criterion": "k_best", "k_best": 100, "max_iter": 12}):
    st = SelfTrainingClassifier(LogisticRegression(C=10, max_iter=3000), **kw).fit(X_pool, y_semi)
    used = st.labeled_iter_ > 0                           # rows that received a pseudo-label
    name = ", ".join(f"{k}={v}" for k, v in kw.items())
    print(f"self-training ({name}): test accuracy {st.score(X_test, y_test):.3f}")
    print(f"  {st.n_iter_} iterations, stopped by '{st.termination_condition_}', "
          f"{used.sum()} pseudo-labels, {np.mean(st.transduction_[used] == y_pool[used]):.3f} of them correct")
    print("  pseudo-labels added per iteration:", np.bincount(st.labeled_iter_[used]).tolist()[1:])
supervised, 30 labels:           test accuracy 0.789
self-training (threshold=0.9): test accuracy 0.830
  10 iterations, stopped by 'max_iter', 972 pseudo-labels, 0.926 of them correct
  pseudo-labels added per iteration: [224, 408, 167, 81, 41, 26, 9, 6, 4, 6]
self-training (criterion=k_best, k_best=100, max_iter=12): test accuracy 0.815
  12 iterations, stopped by 'max_iter', 1200 pseudo-labels, 0.833 of them correct
  pseudo-labels added per iteration: [100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

With threshold=0.9 the result is identical to the from-scratch loop: the same 972 pseudo-labels, added in the same batches (224, 408, 167, …), 0.926 of them correct, test accuracy 0.830. The attributes are the useful part: labeled_iter_ says in which round each row got its label (0 for the original labels, -1 for never), transduction_ holds every row's final label, and termination_condition_ says why the loop stopped (max_iter, no_change or all_labeled). The k_best variant adds 100 per round regardless of confidence, so by round 12 it has labelled 1,200 images with only 0.833 correct, and ends lower (0.815).

When it goes wrong: confirmation bias

A wrong pseudo-label is trained on as if it were true. The model becomes more confident in its own mistake, labels more of its neighbours the same way, and the error spreads: confirmation bias. How bad it gets depends on whether the model's confidence means anything. Here are two base models and four thresholds:

python · try it yourself
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.semi_supervised import SelfTrainingClassifier

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)])
y_semi = np.full(len(y_pool), -1); y_semi[lab] = y_pool[lab]

print("   C  threshold  pseudo-labels  correct  largest class  test accuracy")
for C in (1, 10):
    base = LogisticRegression(C=C, max_iter=3000)
    print(f"{C:4d}  supervised only {'':37s}{base.fit(X_pool[lab], y_pool[lab]).score(X_test, y_test):.3f}")
    for thr in (0.5, 0.7, 0.9, 0.99):
        st = SelfTrainingClassifier(LogisticRegression(C=C, max_iter=3000), threshold=thr).fit(X_pool, y_semi)
        used = st.labeled_iter_ > 0
        if used.sum() == 0:
            print(f"{C:4d}  {thr:9}  {0:13d}  {'-':>7s}  {'-':>13s}  {st.score(X_test, y_test):13.3f}"); continue
        share = np.bincount(st.transduction_[used], minlength=10).max() / used.sum()
        print(f"{C:4d}  {thr:9}  {used.sum():13d}  {np.mean(st.transduction_[used] == y_pool[used]):7.3f}"
              f"  {share:13.3f}  {st.score(X_test, y_test):13.3f}")
   C  threshold  pseudo-labels  correct  largest class  test accuracy
   1  supervised only                                      0.781
   1        0.5           1192    0.793          0.133          0.789
   1        0.7           1063    0.614          0.272          0.561
   1        0.9              0        -              -          0.781
   1       0.99              0        -              -          0.781
  10  supervised only                                      0.789
  10        0.5           1224    0.819          0.124          0.820
  10        0.7           1171    0.857          0.116          0.843
  10        0.9            972    0.926          0.126          0.830
  10       0.99              0        -              -          0.789
  • C=10C = 10 (weak regularisation) gains at thresholds 0.5, 0.7 and 0.9, best at 0.7 (0.843). The pseudo-label accuracy rises with the threshold (0.819, 0.857, 0.926): a stricter threshold means fewer but cleaner labels.
  • C=1C = 1 (stronger regularisation) gives softer probabilities. At 0.9 and 0.99 nothing ever passes, so self-training does nothing. At 0.7 it collapses to 0.561: the most frequent pseudo-label takes 27.2 % of all pseudo-labels instead of about 10 %, one class has swallowed others, and only 0.614 of the pseudo-labels are right.
  • At 0.99 even the C=10C = 10 model never passes the threshold.

The threshold is therefore not a universal constant: it interacts with how confident the base model is, which depends on its regularisation and calibration (calibration). Choose it on a validation set, and watch the class distribution of the pseudo-labels.

Advantages and limits

Advantages Limits
Works with any classifier that gives probabilities Confirmation bias: early mistakes are reinforced
Simple to explain and to implement Needs calibrated confidence; the threshold depends on the model
Unlabelled data is cheap Helps only if the cluster and smoothness assumptions hold
Often a few points of accuracy for free with very few labels Gains shrink as labels grow; with plenty of labels it rarely helps
The deep-learning form (with augmentation, as in FixMatch) is state of the art for small label budgets Unlabelled data from another distribution (other hospital, other season) can hurt

Pitfalls

  • Evaluating on pseudo-labelled data. The test set must have real labels and must not be part of the unlabelled pool.
  • Class imbalance in the pseudo-labels. Easy classes get pseudo-labelled first and grow; hard classes shrink. Cap the number of pseudo-labels per class per round, or check their distribution as in the table above.
  • Uncalibrated confidence. Deep networks are often over-confident, so a threshold of 0.9 lets many errors through. Calibrate, raise the threshold, or use the consistency methods of the next lesson.
  • Unlabelled data from somewhere else. If the unlabelled pool contains classes that are not in the labelled set (out-of-distribution data), the model will force them into known classes with confidence.
  • Choosing rounds or thresholds on the test set, as the peak in round 6 tempts you to.

Practice

  1. In the from-scratch run, why is the first round's pseudo-label accuracy (1.000) higher than the cumulative accuracy after round 10 (0.926)?
  2. Why does C=1C = 1 with threshold 0.9 add no pseudo-labels at all?
  3. You have 40 labelled and 100,000 unlabelled product photos, 5 % of which show products not in your 8 classes. What could go wrong with self-training, and what would you do?
Answers
  1. Each round takes the most confident predictions that are left. The first round gets the easiest images, far inside their clusters; later rounds take harder ones near the boundaries, where more predictions are wrong.
  2. With stronger regularisation and only 30 labels, the logistic regression's probabilities are soft: no unlabelled image gets a maximum probability above 0.9, so the loop stops before adding anything (termination_condition_ is no_change).
  3. The 5 % unknown products get pseudo-labelled as one of the 8 classes, often confidently, and pollute those classes. Filter likely out-of-distribution images first (low maximum probability across several models, or distance from every class in an embedding space), use a high threshold with per-class caps, and validate on a labelled set that includes such images.

Test yourself

How does scikit-learn's SelfTrainingClassifier know which rows are unlabelled?

  1. Rows with NaN features
  2. Rows whose label is -1
  3. A separate unlabelled= argument
  4. Rows after the first 30

What is confirmation bias in self-training?

  1. The model prefers the majority class of the test set
  2. Wrong pseudo-labels are trained on as truth, making the model more confident in its mistakes, which then spread
  3. Humans confirm every pseudo-label
  4. The threshold is too high

Raising the confidence threshold τ\tau usually…

  1. adds more pseudo-labels with lower accuracy
  2. adds fewer pseudo-labels with higher accuracy
  3. has no effect
  4. removes the original labels

Which assumption does pseudo-labelling rely on?

  1. The unlabelled data comes from a different distribution
  2. Points in the same dense cluster tend to share a label, so confident predictions inside clusters are mostly right
  3. The labelled set is larger than the unlabelled set
  4. The model is a decision tree