AI Logic

Meta-Learning and Few-Shot Learning

Matching Networks

Updated:

Training and classification flow of Matching Networks. The left shows the flow of building an episode, classifying queries, and updating the embedding weights from the loss; the right shows the computation that passes the support set and the query through embeddings g and f, obtains a per-example attention weight from a softmax over cosine similarities, and outputs class probabilities as a weighted sum of labels

Background and Overview

Matching Networks is a few-shot learning method for classifying new classes that have only a handful of labeled examples, without additional training. It was proposed in 2016 by Vinyals et al. at Google DeepMind. It maps the image to be classified (the query) and the examples of each class (the support set) into the same feature space, and produces an answer by mixing the examples' labels, weighting more heavily the examples that are more similar to the query.

Ordinary deep learning needs hundreds to thousands of images and many weight updates to learn a single class. Training a class with only one example in the same way quickly leads to overfitting. On the other hand, a method like nearest neighbors, which "answers with the label of the most similar example," can handle new classes without training, but its accuracy is determined by "what counts as similar."

Matching Networks learns this "way of measuring similarity" with a neural network. Picture training, on many practice problems, the ability to compare an unfamiliar character against five examples and answer "it resembles this example, so it is probably this character." The practice problems (episodes) are built in the same form as the test: "a few classes, a few examples each." The paper presented this as the principle that training and test conditions should match.

In the paper's experiments, 5-way classification on Omniglot, a dataset of character images, reached 98.1% accuracy with one example per class (1-shot), and 93.8% with 20 classes. The paper also created miniImageNet (a small dataset of 100 classes with 600 images each, selected from ImageNet), which has since become widely used as a standard benchmark for few-shot learning.

Training Procedure (Episodic Training)

The task of classifying after seeing kk examples from each of NN classes is called NN-way kk-shot. Matching Networks trains by turning this task format directly into practice problems (Section 2.2 of the paper).

  1. Select several classes (a label set LL) from the training classes. In the paper, for example, up to 5 classes with up to 5 images each.
  2. From the images of the selected classes, draw a support set SS of examples and a batch BB (a collection of queries) whose answers are to be predicted, without overlap.
  3. For each query x^\hat{x} in BB, compute the label probabilities Pθ(y∣x^,S)P_\theta(y \mid \hat{x}, S) using only SS as a cue (the computation is described in the next section).
  4. Update the weights θ\theta of the embedding network so that the log-likelihood of the correct label increases.
  5. Repeat steps 1–4, switching classes from episode to episode.

The objective maximized in step 4 is the following.

θ=arg⁡max⁡θ  EL∼T[ ES∼L, B∼L[∑(x,y)∈Blog⁡Pθ(y∣x,S)]]\theta = \arg\max_\theta \; \mathbb{E}_{L \sim T}\Bigl[\, \mathbb{E}_{S \sim L,\, B \sim L} \Bigl[ \sum_{(x, y) \in B} \log P_\theta(y \mid x, S) \Bigr] \Bigr]

TT is the distribution from which label sets are drawn (the task). At test time, S′S' is built from classes not used in training and classified with the same computation. The weights are not updated at test time. Information about the new classes is simply passed in as input, in the form of the support set.

This "way of building practice problems" called episodes was carried over almost unchanged into later methods such as Prototypical Networks and Relation Network.

How Classification Works (Mixing Example Labels with Attention)

The prediction for a query x^\hat{x} is the sum of the labels yiy_i (one-hot vectors) of the support set S={(xi,yi)}i=1kS = \{(x_i, y_i)\}_{i=1}^{k}, weighted by the attention aa (Eq. (1) of the paper).

y^=∑i=1ka(x^,xi) yi\hat{y} = \sum_{i=1}^{k} a(\hat{x}, x_i)\, y_i

The attention weight is obtained by converting the query and each example into embeddings, measuring their cosine similarity cc, and taking a softmax over all the examples.

a(x^,xi)=exp⁡(c(f(x^),g(xi)))∑j=1kexp⁡(c(f(x^),g(xj)))a(\hat{x}, x_i) = \frac{\exp\bigl(c(f(\hat{x}), g(x_i))\bigr)}{\sum_{j=1}^{k} \exp\bigl(c(f(\hat{x}), g(x_j))\bigr)}

ff is the embedding network for queries and gg the one for examples; they may be the same network. For images a CNN is used, and for text, word embeddings. Since the weights sum to 1, y^\hat{y} is directly a probability for each class. The right side of the figure at the top shows how, when the query resembles the class 2 examples, the attention concentrates on those examples and the probability of class 2 becomes high.

