Skip to main content
LearnMLAcademy
Intermediate10 min read

Semi-Supervised Learning

Leverage large unlabelled datasets with pseudo-labelling and label spreading, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Semi-Supervised Learning

Suppose you have 10,000 photos, but a human has labelled only 300 of them. Throwing away the other 9,700 photos feels wasteful, but paying people to label everything may be expensive. Semi-supervised learningasks whether the unlabelled examples can help us learn while we still use the labels we trust.

Understand first

Small labelled set

Examples with known answers

Large unlabelled set

Examples whose answers are unknown

Learn from both

When the method's assumptions are useful

Supervised, Unsupervised, and Semi-Supervised

ApproachLabels available?Typical purpose
Supervised learningLabels for the training examplesLearn input → target mapping
Unsupervised learningNo target labelsDiscover structure such as clusters or representations
Semi-supervised learningSome labelled + some unlabelled examplesUse both sources to learn a supervised task

Unlabelled data does not automatically improve a model

Semi-supervised methods can help when the unlabelled data reflects useful structure related to the target. They can also add little value—or even hurt—when their assumptions are wrong, pseudo-labels are poor, or the unlabelled data comes from a different distribution.

A Familiar Example: Classifying Emails

Imagine that you collected thousands of emails, but only a small number were manually labelled as Spam or Not Spam.

Known label

“Win a prize now!”

Spam

Known label

“Meeting moved to 3 PM”

Not Spam

Unknown label

Thousands of other emails

Unlabelled

A semi-supervised method may use the labelled emails to anchor the classes and the unlabelled emails to learn additional structure. The exact mechanism depends on the algorithm.

Two Core Ways to Use Unlabelled Data

1

Self-training: create careful pseudo-labels

Train a supervised classifier using the labelled examples, predict the unlabelled examples, add selected high-confidence predictions as pseudo-labels, and fit again.

Labelled data → train → predict unlabelled data → keep selected confident predictions → retrain
2

Graph methods: spread labels through similarity

Treat examples as nodes in a graph. Similar examples receive stronger connections, and information from labelled nodes is propagated toward related unlabelled nodes.

Labelled + unlabelled examples → similarity graph → propagate label information

Self-Training: A Tiny Step-by-Step Example

Suppose a classifier predicts three unlabelled examples with these maximum class probabilities:

Unlabelled examplePredicted classConfidenceWith threshold = 0.90
ASpam0.97Add pseudo-label
BNot Spam0.93Add pseudo-label
CSpam0.61Leave unlabelled

After adding A and B, the classifier can be fitted again. This process may continue for several rounds.

Why confidence needs caution

A model can be confidently wrong. If incorrect pseudo-labels are repeatedly added, the next model may learn those mistakes and reinforce them. A high threshold reduces how many pseudo-labels are accepted, but it does not guarantee that accepted labels are correct.

When Can Unlabelled Data Help?

Different semi-supervised algorithms rely on different assumptions. Three common intuitions are useful:

Smoothness / continuity

Nearby or very similar examples are often expected to have similar labels.

Cluster assumption

Dense groups of examples may correspond to classes, with useful decision boundaries passing through lower-density regions.

Manifold assumption

High-dimensional observations may lie near lower-dimensional structure that unlabelled examples help reveal.

These are assumptions and modeling intuitions—not universal laws. For example, two classes can overlap heavily, or nearby points can have different labels. In such cases, unlabelled structure may not align with the prediction target.

Python Example: Label Spreading with Scikit-Learn

In Scikit-Learn's semi-supervised graph algorithms, unlabelled targets are represented by -1. The example below keeps only 4 labelled training examples per Iris class. The remaining training examples are supplied as unlabelled observations, while the test set stays completely separate.

Python
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.semi_supervised import LabelSpreading
from sklearn.metrics import accuracy_score

X, y = load_iris(return_X_y=True)

X_train, X_test, y_train, y_test = train_test_split(
    X,
    y,
    test_size=0.30,
    random_state=42,
    stratify=y
)

rng = np.random.default_rng(42)
y_semi = np.full_like(y_train, -1)

