Practical Deep Learning/Meta-Learning and Few-Shot Learning

Lesson 10.73,195 words

Meta-Learning and Few-Shot Learning

A deep network trained on one example per class overfits. Meta-learning targets this few-shot regime by training across a distribution of tasks so that a new task is learnable from a handful of examples.

╌╌╌╌

A supervised learner is trained on one task and tested on held-out examples of that same task. Meta-learning changes the unit of experience: the learner is trained on a distribution over tasks and tested on its ability to acquire a new task from a few examples. This is learning to learn, and it is the formal account of why a person who has seen a thousand object categories needs only one photograph to learn the thousand-and-first.1 The right inductive bias, tuned across many tasks, is what makes one example enough.2 The skill being optimized is not a classifier but the procedure that produces one.

This lesson connects directly to transfer learning: both reuse experience across tasks. Transfer reuses a representation; meta-learning reuses a learning algorithm, and the line between them blurs at the modern end, where a frozen large language model performs new tasks from a few in-context examples with no gradient step at all.

The few-shot problem

Fix a space of tasks. Each task is a small classification problem drawn from a common distribution; the learner never sees enough examples of any one task to solve it in isolation, but it sees many tasks and must extract what they share.

regularization choice: it targets generalization of the learned procedure, not memorization of the shots.3 Meta-learning optimizes expected post-adaptation performance

, where is the learning procedure and is the task's few labeled examples.

The training signal arrives in episodes. Each episode samples a task, splits its data into a tiny labeled support set the learner adapts on and a query set it is scored on, and the meta-objective rewards low query loss after adaptation. The episode is the atom of meta-learning, and its shape is named by two numbers.

For example, take a -way -shot episode with queries per class and a backbone that embeds each image to dimensions. The support holds labeled images; the query holds . After embedding, the support is a matrix of shape and the query a matrix of shape . A prototypical classifier reduces the support to prototypes (), then computes a distance matrix, one distance from each query to each prototype, and takes a row-wise softmax to get class probabilities. The entire episode is a handful of matrix operations; its cost is dominated by the forward passes through the backbone.

The classes used to build meta-training episodes are disjoint from those used at meta-test time: the model must classify categories it never saw, judged only on its ability to learn them from shots.

A 3-way 2-shot episode. The support set (left) labels two examples per class; the query (right) is classified by the procedure adapted on the support.

Two strategies dominate, and they differ in what is meta-learned. Metric-based methods meta-learn an embedding so that a fixed, parameter-free rule (nearest neighbor) classifies; optimization-based methods meta-learn an initialization so that a few steps of ordinary gradient descent adapt. A third model-based family folds the whole learning procedure into a network's forward pass.

FamilyWhat is meta-learnedAdaptation at test timeCost
metric-basedan embedding compute support statistics, compare distancescheap; one forward pass
optimization-basedan initialization run gradient steps on the supportcostly; backprop-through-backprop
model-baseda network that ingests a single conditioned forward passcheap forward; hard to train
The three meta-learning families, split by what is meta-learned and whether a gradient step runs at adaptation time.

Metric-based meta-learning

The idea is to learn an embedding such that examples of the same class land close together and different classes land far apart. Then a new task needs no training, only its support embeddings and a distance. This rests on distributed representations placing similar inputs near one another, so that geometric proximity in feature space carries class information.45

Siamese and matching networks

The earliest version trains a network to decide whether two images share a class. A Siamese network embeds both inputs with the same weights and scores their agreement, turning classification into a learned similarity.

Matching Networks generalize the nearest-neighbor rule into a differentiable, attention-weighted vote over the entire support set, so the whole episode is trained end-to-end against the query loss.

Prototypical networks

Matching Networks compare a query to every support point. Prototypical Networks compress each class to a single point, its prototype, the mean of its support embeddings, and classify a query by the nearest prototype. The model is a parameter-free softmax over negative squared distances.

The prototypical-network pipeline for a 3-way 2-shot episode. The shared embedding maps every support image to ; each class prototype is the mean of its two support embeddings; the query is embedded and assigned the class of the nearest prototype under squared Euclidean distance.

For example, take classes and suppose a query embeds to at squared distances , , from the three prototypes. The logits are the negatives ; exponentiating gives , , , which sum to . The probabilities are , , : the nearest prototype dominates, and the softmax is sharp because distances enter the exponent directly. Doubling the embedding scale (multiplying by ) quadruples every distance, which sharpens the softmax further, so the embedding's overall scale acts as an implicit temperature the network is free to learn.

