Skip to main content
LearnMLAcademy
Advanced10 min read

Self-Supervised and Few-Shot Learning

Train representations without labels using contrastive learning and few shots, with sequence diagrams, attention calculations, and model-code exercises.

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

Deep Learning · Learning with Limited Labels

Learn how a model can pretrain representations from unlabelled data, then adapt those representations when only a small labelled support set is available. Self-supervised and few-shot learning are connected, but they solve different parts of the limited-label problem.

The Problem: Useful Data, Very Few Labels

Many projects can collect images, recordings or documents cheaply, but trustworthy labels require scarce expert time. Two ideas address different parts of this problem. Self-supervised learning first learns representations from unlabelled data by creating supervision from the data itself. Few-shot learning asks a trained system to recognize a new task or new classes from only a tiny labelled support set.

They can be used separately or together: an encoder may learn from a large unlabelled collection, then support a few-shot classifier when only one to five examples of a new class arrive.

Self-Supervised Learning: Learn from Data Before Adding Labels

Suppose a hospital owns one million unlabelled scans but radiologists have labelled only 2,000. Throwing away the unlabelled scans wastes information about common shapes and textures. Self-supervised learning creates a learning target from the data itself, so an encoder can learn useful representations before the smaller labelled task begins.

One family is contrastive learning. It treats two changed views of the same item as a positive pair and views from other items as negative examples. A projection head temporarily maps encoder features into the space where the contrastive loss is calculated. After pretraining, that projection head is commonly discarded and the encoder is transferred to a labelled task.

Self-supervision creates its own training signal from an unlabelled image

🚲

one unlabelled image

→

random crop + colour change

view A → shared encoder → vector z₁

↘
→

different crop + blur

view B → same encoder → vector z₂

↗

pull z₁ and z₂ together

same source image = positive pair

separate other images

different sources = negatives

The labels come from how the views were created, not from a person naming the object. The chosen augmentations define which changes the representation should ignore.

A Small Contrastive-Loss Calculation

A simplified InfoNCE-style objective turns similarities into a probability. For anchor i and its positive view j:

Lᵢ = −log [ exp(sᵢⱼ/τ) / Σₖ exp(sᵢₖ/τ) ]

sᵢₖ is a model-produced similarity between the anchor and candidate k. τ is a positive developer-chosen temperature: dividing by a smaller τ spreads the softmax scores more sharply. Exponentiation makes comparison weights positive, normalization makes them sum to 1, and −log penalizes low positive probability.

One positive and two negatives

For a transparent demonstration, use already temperature-scaled scores 2 for the positive and 0 and 1 for two negatives. These three numbers are manually chosen; a real encoder and temperature produce them.

positive probability = e² / (e² + e⁰ + e¹)
= 7.389 / (7.389 + 1 + 2.718)
≈ 0.665

loss = −ln(0.665) ≈ 0.408

Meaning: increasing positive similarity relative to the negatives raises that probability and lowers loss. Production implementations must handle both directions, masking and numerical stability.

The Augmentations Define What “Same” Means

Contrastive learning is not automatically correct simply because labels are absent. If colour determines whether fruit is ripe, aggressive colour removal may teach the encoder to ignore the very evidence needed downstream. If left and right have different medical meaning, a horizontal flip can create a false positive pair.

DecisionQuestion to askFailure if wrong
View generationShould prediction remain unchanged after this crop, blur, flip or colour shift?False positive pairs erase useful information
Negative samplingCould two different records actually mean the same thing?False negatives push related examples apart
Data splitWere near-duplicates/patients/users separated before pretraining evaluation?Leakage overstates transfer quality
EvaluationDoes a linear probe or fine-tuned target model beat simple baselines?Low pretext loss may not mean useful features

Evaluate the Representation, Not Only the Pretraining Loss

A low contrastive or reconstruction loss does not prove that the encoder learned features useful for the real task. Freeze the encoder and train a simple linear classifier on top: this linear probe tests how accessible the target information already is. Then compare controlled fine-tuning, a generic pretrained encoder and a scratch baseline using the same splits and metrics.

Keep the test honest: separate patients, users, documents or time periods before pretraining evaluation, report performance across label budgets, and inspect class-level failures. Otherwise duplicates or selection effects can make an unhelpful representation look strong.

Few-Shot Learning: Adapt from a Tiny Support Set

Few-shot learning evaluates whether a system can handle a new task or new classes from very few labelled examples. In a 5-way 1-shot image episode, the support set contains one labelled example for each of five classes. The model must classify separate query examples from those same episode classes.