# Keep only 4 known labels from each class.
for class_id in np.unique(y_train):
    class_rows = np.where(y_train == class_id)[0]
    labeled_rows = rng.choice(class_rows, size=4, replace=False)
    y_semi[labeled_rows] = y_train[labeled_rows]

labeled_count = np.sum(y_semi != -1)
unlabeled_count = np.sum(y_semi == -1)

model = make_pipeline(
    StandardScaler(),
    LabelSpreading(
        kernel="knn",
        n_neighbors=7,
        alpha=0.2,
        max_iter=100
    )
)

model.fit(X_train, y_semi)
predictions = model.predict(X_test)

print("Labeled training samples:", labeled_count)
print("Unlabeled training samples:", unlabeled_count)
print("Held-out test samples:", len(y_test))
print("Test accuracy:", round(accuracy_score(y_test, predictions), 3))

Expected output

Labeled training samples: 12
Unlabeled training samples: 93
Held-out test samples: 45
Test accuracy: 0.889

What does this example prove?

It demonstrates the mechanics: the model receives only 12 known labels but also sees 93 unlabelled training feature vectors, and it is evaluated on 45 untouched test examples.

It does not prove that semi-supervised learning is always better. To test that claim fairly, compare it against suitable supervised baselines using the same label budget and evaluate both on the same held-out data.

Label Propagation vs Label Spreading

AspectLabelPropagationLabelSpreading
Graph ideaUses the similarity graph directlyUses a normalized graph-Laplacian formulation
Input-label clampingHard clampingSoft clamping controlled by alpha
NoiseCan be more sensitive to incorrect labelsRegularization can make it more robust to noise
Built-in kernelsRBF or KNNRBF or KNN

With LabelSpreading, alpha controls how much an example adopts information from its neighbors versus retaining its initial label information. It is a model parameter to tune—not a universal constant.

Going Deeper: Other Semi-Supervised Approaches

1. Self-training / pseudo-labeling

Iteratively add selected model predictions to the labelled set. Scikit-Learn provides SelfTrainingClassifier, whose threshold-based mode relies on meaningful probability estimates.

2. Co-training

Classical co-training learns from different views of the same examples, such as page text and link information. Its classical theory assumes informative views with a degree of independence; practical variants may relax those assumptions.

3. Graph-based methods

Construct a similarity graph and propagate label information. This is the family containing LabelPropagation and LabelSpreading.

4. Consistency regularization

Encourage the model to make compatible predictions when an unlabelled input is perturbed or augmented in ways that should not change its class. Modern image methods such as FixMatch use this broad idea together with pseudo-labeling.

5. Semi-supervised generative approaches

Some generative-model designs use labelled and unlabelled observations jointly. Semi-supervised VAE/GAN variants exist, but they are more advanced than the graph and self-training methods introduced here.

Semi-Supervised vs Self-Supervised Learning

Semi-supervised

The training problem directly contains both labelled and unlabelled examples for a supervised target.

Self-supervised

The system creates a learning signal from the data itself—for example by predicting masked or transformed parts—without requiring human target labels for that pretraining task.

They are related because both can benefit from unlabelled data, but they are not synonyms. A self-supervised representation may later be fine-tuned with labelled data, while classical semi-supervised methods directly mix labelled and unlabelled examples during learning.

Real-World Situations Where It Can Be Useful

Medical imaging

Large image archives may exist while expert annotation is costly and slow.

Text classification

Organizations may have millions of documents but only a small manually categorized subset.

Security / anomaly triage

Raw events can be abundant while reliable analyst labels are limited.

Product and content classification

Catalogs may grow faster than humans can accurately label every new item.

When to Consider It—and When to Be Careful

Good reason to investigate it

  • • Reliable labels are expensive or scarce.
  • • You have much more unlabelled data from the relevant population.
  • • The unlabelled structure plausibly relates to the target.
  • • You can evaluate against a trustworthy labelled validation/test set.

