TExcelTAD

Semi-Supervised Learning

A hospital has 100,000 scans and a radiologist can label 50 a day. A company has millions of support tickets and a few hundred tagged by topic. Often unlabelled data is plentiful and labels are scarce. Semi-supervised learning trains on both: a small labelled set and a large unlabelled one.

Why unlabelled data can help

Unlabelled examples carry no answers, but they show where the data lives: which regions are dense, which points form groups, what the boundaries between groups look like. Semi-supervised methods rely on one of three closely related assumptions:

Assumption Meaning
Smoothness points that are close to each other probably share a label
Cluster points in the same dense group probably share a label, so class boundaries run through low-density gaps
Manifold high-dimensional data (images, sound) lies near a lower-dimensional surface, and labels change smoothly along it

If these hold, a few labels can be spread along the structure the unlabelled data reveals. If they do not hold, unlabelled data can make things worse.

The main families

Method Idea
Self-training (pseudo-labelling) train on the labels you have, predict the unlabelled data, adopt the most confident predictions as labels, retrain, repeat
Label propagation / spreading build a similarity graph over all points and let the known labels flow along its edges
Consistency regularisation the model must give the same answer for an example and a slightly changed version of it (noise, cropping), which uses unlabelled data without labels
Teacher–student a teacher model labels unlabelled data, a student learns from those labels (often with noise added), and the student becomes the next teacher

Deep-learning versions of these ideas are covered in Training Strategies. Here are the first two with scikit-learn.

Self-training from scratch

The digits data has 1257 training images, but we pretend only 40 are labelled. Each round, the model labels the remaining images, and for every digit we keep the 20 predictions it is surest about as pseudo-labels.

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_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

rng = np.random.default_rng(0)
labelled = rng.choice(len(X_train), size=40, replace=False)        # we can afford only 40 labels
pool = np.delete(X_train, labelled, axis=0)                         # the rest: images without labels
X_lab, y_lab = X_train[labelled], y_train[labelled]

model = LogisticRegression(C=10, max_iter=5000).fit(X_lab, y_lab)
print(f"40 labels only: test accuracy {model.score(X_test, y_test):.3f}")

# Self-training: give pseudo-labels to the rows the model is surest about, add them, refit.
for round_ in range(1, 6):
    proba = model.predict_proba(pool)
    guess, confidence = proba.argmax(axis=1), proba.max(axis=1)
    picked = []
    for digit in range(10):                         # the 20 surest rows per predicted digit
        rows = np.where(guess == digit)[0]
        picked.extend(rows[np.argsort(-confidence[rows], kind="stable")[:20]])
    X_lab = np.vstack([X_lab, pool[picked]])
    y_lab = np.concatenate([y_lab, guess[picked]])
    pool = np.delete(pool, picked, axis=0)
    model = LogisticRegression(C=10, max_iter=5000).fit(X_lab, y_lab)
    print(f"round {round_}: {len(y_lab):4} training rows, test accuracy {model.score(X_test, y_test):.3f}")
40 labels only: test accuracy 0.848
round 1:  240 training rows, test accuracy 0.872
round 2:  440 training rows, test accuracy 0.870
round 3:  640 training rows, test accuracy 0.880
round 4:  840 training rows, test accuracy 0.889
round 5: 1040 training rows, test accuracy 0.902

Test accuracy on 540 images rises from 0.848 to 0.902 without a single new human label. Two details matter. Taking the same number of rows per predicted class keeps the pseudo-labelled set balanced; without it, the model tends to pile up confident examples of the easy digits. And the gain is not guaranteed in every round (round 2 dips slightly), because some pseudo-labels are wrong and the model learns from its own mistakes. In a quick experiment with a simpler rule (adopt every prediction with confidence at least 0.7, default regularisation), accuracy fell from 0.817 to 0.657 over five rounds: wrong pseudo-labels reinforced themselves. This is the main risk of self-training, called confirmation bias.

scikit-learn packages the same idea as SelfTrainingClassifier.

Label spreading

Label spreading connects every image to its 7 nearest neighbours and lets the 40 known labels flow through this graph until every image has one. scikit-learn marks unlabelled rows with the label -1.

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

X, y = load_digits(return_X_y=True)
X = X / 16.0
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)

rng = np.random.default_rng(0)
y_partial = np.full_like(y_train, -1)                  # -1 means "no label" in scikit-learn
known = rng.choice(len(y_train), size=40, replace=False)
y_partial[known] = y_train[known]

base = LogisticRegression(max_iter=2000).fit(X_train[known], y_train[known])
spread = LabelSpreading(kernel="knn", n_neighbors=7).fit(X_train, y_partial)
print("labelled rows:", (y_partial != -1).sum(), "of", len(y_partial))
print(f"supervised on 40 labels:     {base.score(X_test, y_test):.3f}")
print(f"label spreading, all rows:   {spread.score(X_test, y_test):.3f}")
hidden = y_partial == -1
print(f"labels it inferred correctly: {np.mean(spread.transduction_[hidden] == y_train[hidden]):.3f}")
labelled rows: 40 of 1257
supervised on 40 labels:     0.817
label spreading, all rows:   0.937
labels it inferred correctly: 0.924

With the same 40 labels, label spreading scores 0.937 on the test images against 0.817 for logistic regression trained on the 40 labelled images alone, and it assigns 92.4 % of the 1217 hidden training labels correctly. Digits of the same kind form dense, connected groups, exactly what the cluster assumption needs.

When to use it

  • Labels are expensive, unlabelled data is cheap and comes from the same source as the data you will predict on.
  • A supervised baseline on the labelled data alone exists, so you can tell whether the unlabelled data helps. Always compare against it on a labelled test set.
  • If you can buy more labels, compare with active learning, which chooses which examples to label; the two combine well.

Pitfalls

  • Confirmation bias. Wrong pseudo-labels get treated as truth and reinforce themselves. Use high confidence thresholds, balance per class, and check on labelled validation data each round.
  • Class imbalance in pseudo-labels. Easy classes collect most of the confident predictions; select per class.
  • Different distributions. Unlabelled data from another source (another hospital, another year) can pull the model in the wrong direction.
  • Evaluating on pseudo-labels. The test set must have real labels.

Practice

  1. In the label-spreading example, why is the "labels it inferred correctly" score (0.924) computed only on rows with y_partial == -1?
Answer

The 40 labelled rows keep their given labels, so including them would inflate the score. Only the 1217 hidden rows test how well the labels spread.

  1. Which assumption would fail for a data set where the two classes are mixed evenly in one dense cloud, with no gap between them?
Answer

The cluster assumption: class boundaries should run through low-density regions, but here the boundary runs through the middle of a dense region. Unlabelled points then give no hint where the boundary is, and semi-supervised methods offer little or nothing over the labelled data alone.

Test yourself

What data does semi-supervised learning train on?

  1. Only labelled examples
  2. Only unlabelled examples
  3. A small labelled set plus a large unlabelled set
  4. Rewards

What is a pseudo-label?

  1. A label written by an expert
  2. A model's own confident prediction used as a training label
  3. A random label
  4. A label of -1

What is the main risk of self-training?

  1. It is too slow
  2. Wrong pseudo-labels reinforce themselves (confirmation bias)
  3. It needs no labels at all
  4. It only works for images

In scikit-learn's semi-supervised estimators, how is an unlabelled row marked?

  1. With None
  2. With the label -1
  3. With NaN in the features
  4. It is left out