This is different from ordinary fine-tuning on a small dataset: few-shot methods are commonly trained across many episodes so the learning procedure matches how the model will be tested. Meta-learning is the broader idea of learning across tasks so adaptation to a new task becomes faster; metric-based prototypes are one approach, while optimization-based methods such as MAML learn an initialization that can adapt in a few gradient steps.

A 2-way 2-shot episode: classify the query by the nearest class prototype

support set (labelled)C1C1C2C22 classes × 2 examplesaverage eachembedding spaceP1P2?distance 1distance 3query predictionclass 1nearest prototype
Way is the number of classes in an episode; shot is the labelled support examples per class. The unlabelled item being classified is the query.

Worked Example: Classify with Two Prototypes

A prototypical classifier embeds each support example, averages embeddings within a class, then assigns a query to the nearest class average (the prototype). The two-dimensional coordinates below are manually chosen teaching embeddings. In a real episode the encoder produces them from labelled support items and an unlabelled query.

class 1 supports: (1,1), (1,3)
prototype c₁ = ((1+1)/2, (1+3)/2) = (1,2)

class 2 supports: (5,1), (5,3)
prototype c₂ = (5,2)

query q = (2,2)
d(q,c₁) = √[(2−1)²+(2−2)²] = 1
d(q,c₂) = √[(2−5)²+(2−2)²] = 3

Why average and measure distance? Averaging creates one representative centre per class; Euclidean distance measures how far the query lies from each centre. The result is class 1 because distance 1 is smaller than distance 3. Real performance depends on whether the encoder learned a space where semantic classes form useful clusters.

Choose the Strategy That Matches the Data You Actually Have

SituationStrong first approachWhyMain check
Related public checkpoint + modest labelled target setTransfer learningReuse broad features and train a target headCompare frozen and fine-tuned validation results
Large in-domain unlabelled collection + few labelsSelf-supervised pretraining, then transferLearn domain representations before using scarce labelsProbe/fine-tune against generic pretrained and scratch baselines
New classes arrive with 1–5 examples eachFew-shot metric/meta-learningMake support/query adaptation part of trainingEvaluate on genuinely unseen classes/tasks
Enough representative labels and computeSupervised pretraining or training from scratch as a baselineDirect objective may be simplestMatch compute, split and selection fairly
Different domain and weak source matchIn-domain self-supervision or closer source modelReduces source-target mismatchWatch negative transfer and augmentation validity

These methods can form one pipeline: self-supervise an encoder on unlabelled in-domain data, transfer it to episodic training, then classify new classes from a few support examples.

The Limited-Label Learning Checklist

  1. Define the unlabelled collection, target task and label budget before selecting a method.
  2. Design self-supervised views around transformations that should preserve downstream meaning.
  3. Evaluate representations with a linear probe or controlled fine-tuning baseline.
  4. For few-shot claims, separate support and query examples and test on genuinely unseen classes or tasks.
  5. State the N-way K-shot episode design and compare prototypes with simple nearest-neighbour baselines.
  6. Report variation across episodes, domain shift, compute and failure cases—not one average accuracy alone.

Continue Learning

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 "Self-Supervised and Few-Shot 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.

Summary / Key Takeaways

  • Self-supervision derives training signals from the data itself.
  • Contrastive learning pulls related views together and separates unrelated examples.
  • A pretext task matters only when its representation transfers.
  • Few-shot learning adapts from a small labelled support set.
  • Augmentation, negatives, leakage, and episode design change results.
  • Compare specialized methods with pretrained transfer-learning baselines.

Knowledge Check

Progress: 0/5

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

Question 1 of 5conceptual
Where does a self-supervised target come from?
Question 2 of 5conceptual
What does a contrastive objective encourage?
Question 3 of 5interpretation
Why must two augmented views preserve identity?
Question 4 of 5conceptual
What are support and query sets in few-shot evaluation?
Question 5 of 5practical selection
What baseline should a few-shot method be compared with?

Knowledge Check Review & Explanations

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

1Where does a self-supervised target come from?▼

Correct Answer: A transformation or hidden part of the data itself

The learning signal is constructed from relationships already present in unlabelled data.

2What does a contrastive objective encourage?▼

Correct Answer: Related views close and unrelated examples apart

Similarity structure teaches representations that may transfer to downstream tasks.

3Why must two augmented views preserve identity?▼

Correct Answer: They are treated as a positive pair

If augmentation changes semantic identity, the objective pulls genuinely different examples together.

4What are support and query sets in few-shot evaluation?▼

Correct Answer: Support examples enable adaptation; query examples measure it

Keeping query examples separate measures generalization after limited support information.

5What baseline should a few-shot method be compared with?▼

Correct Answer: A pretrained transfer-learning approach under the same split

Pretrained representations can already perform strongly with few labels, so specialized complexity needs evidence.

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