SkillNavora
AI-First Data Engineer › ML class guide › Companion lesson 2 of 6
Covers Class 3

Semi-supervised learning: a few labels, many unlabelled rows

Labels are expensive: someone has to check every loan, ticket or scan. Semi-supervised learning uses the few labelled rows plus the many unlabelled ones, and can beat a model trained on the labelled rows alone.

Best read after Statistics & Machine Learning 7: Introduction to Machine Learning: Types, Business Framing and the ML Lifecycle in the Data Science & AI handbook.

In plain words. A new credit officer reviews 20 loan files with a mentor who knows the outcomes. Then they sort 1,500 more files on their own, but only file the ones they are very sure about, learn from those, and repeat. That is self-training.

1. Why it matters

  • In real projects most data has no Y: only some applications have a known outcome, only some tickets are tagged.
  • Labelling more data costs money and time; using unlabelled data is free.
  • It sits between supervised (all labelled) and unsupervised (no labels), the third type of ML system from Class 3.

2. Key ideas

Labelled and unlabelled dataRows with a known Y and rows without. scikit-learn marks a missing label as -1.
Self-training (pseudo-labelling)Train on the labelled rows, predict the unlabelled ones, add only the predictions above a confidence threshold as new labels, retrain, repeat.
Label spreading / propagationBuild a graph of similar rows (nearest neighbours) and let labels flow to their neighbours.
Confidence thresholdToo low adds wrong pseudo-labels that teach the model mistakes; too high adds almost none.
When it helpsWhen labels are scarce and the unlabelled rows come from the same population. With plenty of labels the gain disappears.
When it hurtsWhen the first model is poor, its confident mistakes get reinforced (confirmation bias).

3. Step by step

  1. Split off a labelled test set first and never use it for training.
  2. Mark unlabelled training rows with -1.
  3. Train a supervised baseline on the labelled rows only.
  4. Train SelfTrainingClassifier and LabelSpreading on labelled plus unlabelled rows.
  5. Compare all three on the same test set, for several label counts.
  6. Use the semi-supervised model only if it beats the baseline; spend money on more labels if it does not.

4. Code you can run

Install once: pip install numpy pandas scipy scikit-learn statsmodels, then run python c2_semi_supervised.py. The data is generated inside the script, so it runs anywhere.

c2_semi_supervised.py
"""Semi-supervised learning: train with a few labelled loans plus many unlabelled ones.
Mirrors the class example: some applications have a known outcome (Y), the rest do not.
Run: python c2_semi_supervised.py"""
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.semi_supervised import LabelSpreading, SelfTrainingClassifier

X, y = make_classification(n_samples=2000, n_features=8, n_informative=5, n_redundant=1, n_clusters_per_class=1,
                           class_sep=0.8, flip_y=0.03, random_state=11)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=11, stratify=y)
scaler = StandardScaler().fit(X_train)
X_train, X_test = scaler.transform(X_train), scaler.transform(X_test)

rng = np.random.default_rng(3)
print(f"Training pool: {len(y_train)} applications | test set: {len(y_test)} (always labelled, never used to train)\n")
print(f"{'labelled':>9} {'unlabelled':>11} | {'supervised only':>15} | {'self-training':>13} | {'label spreading':>15}")
for n_lab in [10, 20, 50, 500]:
    accs = {"sup": [], "self": [], "spread": []}
    for seed in range(5):                                  # repeat to average out luck
        idx = np.random.default_rng(seed).choice(len(y_train), n_lab, replace=False)
        if len(set(y_train[idx])) < 2:                     # need both classes to train
            continue
        y_partial = np.full(len(y_train), -1)              # -1 means "no label" in scikit-learn
        y_partial[idx] = y_train[idx]

        sup = LogisticRegression().fit(X_train[idx], y_train[idx])
        accs["sup"].append(accuracy_score(y_test, sup.predict(X_test)))

        st = SelfTrainingClassifier(LogisticRegression(), threshold=0.9).fit(X_train, y_partial)
        accs["self"].append(accuracy_score(y_test, st.predict(X_test)))

        ls = LabelSpreading(kernel="knn", n_neighbors=10).fit(X_train, y_partial)
        accs["spread"].append(accuracy_score(y_test, ls.predict(X_test)))
    print(f"{n_lab:>9} {len(y_train) - n_lab:>11} | {np.mean(accs['sup']):>15.3f} | {np.mean(accs['self']):>13.3f} | {np.mean(accs['spread']):>15.3f}")

# What self-training did, step by step, for one run with 20 labels
idx = np.random.default_rng(0).choice(len(y_train), 20, replace=False)
y_partial = np.full(len(y_train), -1); y_partial[idx] = y_train[idx]
st = SelfTrainingClassifier(LogisticRegression(), threshold=0.9).fit(X_train, y_partial)
added = st.labeled_iter_
print(f"\nOne run with 20 labels: {int((added > 0).sum())} pseudo-labels added over {st.n_iter_} rounds; "
      f"{int((added == -1).sum())} rows stayed unlabelled (model never 90% sure).")
pseudo = added > 0
print(f"Pseudo-label accuracy against the hidden truth: {accuracy_score(y_train[pseudo], st.transduction_[pseudo]):.3f}")
Real output (captured when this page was built)
Training pool: 1500 applications | test set: 500 (always labelled, never used to train)

 labelled  unlabelled | supervised only | self-training | label spreading
       10        1490 |           0.816 |         0.743 |           0.896
       20        1480 |           0.911 |         0.921 |           0.916
       50        1450 |           0.943 |         0.954 |           0.934
      500        1000 |           0.972 |         0.972 |           0.974

One run with 20 labels: 1313 pseudo-labels added over 10 rounds; 167 rows stayed unlabelled (model never 90% sure).
Pseudo-label accuracy against the hidden truth: 0.890

5. Reading the output

  • Each row of the table averages five random draws of labelled rows, so luck does not decide the result.
  • With 10 labels, label spreading lifts accuracy from 0.82 to 0.90, while self-training falls to 0.74: its first model is weak and it learns from its own confident mistakes.
  • With 20 to 50 labels both methods help a little; with 500 labels all three match, so extra unlabelled data adds nothing.
  • The last lines show what self-training did in one run: how many pseudo-labels it added and how accurate they were.

6. Common mistakes

MistakeDo this instead
Evaluating on the pseudo-labelled rowsAlways evaluate on a separate, truly labelled test set.
Threshold too lowWrong pseudo-labels pile up. Start at 0.9 and check pseudo-label accuracy on a labelled sample.
Unlabelled data from a different populationLast year's applicants or another region can mislead the model. Check that distributions match.
Skipping the supervised baselineWithout it you cannot tell whether the unlabelled data helped.

7. Assignment

Take any labelled classification dataset, hide the labels of 95% of the training rows, and compare a supervised baseline, self-training and label spreading at 1%, 5% and 20% labelled. Plot accuracy against the share of labels and write when you would pay for more labels instead.

8. Interview questions

What is semi-supervised learning?

Training with a small labelled set plus a large unlabelled set, for example by pseudo-labelling confident predictions or spreading labels to similar rows.

When does it fail?

When the initial model is poor or the unlabelled data differs from the labelled data: confident mistakes get reinforced.

How is it different from active learning?

Active learning asks a human to label the most useful rows; semi-supervised learning labels rows automatically.

9. Go further

Refer & earn