Geometrically, the prototypes act as reference points, and the softmax over negative distances partitions the embedding space into Voronoi-like cells that are the class regions.

Prototypical networks. Each class prototype (square) is the mean of its support embeddings (dots); a query is assigned the nearest prototype's class.

Training minimizes the negative log-probability of the true class on the query set, averaged over episodes. Because every operation (embed, average, distance, softmax) is differentiable, gradients flow back into .

Algorithm:ProtoNetEpisode(S,Q,fθ)\textsc{ProtoNetEpisode}(\mathcal{S}, \mathcal{Q}, f_\theta) — one meta-training episode
  1. 1
    L0L \gets 0
  2. 2
    for c1c \gets 1 to NN do
  3. 3
    cc1K(xi,yi)Scfθ(xi)\mathbf{c}_c \gets \frac{1}{K}\sum_{(x_i, y_i)\in \mathcal{S}_c} f_\theta(x_i)
    class prototype = mean support embedding
  4. 4
    for each (x,y)(x^\ast, y^\ast) in Q\mathcal{Q} do
  5. 5
    for c1c \gets 1 to NN do
  6. 6
    dcfθ(x)cc2d_c \gets \norm{f_\theta(x^\ast) - \mathbf{c}_c}^2
    squared distance to each prototype
  7. 7
    LL+dy+logcexp(dc)L \gets L + d_{y^\ast} + \log \sum_{c} \exp\parens{-d_c}
    negative log-softmax of true class
  8. 8
    update θ\theta by gradient descent on L/QL / \abs{\mathcal{Q}}
    backprop into the embedding
  9. 9
    return θ\theta

The theorem explains why squared Euclidean distance is the right choice and cosine distance underperforms: it makes the classifier a linear readout whose weights are the prototypes, recovering a Bregman-divergence mean-classifier rather than an arbitrary metric.4

Optimization-based meta-learning

Metric methods bake in a fixed classification rule. Optimization-based methods keep ordinary gradient descent as the adaptation rule and instead meta-learn the starting point. The adaptation itself is nothing exotic: it is the same gradient step that trains any network, run for a few iterations on the support set.67 The goal is an initialization that sits a few gradient steps away from a good solution for any task in .

MAML and the bi-level objective

Model-Agnostic Meta-Learning (MAML) is model-agnostic because it adds nothing to the architecture: it only changes how the initialization is trained. The inner loop adapts to a task with one (or a few) gradient steps on its support loss; the outer loop updates so that this adaptation generalizes, scored on the query loss after adaptation.

The objective is bi-level: the outer minimization over contains, inside its loss, the inner minimization that produced . Differentiating it is the crux. By the chain rule, the meta-gradient of one task's query loss is

Differentiating the one-step update with respect to gives the inner Jacobian

so the exact meta-gradient carries a Hessian of the support loss:

This is the second-order MAML update: backpropagating through the inner gradient step requires a Hessian-vector product, differentiating the gradient itself.

The dimensions clarify why this is expensive yet the Hessian is never materialized. Let with the parameter count. The query gradient is a vector in ; the inner Jacobian and the Hessian are matrices. Forming a Hessian is impossible for a real network ( is in the millions), but the meta-gradient only ever multiplies it by a vector:

The Hessian-vector product is one extra backward pass (reverse-mode over the inner gradient), so the exact meta-gradient costs roughly two backward passes per task, not the storage a full Hessian would need. For inner steps, the chain rule nests such Jacobians, and the cost grows linearly in .

MAML as a computation graph for one task. Forward (top): the meta-parameter takes an inner gradient step on the support loss to the adapted , which is scored on the query loss. Backward (bottom): the meta-gradient flows through into , passing the inner Jacobian . FOMAML cuts the dashed second-order edge, treating as constant in .

FOMAML loses little accuracy in practice while removing the cost of the Hessian term, evidence that most of the meta-signal is in the first-order direction.8 The two loops are nested: an inner trajectory per task, an outer step that moves the shared start.