This form can be viewed in several ways.

  • Weighted nearest neighbors: It can be seen as nearest neighbors in which more similar examples get heavier votes. If the weights are viewed as a kernel, it is also close to kernel density estimation.
  • Attention mechanism: It can be seen as a memory from which labels are read out by attention, with the example xix_i as the "key" and the label yiy_i as the "value."
  • Nonparametric: As examples are added, the memory used grows accordingly. New classes are handled simply by passing them as input rather than memorizing them in the weights.

Embedding with the Whole Set in View (Full Context Embeddings)

In the form above, each example xix_i is converted to g(xi)g(x_i) independently of the other examples. The paper proposed two extensions (called FCE) so that the embeddings can change based on the whole support set.

  • Example embedding g(xi,S)g(x_i, S): The CNN features are fed through a bidirectional LSTM as a sequence formed by lining up the support set, and the forward and backward outputs are added to the original features. When similar examples appear side by side, they can be turned into embeddings that are easier to tell apart.
  • Query embedding f(x^,S)f(\hat{x}, S): With the CNN features as input, an LSTM is run for a fixed number of steps (KK) while reading attention over the support set's embeddings. This lets the choice of which examples to rely on adapt to the query.

In the paper, FCE had almost no effect on Omniglot, and gave an improvement of about 2 points on the harder miniImageNet.

Experimental Results

In the paper's Omniglot experiments, the embedding was a small CNN that stacks four blocks of "3×3 convolution (64 channels) → batch normalization → ReLU → 2×2 max pooling," trained on 1,200 characters and evaluated on the remaining characters.

Method (Omniglot)5-way 1-shot5-way 5-shot20-way 1-shot20-way 5-shot
Nearest neighbor with pixel cosine41.7%63.2%26.7%42.6%
Nearest neighbor on classifier features (no fine-tuning)80.0%95.0%69.5%89.1%
Siamese Network (no fine-tuning)96.7%98.4%88.0%96.5%
Matching Networks (no fine-tuning)98.1%98.9%93.8%98.5%

The 5-way accuracies on miniImageNet (split into 80 training classes and 20 test classes) are as follows.

Method (miniImageNet)1-shot5-shot
Nearest neighbor on classifier features (no fine-tuning)36.6%46.0%
Matching Networks41.2%56.2%
Matching Networks (FCE)44.2%57.0%
Matching Networks (FCE, fine-tuned on the support set)46.6%60.0%

On the full ImageNet as well, when 118 classes were held out of training and evaluated 5-way 1-shot, Matching Networks reached 93.2%, versus 87.6% for nearest neighbor on Inception features. For text, the paper built a task of guessing the word that fills a blank from five example sentences (Penn Treebank), reporting 32.4%–38.2% accuracy with 1–3 example sentences (the upper bound for a language model trained on all the data was 72.8%).

Caveats in Practice

It does not work well when the nature of the classes differs greatly between training and test. In the paper's ImageNet experiment, training on non-dog classes and evaluating on dog breeds (118 classes) gave about 1 point lower accuracy than nearest neighbor on Inception features. The paper attributes this to the training episodes being random sets of classes, while the test was fine-grained classification that distinguishes similar classes.

  • The larger the support set, the heavier the computation. Because each query computes its similarity to every example, computation and memory grow in proportion to the number of examples. The paper also lists this as future work.
  • miniImageNet numbers depend on how the classes are split. The split in this paper (80 training and 20 test classes) differs from the split by Ravi and Larochelle that later became widely used (64 training, 16 validation, and 20 test classes). The Matching Networks figures often cited in later papers (1-shot: 43.40% without FCE, 43.56% with FCE) were re-measured on the latter split.
  • The bidirectional LSTM in FCE imposes an order on the support set. A set has no inherent order, so results can vary slightly with the ordering.
  • If the embedding includes batch normalization, model.train() and model.eval() use the statistics differently. Use model.eval() for evaluation.

Comparison with Other Meta-Learning Methods

The table compares representative few-shot classification methods from the same viewpoints.

MethodHow the query is compared with examplesAdaptation to new classesStrengthsWeaknesses
Matching NetworksAttention over cosine similarity to each example, mixing labelsNo gradient computation (examples passed as input)Handles new classes without training; FCE can take the whole set into accountComputation grows with the number of examples; FCE is structurally complex
Prototypical NetworksSquared Euclidean distance to each class's mean embedding (prototype)No gradient computationSimple and fast; especially strong in 5-shotRepresents a class as a single point, so within-class variation is hard to capture
Relation NetworkConcatenates example and query features and scores them with a learned functionNo gradient computationThe comparison itself can be learned from dataAdds a network for comparison; computes for every pair
MAMLNo comparison; adapts from initial weights by gradient descentA few gradient descent steps on the support setApplicable beyond classification (regression, reinforcement learning)Needs gradient computation for adaptation; second-order derivatives are expensive