Be careful when

  • • Unlabelled data comes from a different population or time period.
  • • Classes overlap and similarity does not imply the same target.
  • • Pseudo-label mistakes are expensive or difficult to detect.
  • • Graph construction is too costly for the data scale.

Evaluation: Keep the Test Labels Truly Hidden

Training pool

Some labels known, others marked unlabelled

Tune / validate

Compare choices fairly

Final labelled test set

Untouched until final evaluation

It is legitimate for a semi-supervised algorithm to use unlabelled training features; that is the point. But final test labels must not leak into training, pseudo-label selection, threshold tuning, graph tuning, or model selection.

Scalability Note

Graph-based methods can become expensive as the number of examples grows. In Scikit-Learn's label-propagation family, the RBF kernel builds a fully connected dense similarity graph, whereas the KNN kernel can use a much sparser neighborhood graph. So “semi-supervised learning scales to millions of examples” is not a safe general claim—the algorithm and representation matter.

Common Mistakes

1

Assuming that more unlabelled data must improve accuracy.

2

Treating a pseudo-label as if it were a human-verified ground-truth label.

3

Evaluating on the same examples whose labels were used during model development.

4

Mixing unlabelled data from a different distribution without checking domain shift.

5

Calling all self-supervised pretraining 'semi-supervised learning'.

6

Ignoring class coverage—for example, having no trustworthy labelled examples for an important class.

Quick Recap

Why can pseudo-labeling fail?

Because model predictions can be wrong. If wrong predictions are accepted as labels, later training rounds may reinforce those errors.

What does -1 mean in Scikit-Learn's graph-based example?

It marks a training sample whose target label is unknown to the semi-supervised algorithm.

Does 0.889 test accuracy prove semi-supervised learning is better?

No. It is one reproducible teaching run. A fair comparison needs suitable supervised baselines using the same label budget and the same held-out evaluation data.

Final Summary

Remember this:

Semi-supervised learning uses a small amount of labelled data together with unlabelled data.The unlabelled examples can provide useful structure, but only when that structure is relevant to the target and the algorithm uses it well. Always compare against a supervised baseline and evaluate on genuinely held-out labelled data.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Semi-Supervised Learning"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What problem does semi-supervised learning solve?
Question 2 of 4
What is the self-training approach to semi-supervised learning?
Question 3 of 4
What is the cluster assumption in semi-supervised learning?
Question 4 of 4
In NLP, BERT uses self-supervised pretraining. How does this relate to semi-supervised learning?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What problem does semi-supervised learning solve?▼

Correct Answer: The high cost of labelling — when you have abundant unlabelled data but few labelled examples, semi-supervised learning leverages unlabelled data structure to improve beyond what labelled data alone achieves

Labels are expensive — expert annotation takes time and money. Unlabelled data is cheap. Methods like self-training, label propagation, and pseudo-labelling bridge this gap.

2What is the self-training approach to semi-supervised learning?▼

Correct Answer: Train on labelled data, predict on unlabelled data, add high-confidence predictions as new labelled examples, retrain. Repeat. Each round expands the labelled set with examples the model is confident about

Self-training risks error propagation — wrong confident predictions become training labels. Use high confidence thresholds (p > 0.95) and monitor carefully.

3What is the cluster assumption in semi-supervised learning?▼

Correct Answer: Points in the same cluster are likely to share the same label — decision boundaries should pass through low-density regions. This allows unlabelled data cluster structure to improve classification boundaries

If this assumption holds, the unlabelled data cluster structure tells you where to draw class boundaries. If it doesn't hold, semi-supervised learning can actually hurt performance.

4In NLP, BERT uses self-supervised pretraining. How does this relate to semi-supervised learning?▼

Correct Answer: BERT's pretraining (predicting masked words in unlabelled text) is self-supervised — labels are derived from the data itself. A form of semi-supervised learning where labelling is automatic. The representations are then fine-tuned with a small amount of task-specific labelled data

Pretraining on massive unlabelled corpora (self-supervised) + fine-tuning on small labelled datasets achieves what previously required millions of labelled examples — the core semi-supervised paradigm at massive scale.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next