🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Few-Shot Vision: Prototypical Networks and MAML

Computer VisionFew-Shot VisionđŸŸĸ Free Lesson

Few-Shot Vision

Module: Computer Vision | Difficulty: Advanced

Prerequisites

  • !Softmax classifiers and cross-entropy loss
  • !How a convolutional backbone produces a feature vector
  • !Train / validation / test splits

What You'll Learn

  • 1Explain why episode training matches the few-shot test condition
  • 2Implement a prototypical network and its episodic sampler
  • 3Write a correct inner loop for MAML that stays differentiable
  • 4Report few-shot accuracy without inflating it
  • 5Pick the right family of method for a given label budget

The label wall every classifier eventually hits

A quality inspector wants the network on the inspection line to reject a new weld defect that appeared after the fixture was retooled. There are twelve labeled photographs of it. Gathering twelve thousand more would take a quarter, and by the time the set exists the line has been retooled again. The deployed model meanwhile has a fixed-width output head that cannot represent a class it never saw, and naively retraining that head on twelve images wrecks the accuracy already earned on the original defect catalogue.

Few-shot vision is the study of exactly this constraint. Instead of asking how well a network performs after thousands of examples per class, it asks how quickly a trained network absorbs a small support set for classes it has never encountered while keeping its old competence intact. The vocabulary is small but precise. N is the number of novel classes inside one trial, K is the number of labeled examples supplied for each of them, and the whole trial is called a task or an episode. A five-way one-shot task hands the model one image from each of five new classes and then asks it to classify a further image it has never seen.

The practical appeal is obvious: shipping a new product category becomes an annotation session of minutes rather than a data-collection project of months. The scientific difficulty is subtler, because a model that cheats by leaking information from training classes into evaluation classes will look excellent on a leaderboard and fail the moment it meets real novelty.

Episodes: training on the test condition

Ordinary supervised learning assumes the training classes and the test classes are the same set. Few-shot evaluation removes that assumption. Classes are partitioned into a base split, used for pretraining, and a novel split, used only at evaluation time, and the two never overlap. Holding out entire classes is what makes the measurement honest, because a network that memorized base-class features cannot simply replay them for a novel one.

Training then mirrors the condition it will be graded under. Each step draws N classes, samples K support images plus a batch of query images per class, computes a loss on the queries, and updates the shared parameters. After hundreds of thousands of such steps the optimiser has learned the meta-skill of extracting a usable decision rule from almost no evidence, rather than the object-level skill of recognizing particular categories.

SymbolMeaningTypical value
Nclasses presented in one episode5 or 10
Klabeled support images per class1, 5
Qquery images scored per class15
Eepisodes batched per parameter update4 to 16
Sbase / novel class split ratio64 / 16 (tier 1)

The inner expression performs one gradient step on task i; the outer sum differentiates through it. That nesting is the whole idea of meta-learning: the parameters are optimized for how well they adapt, not for how well they already perform.

Prototypes: classifying by distance in embedding space

The simplest effective approach never updates a weight at test time. A shared encoder maps every image to a vector, the prototype of a class is the mean of its support vectors, and a query is assigned to the class whose prototype it sits closest to. Distance is usually squared Euclidean, negated so that larger values act like logits for a softmax.

Two design choices matter more than they look. First, the encoder must be trained on episodes rather than on plain classification, otherwise the embedding space clusters by base-class identity and gives no guarantee that novel classes form compact groups. Second, squared Euclidean outperforms cosine distance here because it is equivalent to a linear classifier whose weights and bias are determined by the prototypes, which makes the geometry behave predictably when support sets are tiny.

python
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models


