Collecting data is often cheap, but labelling it is slow and costly. A hospital may have 10,000 X-rays but time for a doctor to label only 200. Semi-supervised learning uses the few labelled examples and the many unlabelled ones together. In this lesson you will train a digit recogniser with just 50 labels and see how far the unlabelled images can push it.
In this lesson you will learn
- When semi-supervised learning is worth trying
- How to mark unlabelled rows with -1 in scikit-learn
- Self-training with pseudo-labels using
SelfTrainingClassifier - Label spreading over a similarity graph with
LabelSpreading - How the confidence threshold trades quantity for quality
You should know logistic regression and k-nearest neighbours.
Learning From Unlabelled Data
Unlabelled data has no answers, so how can it help? It shows the shape of the data. Handwritten 7s form a group, and so do 1s. If one point in a group is labelled 7, its close neighbours are probably 7s too. Semi-supervised methods use this idea in two main ways:
- Self-training: train on the labelled data, predict the unlabelled data, and keep the guesses the model is very sure about. These guesses are called pseudo-labels. Add them to the training set and repeat.
- Label spreading: link every point to its nearest neighbours, like a web. Labels then flow along the links from labelled points to unlabelled ones.
Fifty Labels, 1,257 Images
The digits dataset has 1,797 small images of handwritten digits. We keep 30% for testing. Of the remaining 1,257 training images, we pretend only 50 have labels. In scikit-learn, an unlabelled row gets the label -1.
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, LabelSpreading
X, y = load_digits(return_X_y=True)
X = X / 16.0
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
# Pretend we could only afford to label 50 of the 1257 training images
rng = np.random.default_rng(0)
labelled = rng.choice(len(y_tr), 50, replace=False)
y_partial = np.full_like(y_tr, -1) # -1 means "no label"
y_partial[labelled] = y_tr[labelled]
print("labelled images:", (y_partial != -1).sum(), "of", len(y_partial))
# 1) Supervised only: train on the 50 labelled images
base = LogisticRegression(max_iter=2000, C=10).fit(X_tr[labelled], y_tr[labelled])
print(f"only 50 labels : {base.score(X_te, y_te):.3f}")
# 2) Self-training: label the confident unlabelled images, retrain, repeat
st = SelfTrainingClassifier(LogisticRegression(max_iter=2000, C=10), threshold=0.9)
st.fit(X_tr, y_partial)
print(f"self-training : {st.score(X_te, y_te):.3f} "
f"({(st.labeled_iter_ > 0).sum()} images got pseudo-labels)")
new = st.labeled_iter_ > 0
print(f"pseudo-labels correct : {np.mean(st.transduction_[new] == y_tr[new]):.3f}")
# 3) Label spreading: labels flow to nearby points through a similarity graph
ls = LabelSpreading(kernel="knn", n_neighbors=10).fit(X_tr, y_partial)
print(f"label spreading : {ls.score(X_te, y_te):.3f}")
# 4) The dream: every training image labelled
full = LogisticRegression(max_iter=2000, C=10).fit(X_tr, y_tr)
print(f"all 1257 labels : {full.score(X_te, y_te):.3f}")
Output
labelled images: 50 of 1257
only 50 labels : 0.848
self-training : 0.902 (1012 images got pseudo-labels)
pseudo-labels correct : 0.950
label spreading : 0.941
all 1257 labels : 0.967
- With only the 50 labelled images, logistic regression reaches about 85%.
- Self-training gave pseudo-labels to 1,012 images, and 95% of those guesses were right. Training on them lifts the test score to about 90%.
- Label spreading does even better, at about 94%. Digits of the same kind sit close together, which is exactly what this method needs.
- With all 1,257 labels we would get about 97%. So 50 labels plus unlabelled data closed most of the gap, for a fraction of the labelling work.
How Sure Is Sure Enough?
Self-training only accepts a guess if the predicted probability is above a threshold. A low threshold adds many pseudo-labels, but more of them are wrong. A high threshold adds fewer but cleaner labels.
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_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.3, random_state=0, stratify=y)
rng = np.random.default_rng(0)
labelled = rng.choice(len(y_tr), 50, replace=False)
y_partial = np.full_like(y_tr, -1)
y_partial[labelled] = y_tr[labelled]
# How sure must the model be before it trusts its own guess?
print("threshold pseudo-labels correct test acc.")
for t in (0.5, 0.7, 0.9, 0.95):
st = SelfTrainingClassifier(LogisticRegression(max_iter=2000, C=10), threshold=t)
st.fit(X_tr, y_partial)
new = st.labeled_iter_ > 0
right = np.mean(st.transduction_[new] == y_tr[new])
print(f" {t:<8} {new.sum():>10} {right:.3f} {st.score(X_te, y_te):.3f}")
Output
threshold pseudo-labels correct test acc.
0.5 1203 0.871 0.881
0.7 1163 0.906 0.894
0.9 1012 0.950 0.902
0.95 836 0.957 0.856
- At 0.5, almost every image gets a pseudo-label, but 13% of them are wrong. The model then learns from its own mistakes.
- At 0.9, the balance is best here: a thousand pseudo-labels at 95% correctness.
- At 0.95, the labels are cleaner but too few are added, and the score drops. The best threshold depends on the data, so test a few.
Confirmation bias
A self-training model believes its own guesses. If an early pseudo-label is wrong, the model trains on it and becomes even more sure of the mistake. A high threshold and a model with good probabilities reduce this risk. See probability calibration.
When Does It Help?
| Helps when | Does not help when |
|---|---|
| Labels are few but unlabelled data is plentiful | You already have plenty of labels |
| Classes form clear groups | Classes overlap heavily |
| Unlabelled data comes from the same source | Unlabelled data is from a different source |
Always keep a labelled test set and compare with the “labelled only” model. If the semi-supervised model is not better, use the simpler one.
Common Mistakes
- Putting unlabelled rows in the test set. You can only measure accuracy on rows with true labels.
- Using a low threshold to get more data. Wrong pseudo-labels can hurt more than missing ones.
- Forgetting to scale features for label spreading. It uses distances, so one large column can dominate the graph.
- Skipping the baseline. Without a “labelled only” score, you cannot tell whether the unlabelled data helped.
Practice Exercises
Exercise 1. In ss1.py, change 50 to 200 labelled images. Which score improves the most, and why?
Show answer
The “labelled only” score improves the most, because it gains real labels directly. The semi-supervised scores also rise, but the gap between them and the baseline shrinks. Semi-supervised learning helps most when labels are very scarce.
Exercise 2. A pseudo-label is wrong. Why can that be worse than leaving the row unlabelled?
Show answer
An unlabelled row teaches nothing, but a wrongly labelled row teaches the wrong thing. The model then becomes more confident in its mistake and may spread it to similar rows.
Frequently Asked Questions
What is the difference between semi-supervised and unsupervised learning?
Unsupervised learning uses no labels at all, as in clustering. Semi-supervised learning uses a few labels plus many unlabelled rows, and still predicts the labelled classes.
What is a pseudo-label?
A pseudo-label is a label the model predicts for an unlabelled row and then uses as if it were true training data. Only confident predictions should become pseudo-labels.
Can I use any classifier with SelfTrainingClassifier?
Any classifier that has predict_proba works. Models with reliable probabilities, such as logistic regression, usually work best, because the threshold depends on those probabilities.
Summary
- Semi-supervised learning mixes a few labels with many unlabelled rows.
- Mark unlabelled rows with -1 in scikit-learn.
- Self-training adds confident pseudo-labels; label spreading passes labels to neighbours.
- The threshold controls the trade-off between more labels and correct labels.