Rough guidelines for choosing are as follows.

  • For classification only, when you want to try a simple method first, Prototypical Networks is an easy starting point. In 1-shot, with the same distance, it is the same computation as Matching Networks.
  • When you want to compare while preserving per-example differences (variation within a class), Matching Networks, which attends to each example individually, is a good fit.
  • For problems other than classification, or when the model may be trained a little at test time, consider methods that learn an initialization, such as MAML or Reptile.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

"""
Minimal implementation of Matching Networks (without FCE).
Eq. (1) of the paper: ŷ = Σ a(x̂, xᵢ) yᵢ, a = softmax(cos(f(x̂), g(xᵢ))),
Eq. (2): maximize the log-likelihood of the episode's queries
"""

def conv_block(in_ch, out_ch):
  # 3×3 convolution (64 channels) → batch normalization → ReLU → 2×2 max pooling (Section 4.1.1 of the paper)
  return nn.Sequential(
    nn.Conv2d(in_ch, out_ch, 3, padding=1),
    nn.BatchNorm2d(out_ch),
    nn.ReLU(),
    nn.MaxPool2d(2),
  )


class MatchingNetwork(nn.Module):
  def __init__(self, in_ch=1, hidden=64):
    super().__init__()
    # Use the same network for f and g (the paper also allows f = g)
    self.encoder = nn.Sequential(
      conv_block(in_ch, hidden), conv_block(hidden, hidden),
      conv_block(hidden, hidden), conv_block(hidden, hidden),
    )

  def forward(self, support_x, support_y, query_x, n_way):
    """
    support_x: (N*K, C, H, W), support_y: (N*K,) labels in 0..N-1
    query_x:   (Q, C, H, W)
    returns: (Q, N) probability of each class P(y | x̂, S)
    """
    g = self.encoder(support_x).flatten(1)            # g(xᵢ): (N*K, D)
    f = self.encoder(query_x).flatten(1)              # f(x̂):  (Q, D)
    # Cosine similarity c(f(x̂), g(xᵢ)): (Q, N*K)
    cos = F.normalize(f, dim=1) @ F.normalize(g, dim=1).T
    attention = cos.softmax(dim=1)                    # a(x̂, xᵢ), sums to 1 over the examples
    one_hot = F.one_hot(support_y, n_way).float()     # yᵢ: (N*K, N)
    return attention @ one_hot                        # ŷ = Σ a yᵢ: (Q, N)


def episode_loss(model, support_x, support_y, query_x, query_y, n_way):
  probs = model(support_x, support_y, query_x, n_way)
  # −log P(y | x̂, S) of Eq. (2). These are probabilities, so take the log before NLL
  return F.nll_loss(torch.log(probs + 1e-8), query_y)


# Usage (5-way 1-shot, 15 queries per class, 28×28 grayscale images)
n_way, k_shot, n_query = 5, 1, 15
model = MatchingNetwork(in_ch=1)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)

support_x = torch.randn(n_way * k_shot, 1, 28, 28)    # in practice, images selected for each episode
support_y = torch.arange(n_way).repeat_interleave(k_shot)
query_x = torch.randn(n_way * n_query, 1, 28, 28)
query_y = torch.arange(n_way).repeat_interleave(n_query)

model.train()                                         # batch normalization uses the episode's statistics
loss = episode_loss(model, support_x, support_y, query_x, query_y, n_way)
optimizer.zero_grad()
loss.backward()
optimizer.step()

model.eval()                                          # evaluation uses the statistics accumulated during training
with torch.no_grad():
  pred = model(support_x, support_y, query_x, n_way).argmax(dim=1)
  print("accuracy:", (pred == query_y).float().mean().item())

FAQ

Q. Does Matching Networks train (update its weights) at test time?
A.

No. The examples of the new classes are simply passed in as the support set SS, and the query probabilities P(y∣x^,S)P(y \mid \hat{x}, S) can be computed directly. The paper also tries a setting with additional fine-tuning on the support set, but it is not required.

Q. How is it different from nearest neighbors?
A.

Nearest neighbors answers with the label of the closest example under a fixed distance. Matching Networks puts attention weights on all the examples, mixes their labels, and trains the embedding network so that the result is correct. In other words, the difference is that it learns "what counts as similar" from episodic practice problems.

Q. Should FCE (Full Context Embeddings) always be used?
A.

It is not required. In the paper it had almost no effect on Omniglot and improved the harder miniImageNet by about 2 points. Since it makes the architecture more complex and also imposes an order on the support set, it is easiest to try without FCE first.

References

  1. Vinyals, O., Blundell, C., Lillicrap, T., Kavukcuoglu, K., & Wierstra, D. (2016). Matching Networks for One Shot Learning. Advances in Neural Information Processing Systems 29 (NIPS 2016).
  2. Snell, J., Swersky, K., & Zemel, R. (2017). Prototypical Networks for Few-shot Learning. Advances in Neural Information Processing Systems 30 (NIPS 2017).