class PrototypicalNet(nn.Module):
    def __init__(self, backbone="resnet18", embedding_dim=128):
        super().__init__()
        net = getattr(models, backbone)(weights="IMAGENET1K_V1")
        self.encoder = nn.Sequential(*list(net.children())[:-1])
        self.proj = nn.Linear(net.fc.in_features, embedding_dim)

    def embed(self, x):
        return self.proj(self.encoder(x).flatten(1))

    def forward(self, support, support_y, query, n_way):
        s = self.embed(support)
        q = self.embed(query)
        prototypes = torch.stack(
            [s[support_y == k].mean(0) for k in range(n_way)])
        dists = torch.cdist(q, prototypes).pow(2)
        return -dists


def sample_episode(dataset, n_way, k_shot, n_query):
    classes = random.sample(list(dataset.by_class), n_way)
    sx, sy, qx, qy = [], [], [], []
    for label, cls in enumerate(classes):
        imgs = random.sample(dataset.by_class[cls], k_shot + n_query)
        sx += imgs[:k_shot]
        sy += [label] * k_shot
        qx += imgs[k_shot:]
        qy += [label] * n_query
    return torch.stack(sx), torch.tensor(sy), torch.stack(qx), torch.tensor(qy)


model = PrototypicalNet()
opt = torch.optim.Adam(model.parameters(), lr=1e-3)

for step in range(4000):
    support, sy, query, qy = sample_episode(train_set, 5, 1, 15)
    logits = model(support, sy, query, n_way=5)
    loss = F.cross_entropy(logits, qy)
    opt.zero_grad()
    loss.backward()
    opt.step()

MAML: learning an initialization instead of a classifier

Model-Agnostic Meta-Learning takes the opposite route. It looks for a set of initial weights such that a few gradient steps on a support set produce a working classifier for that task. The inner loop clones the current weights and descends on the support loss; the outer loop scores the adapted weights on query images and backpropagates through the inner descent itself.

Differentiating through the inner loop requires retaining the computation graph, which is why full MAML is expensive: memory grows with the number of inner steps. First-order variants drop the second-order terms and simply treat the inner gradients as constants, cutting memory substantially at a small accuracy cost. Reptile goes further and averages weights across tasks, which is cheap but loses the clean meta-objective.

python
import torch
import torch.nn.functional as F
from torch import nn, optim
from torch.func import functional_call


class TinyCNN(nn.Module):
    def __init__(self, num_classes=5):
        super().__init__()
        self.conv = nn.Conv2d(3, 32, 3, padding=1)
        self.head = nn.Linear(32, num_classes)

    def forward(self, x):
        x = F.max_pool2d(F.relu(self.conv(x)), 2)
        return self.head(F.adaptive_avg_pool2d(x, 1).flatten(1))


model = TinyCNN()
names = [n for n, _ in model.named_parameters()]
meta_opt = optim.Adam(model.parameters(), lr=1e-3)


def forward_with(params, x):
    return functional_call(model, dict(zip(names, params)), x)


def adapt(params, x, y, lr=0.05, steps=3):
    out = list(params)
    for _ in range(steps):
        loss = F.cross_entropy(forward_with(out, x), y)
        grads = torch.autograd.grad(loss, out, create_graph=True)
        out = [p - lr * g for p, g in zip(out, grads)]
    return out


for episode in range(3000):
    s_x, s_y, q_x, q_y = sample_episode(train_tasks, n_way=5, k_shot=5)
    adapted = adapt(list(model.parameters()), s_x, s_y)
    meta_loss = F.cross_entropy(forward_with(adapted, q_x), q_y)
    meta_opt.zero_grad()
    meta_loss.backward()
    meta_opt.step()

create_graph=True is the line that makes the second backward pass reach the original weights. Set it to False and you have implemented first-order MAML instead.

Matching the method to your label budget

MethodGradients at test timeTrain costOne-shot accuracySensitivity to tuning
Fine-tuned linear headYesLowPoorHigh
Matching NetworksNoLowGoodLow
Prototypical NetworksNoLowGoodLow
MAML, full second orderYesVery highStrongestHigh
FOMAML or ReptileYesHighGoodMedium
Linear probe on a frozen self-supervised encoderNoMinimalOften competitiveLow