MAML. From a shared initialization, each task takes inner gradient steps to its own optimum; the outer step moves the start to minimize post-step loss.
Algorithm:MAML(p(T),α,β)\textsc{MAML}(p(\mathcal{T}), \alpha, \beta) — meta-learn an initialization
  1. 1
    initialize meta-parameters θ\theta
  2. 2
    while not converged do
  3. 3
    sample a batch of tasks T1,,TBp(T)\mathcal{T}_1, \dots, \mathcal{T}_B \sim p(\mathcal{T})
  4. 4
    for i1i \gets 1 to BB do
  5. 5
    θiθαθLTispt(θ)\theta_i' \gets \theta - \alpha\,\nabla_\theta \mathcal{L}^{\text{spt}}_{\mathcal{T}_i}(\theta)
    inner loop: adapt on support
  6. 6
    θθβθiLTiqry(θi)\theta \gets \theta - \beta\,\nabla_\theta \sum_{i} \mathcal{L}^{\text{qry}}_{\mathcal{T}_i}(\theta_i')
    outer loop: meta-update on query
  7. 7
    return θ\theta

Reptile: first-order without a query split

Reptile removes even the support/query distinction. It runs several SGD steps on a task to reach , then moves the initialization toward that point.7 The meta-update is a difference of parameter vectors, no second derivative anywhere.

Reptile works because , averaged over tasks, points toward a point near each task's manifold of solutions, exactly where a few more steps land fastest. It is the cheapest of the three and a strong default when compute is tight.

MethodMeta-gradientHessian neededQuery split
MAML (2nd-order)yesyes
FOMAMLnoyes
Reptile (direction)nono

A related thread treats the optimizer itself as a learnable network: an LSTM meta-learner that ingests the gradient at each step and emits the parameter update, learning a task-specific update rule in its hidden state rather than a fixed .6

Model-based meta-learning

Metric and optimization methods both run an explicit adaptation procedure at test time. Model-based (black-box) methods absorb the procedure into a single network whose forward pass reads the support set and then classifies the query, so learning is one conditioned inference.

The canonical instance is a memory-augmented neural network: a controller writes each support embedding into an external, content-addressable memory, then reads the slot most similar to the query to recover its label, learning a write-then-retrieve policy that generalizes to new classes. This family is the conceptual bridge to in-context learning: a forward pass that adapts because the support is in its input, not in its weights.

Connections: transfer, and in-context learning

Meta-learning, transfer learning, and the few-shot behavior of large language models form a spectrum distinguished by where task-specific information lives and whether a gradient step occurs at adaptation time.

ParadigmCross-task signal reusedAdaptation mechanismGradient at test?
transfer / fine-tuninga pretrained representationfine-tune a head on target datayes
metric meta-learningan embedding metriccompute support statisticsno
optimization meta-learningan initializationa few inner gradient stepsyes (inner)
in-context (LLM)a sequence model's weightscondition on examples in the promptno

Transfer learning meta-learns implicitly: pretraining on a broad source task yields features that adapt to many targets, which is the few-shot objective with a single giant task: feature extraction reuses the frozen representation, and fine-tuning takes a few gradient steps on it, exactly the metric and optimization mechanisms seen above, applied to one source instead of a task distribution.9 The most recent form is in-context learning: a frozen large language model shown a few input–output pairs in its prompt performs the new task with no weight update, the support set living entirely in the context window.

This is meta-learning whose inner loop is a forward pass. Pretraining on a vast distribution of implicit tasks (every document is a different prediction problem) plays the role of the meta-training distribution ; the prompt's demonstrations play the role of the support set; and the model's conditioning on them is an implicit adaptation algorithm learned by the same gradient descent that trained the weights. The forward pass has learned to be a learning algorithm.1

Evaluation

Two benchmarks anchor the literature. Omniglot is handwritten characters from alphabets with examples each, the transpose of MNIST (many classes, few examples), well suited to few-shot evaluation. miniImageNet is ImageNet classes ( train, validation, test) at resolution, the harder natural-image standard. Accuracy is reported on held-out classes, averaged over hundreds of sampled -way -shot test episodes with confidence intervals.

Few-shot accuracy rises with shots and falls with ways . More support per class helps; more classes to disambiguate hurts.

The comparison across the families, on mechanism rather than a leaderboard number (which shifts with backbone and year):

MethodMechanismWhat is learnedAdaptation cost
Siameselearned pairwise similarityan embedding + similarity headone forward pass per pair
Matching Networksattention-weighted support votean embedding + context encoderone forward pass over
Prototypical Networksnearest class-mean prototypean embedding (parameter-free rule)mean + distances, one pass
MAMLfew inner gradient steps from a meta-initan initialization steps + 2nd-order backprop
Reptilemove init toward post-SGD parametersan initialization SGD steps, first-order only

Strong baselines and the in-context turn

Two findings since the classic meta-learning papers reshaped how the field thinks about few-shot learning — one deflationary, one transformative.

The deflationary result is that a good representation plus a simple classifier often beats elaborate meta-learning. Chen et al. (2019, ICLR, A Closer Look at Few-Shot Classification) and the Meta-Baseline line (Tian et al., 2020, ECCV) showed that plainly pretraining a backbone on all the base classes with ordinary supervised cross-entropy, then fitting a nearest-centroid or logistic-regression head on the support set, matches or beats MAML and Prototypical Networks on miniImageNet. The episodic training machinery this lesson builds turned out to be less important than the quality of the embedding it produced — an echo of the representation-learning thesis that a good code makes the downstream task easy. A related result, ANIL (Raghu et al., 2020, ICLR, Almost No Inner Loop), showed MAML's inner-loop adaptation barely changes the feature extractor at all: nearly all the benefit comes from adapting the final layer, so MAML is mostly learning a reusable representation, not a fast learner.

The transformative result is in-context learning. A large language model (Brown et al., 2020, NeurIPS, Language Models are Few-Shot Learners) performs a new task from a handful of examples placed in its prompt, with no gradient step at all — the frozen forward pass conditioned on the support set is the adaptation. This is precisely the model-based meta-learning goal from the previous section, achieved as an emergent property of scale rather than an explicit meta-objective: the -way -shot episode becomes demonstrations in the context window. The formal account is still being worked out — evidence suggests the forward pass implements something like implicit gradient descent or Bayesian inference over the demonstrations — but the practical upshot is settled. For text, and increasingly for vision and multimodal tasks, few-shot learning is now done by prompting a foundation model, and the explicit meta-learners of this lesson remain useful mainly where episodes are cheap and a small specialized model is preferable to a giant general one.

Takeaways

  • Meta-learning trains across a distribution of tasks so a new task is learnable from few examples; the unit of experience is the -way -shot episode with its support and query sets, and meta-train/meta-test classes are disjoint.
  • Metric methods learn an embedding where a fixed distance classifies. Prototypical Networks use the class-mean prototype and a softmax over negative squared distances, which (by the expansion of the square) is a linear classifier whose weights are the prototypes.
  • Optimization methods learn an initialization. MAML's bi-level objective minimizes post-adaptation query loss; its exact meta-gradient carries a Hessian , which FOMAML drops and Reptile avoids entirely by moving the init toward post-SGD parameters.
  • Model-based methods fold adaptation into a conditioned forward pass (memory-augmented nets), the bridge to in-context learning.
  • The paradigm is a spectrum with transfer learning and with in-context learning in large language models, where a frozen model's forward pass, conditioned on a few prompt demonstrations, is the learning algorithm meta-learning sought to produce.

Footnotes

  1. Goodfellow, Deep Learning, §15.2 — representation learning: features learned on many tasks transfer to new ones, the principle that reusing cross-task experience is a route to data-efficient acquisition of a new task. 2
  2. Goodfellow, Deep Learning, §5.6 — capacity, overfitting, and inductive bias: a learner biased toward the right hypothesis class generalizes from fewer examples, which is what meta-learning tunes across tasks.
  3. Goodfellow, Deep Learning, §7 — regularization and generalization: controlling the effective complexity of the adaptation is what lets a query loss, not a support loss, be the true objective.
  4. Goodfellow, Deep Learning, §15.4 — distributed representations place similar inputs near one another in feature space, the property a learned embedding exploits so that distance carries class information. 2
  5. Chollet, Deep Learning with Python, §6.1 — embeddings map inputs to a vector space where geometric proximity reflects semantic similarity; a nearest-neighbour rule in that space is then a classifier.
  6. Goodfellow, Deep Learning, §8 — gradient-based optimization: a single step decreases the loss locally, the inner-loop update meta-learning differentiates through. 2
  7. Stevens, Deep Learning with PyTorch, §5.5 — a training loop is repeated gradient steps on batches; the inner loop here runs such a loop for a few steps on the support set. 2
  8. Goodfellow, Deep Learning, §4.3, §8.6 — second-order information (the Hessian) describes how the gradient changes; differentiating through a gradient step therefore introduces a Hessian-vector product.
  9. Chollet, Deep Learning with Python, §5.3 — feature extraction and fine-tuning reuse a pretrained representation on a small target dataset, the transfer-learning limit of the few-shot objective.

╌╌ END ╌╌