If your encoder is already strong and K is one, a frozen backbone with a nearest-centroid classifier is a serious baseline and costs nothing to train. Reach for prototypical networks when you want a clean, fast, differentiable pipeline. Reach for MAML only when tasks genuinely differ in their optimal decision boundary, for example when the same five categories must be separated under different camera settings, because that is where adaptation beats representation. Over-provisioning compute for MAML on a simple class-novelty problem buys almost nothing.

How few-shot numbers get inflated

Evaluating a few-shot model is easier to get wrong than training one. The standard protocol is to sample a large number of held-out episodes, average the accuracy, and report a 95 percent confidence interval across those episodes. Single-episode numbers are meaningless variance. Beyond that, four errors recur constantly.

Random class splits let a novel class leak into pretraining, and the reported gain evaporates on the next split. Batch normalization statistics computed over support and query images let information flow between the two, which is transductive and must be declared. Reporting the best seed out of ten turns noise into a headline. And comparing against a baseline that was not trained episodically makes the baseline look worse than it is, since a class-incremental model without episodic training is not a fair control.

A defensible evaluation freezes the class split, averages at least six hundred episodes, states whether any test-time adaptation happened, and includes a frozen-encoder nearest-centroid baseline so readers can see how much the meta-learning machinery actually contributed.

Common Mistakes

Training the encoder with ordinary softmax classification and only switching to episodes at evaluation

Fix: Sample N-way K-shot episodes during training too, so the embedding space is shaped for the test condition

Reporting accuracy from a single episode or a single random seed

Fix: Average over several hundred sampled episodes and publish a confidence interval

Letting novel classes appear in pretraining data

Fix: Split classes first, images second, and verify the base and novel sets are disjoint

Running batch normalization in training mode over the support and query batches together

Fix: Freeze running statistics, or normalize support and query separately

Best Practices

  • Establish a frozen-encoder nearest-centroid baseline before implementing anything fancier
  • Pretrain with a self-supervised objective so the encoder transfers to classes outside its pretraining taxonomy
  • Use squared Euclidean distance for prototypes and keep embeddings L2-normalized only if you have measured the difference
  • Log the class split alongside the checkpoint so results stay reproducible
  • Budget meta-training steps by episodes seen rather than epochs, since epochs are undefined in this setting

Interview Questions

Q1: Why must support and query classes be disjoint from the classes used for pretraining?

Otherwise the model can win by recognizing base-class features instead of learning to learn. Novelty only means something when the class identity itself was never available during training.

Q2: What does an inner loop mean in MAML, and what goes wrong if you forget create_graph?

The inner loop is a short SGD run on the support set starting from the current meta-parameters. Without create_graph the inner-step computation is detached, so the outer loss cannot send gradient back through the adaptation and the model never learns a good initialization.

Q3: When would you pick prototypical networks over MAML?

When tasks share a decision boundary and differ only in class identity, and when test-time gradients are unacceptable. MAML pays off when tasks differ in how the boundary must be drawn, such as changing capture conditions.

Q4: How do you evaluate a few-shot model honestly?

Sample many held-out episodes from a frozen disjoint class split, average accuracy, report a confidence interval, declare any transductive or test-time steps, and include a simple frozen-encoder baseline.

Key Takeaways

  • Few-shot vision is measured in N-way K-shot tasks, not epochs, and classes are split before images so novelty is real
  • Episode training makes the optimization loop look like the evaluation loop, which is the entire reason it works
  • Prototypical networks classify by distance to class means in a learned embedding and need no test-time gradients
  • MAML optimizes an initialization by differentiating through a short inner gradient run, which is accurate but expensive
  • First-order approximations such as FOMAML and Reptile trade a little quality for much lower memory
  • A frozen self-supervised encoder with a nearest-centroid head is the baseline every fancier method must beat
  • Confidence intervals across hundreds of episodes, not single runs, are the honest unit of reporting
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Computer Vision Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement