AI Logic

Meta-Learning and Few-Shot Learning

Prototypical Networks

Updated:

Training and classification flow of Prototypical 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 the same embedding f_φ, takes the mean of the examples in the embedding space as prototype c_k, and outputs class probabilities from a softmax over distances to the query

Background and Overview

Prototypical Networks is a few-shot learning method that builds one point per class, the mean of the examples' embeddings (the prototype), and classifies the image in question (the query) into the class of the nearest prototype. It was proposed in 2017 by Snell, Swersky, and Zemel at the University of Toronto.

When classifying new classes with only a few examples, the biggest danger is overfitting. The paper reasons that the less data there is, the simpler the classifier should be, and makes a strong assumption: "in a good embedding space, points of the same class cluster around a single representative point." Picture seeing a dog breed for the first time, imagining its "typical appearance" from a few photos, and answering according to which typical appearance the photo in question is closest to.

Whereas the earlier Matching Networks attends to each example individually and mixes their labels, Prototypical Networks simply averages the examples of each class into one point. The structure is much simpler, but by choosing designs such as the squared Euclidean distance, it reached 68.20% on 5-way 5-shot miniImageNet in the paper, far ahead of methods of the time. For new classes it needs neither gradient computation nor weight updates; it classifies just by computing means and distances.

Training Procedure (Episodic Training)

The embedding network fϕf_\phi is trained by repeatedly solving, as practice problems (episodes), the task of classifying after seeing NSN_S examples from each of NCN_C classes (NCN_C-way NSN_S-shot). The procedure follows Algorithm 1 of the paper.

  1. Select NCN_C classes from the training classes.
  2. For each selected class, take NSN_S images as the support set SkS_k and NQN_Q of the rest as the queries QkQ_k.
  3. For each class, average the embeddings of the support set to form the prototype ckc_k (Eq. (1)).
  4. For each query, compute the class probabilities from its distances to all prototypes (Eq. (2)).
  5. Average the negative log-probability of the correct class J(ϕ)=−log⁡pϕ(y=k∣x)J(\phi) = -\log p_\phi(y = k \mid x) over all queries, and update ϕ\phi by gradient descent.

The formulas for steps 3 and 4 are as follows.

ck=1∣Sk∣∑(xi,yi)∈Skfϕ(xi),pϕ(y=k∣x)=exp⁡(−d(fϕ(x),ck))∑k′exp⁡(−d(fϕ(x),ck′))c_k = \frac{1}{|S_k|} \sum_{(x_i, y_i) \in S_k} f_\phi(x_i), \qquad p_\phi(y = k \mid x) = \frac{\exp\bigl(-d(f_\phi(x), c_k)\bigr)}{\sum_{k'} \exp\bigl(-d(f_\phi(x), c_{k'})\bigr)}

dd is a distance function; the paper's experiments use the squared Euclidean distance d(z,z′)=∥z−z′∥2d(z, z') = \|z - z'\|^2. Eq. (2) passes the negated distances through a softmax, and the loss has the same form as cross-entropy. The right side of the figure at the top shows how the query is closest to the class 2 prototype, so class 2 gets the highest probability.

At test time, prototypes are built from examples of classes not used in training, and classification uses the same formulas. The weights are not updated at test time.

Why the Mean and the Squared Euclidean Distance Work Well

The paper explains why this simple form works well from two viewpoints.

It can be seen as mixture density estimation: For distances known as "Bregman divergences," such as the squared Euclidean distance, the representative point that minimizes the total distance to a set of points is exactly their mean. Thus the mean in Eq. (1) is the optimal representative point of each class's cluster. Moreover, Eq. (2) coincides with the formula for estimating which component a query came from in a mixture distribution where each class is a single component (a spherical Gaussian, for the squared Euclidean distance). In other words, choosing a distance amounts to choosing an assumption about "what shape each class's distribution takes in the embedding space."

It can be seen as a linear classifier: Expanding the squared Euclidean distance gives the following.

−∥fϕ(x)−ck∥2=−fϕ(x)⊤fϕ(x)+2ck⊤fϕ(x)−ck⊤ck-\|f_\phi(x) - c_k\|^2 = -f_\phi(x)^\top f_\phi(x) + 2 c_k^\top f_\phi(x) - c_k^\top c_k

The first term does not depend on the class kk, so it does not affect the softmax result. The rest has the same form as a linear classifier with weights wk=2ckw_k = 2c_k and bias bk=−ck⊤ckb_k = -c_k^\top c_k. The paper argues that even though the decision boundary is linear, the necessary nonlinearity can be learned inside the embedding network fϕf_\phi.

With a single example (1-shot), the prototype is just that example's embedding, so the computation is the same as Matching Networks. The two differ only when there are multiple examples.

In the paper's miniImageNet analysis, switching the distance from cosine to squared Euclidean greatly increased accuracy for both Prototypical Networks and Matching Networks. The paper suggests as a possible reason that the cosine distance is not a Bregman divergence, so the mixture-density view above does not hold.

Experimental Results

The embedding is a CNN that stacks four blocks of "3×3 convolution (64 channels) → batch normalization → ReLU → 2×2 max pooling" (the same architecture as Matching Networks). Optimization uses Adam, with a learning rate of 10−310^{-3} halved every 2000 episodes.

Accuracies on Omniglot (1,200 characters plus rotations used for training) are as follows. Training episodes use 60 classes with 5 queries per class.

Method (Omniglot)5-way 1-shot5-way 5-shot20-way 1-shot20-way 5-shot
Matching Networks (cosine)98.1%98.9%93.8%98.5%
Neural Statistician98.1%99.5%93.2%98.1%
Prototypical Networks (Euclidean)98.8%99.7%96.0%98.9%

The 5-way accuracies on miniImageNet (Ravi and Larochelle's split: 64 training, 16 validation, and 20 test classes) are as follows. They are averages over 600 episodes, and ± is the 95% confidence interval.

Method (miniImageNet)1-shot5-shot
Nearest neighbor on classifier features (cosine)28.86 ± 0.54%49.79 ± 0.79%
Matching Networks (cosine)43.40 ± 0.78%51.09 ± 0.71%
Matching Networks FCE (cosine)43.56 ± 0.84%55.31 ± 0.73%
Meta-Learner LSTM43.44 ± 0.77%60.60 ± 0.71%
Prototypical Networks (Euclidean)49.42 ± 0.78%68.20 ± 0.66%

The Prototypical Networks figures were obtained by training on 30-way episodes for 1-shot and 20-way episodes for 5-shot (15 queries per class), and testing 5-way.

Extension to Zero-Shot Learning

When a description of each class (an attribute vector vkv_k) is given instead of example images, a separate embedding gϑg_\vartheta produces the prototype ck=gϑ(vk)c_k = g_\vartheta(v_k). On zero-shot classification of 50 classes from the CUB-200 bird images (using 312-dimensional attributes), it reached 54.6%, surpassing attribute-based methods of the time. In this experiment, normalizing the prototypes to unit length was effective.

Caveats in Practice

Accuracy depends heavily on how training episodes are built. The paper finds it beneficial to train with more classes (way) than at test time, and to match the number of examples (shot) between training and test. The later Relation Network paper reports that Prototypical Networks trained on 5-way episodes reaches only 46.14% on 1-shot miniImageNet. When comparing with other methods, match the training conditions.

  • Each class is represented by a single point. If a class contains groups that look very different (it is multimodal), the mean can end up resembling none of them. The paper also notes that giving a class multiple prototypes would require a separate partitioning procedure.
  • The choice of distance is an assumption. The squared Euclidean distance assumes that each class is distributed spherically. Switching to cosine lowered accuracy in the paper's experiments.
  • Computation barely grows as examples are added. Since there is one prototype per class, computing distances to the query scales only with the number of classes. There is also no need to keep all the examples in memory.
  • Because the embedding includes batch normalization, model.train() and model.eval() use the statistics differently.

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
Prototypical NetworksSquared Euclidean distance to each class's mean (prototype)No gradient computationSimple and fast; computation barely changes as examples are addedRepresents a class as a single point, so within-class variation is hard to capture
Matching NetworksAttention over cosine similarity to each example, mixing labelsNo gradient computationPreserves per-example differences; FCE can take the whole set into accountComputation grows with the number of examples
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
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, which is expensive

Rough guidelines for choosing are as follows.

  • It is well suited as the baseline to try first for few-shot classification, because the implementation is short and both training and evaluation are fast.
  • When appearance varies widely within a class, also consider Matching Networks, which compares against each example individually, or Relation Network, which also learns how to compare.
  • For problems other than classification, methods that learn an initialization of the weights, such as MAML or Reptile, are candidates.

PyTorch example

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

"""
Minimal implementation of Prototypical Networks.
Eq. (1): c_k = per-class mean of the support-set embeddings
Eq. (2): p(y = k | x) = softmax_k(−‖f(x) − c_k‖²)
"""

def conv_block(in_ch, out_ch):
  # 3×3 convolution (64 channels) → batch normalization → ReLU → 2×2 max pooling (Section 3.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 ProtoNet(nn.Module):
  def __init__(self, in_ch=1, hidden=64):
    super().__init__()
    # Use the same embedding f_φ for support and query
    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) logits (−distance)
    """
    z_s = self.encoder(support_x).flatten(1)          # (N*K, D)
    z_q = self.encoder(query_x).flatten(1)            # (Q, D)
    # Eq. (1): the per-class mean is the prototype c_k
    protos = torch.stack([z_s[support_y == k].mean(dim=0) for k in range(n_way)])  # (N, D)
    # Squared Euclidean distance d(f(x), c_k) (torch.cdist gives the Euclidean distance, so square it)
    dists = torch.cdist(z_q, protos) ** 2              # (Q, N)
    return -dists                                     # value fed into the softmax of Eq. (2)


# Usage (training 20-way 5-shot, 15 queries per class, 84×84 color images)
n_way, k_shot, n_query = 20, 5, 15
model = ProtoNet(in_ch=3)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# Paper: halve the learning rate every 2000 episodes
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=2000, gamma=0.5)

support_x = torch.randn(n_way * k_shot, 3, 84, 84)    # 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, 3, 84, 84)
query_y = torch.arange(n_way).repeat_interleave(n_query)

model.train()
logits = model(support_x, support_y, query_x, n_way)
loss = F.cross_entropy(logits, query_y)               # mean of J(φ) = −log p(y = k | x)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()                                      # call once per episode

# Evaluation: 5-way 5-shot on classes not used in training
model.eval()                                          # batch normalization uses the statistics accumulated during training
with torch.no_grad():
  n_way = 5
  sx = torch.randn(n_way * k_shot, 3, 84, 84)
  sy = torch.arange(n_way).repeat_interleave(k_shot)
  qx = torch.randn(n_way * n_query, 3, 84, 84)
  qy = torch.arange(n_way).repeat_interleave(n_query)
  pred = model(sx, sy, qx, n_way).argmax(dim=1)
  print("accuracy:", (pred == qy).float().mean().item())

FAQ

Q. Are the prototypes parameters that are memorized during training?
A.

No. The prototype ckc_k is recomputed in every episode as the mean of the embeddings of that episode's support set. Only the weights of the embedding network fϕf_\phi are learned. So at test time, prototypes can be built even for never-before-seen classes, as long as examples are available.

Q. Can cosine similarity be used as the distance?
A.

It can, but in the paper's miniImageNet experiments the squared Euclidean distance gave much higher accuracy. The paper suggests as a possible reason that with the squared Euclidean distance the prototype (the mean) is the optimal representative point and matches mixture density estimation, whereas this property does not hold for cosine.

Q. How is it different from Matching Networks?
A.

Matching Networks puts attention on the similarity to each example and mixes their labels, while Prototypical Networks classifies by the distance to a single point obtained by averaging the examples of each class. In 1-shot the example's embedding is itself the prototype, so with the same distance the two perform the same computation.

References

  1. Snell, J., Swersky, K., & Zemel, R. (2017). Prototypical Networks for Few-shot Learning. Advances in Neural Information Processing Systems 30 (NIPS 2017).
  2. 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).
  3. Sung, F., Yang, Y., Zhang, L., Xiang, T., Torr, P. H. S., & Hospedales, T. M. (2018). Learning to Compare: Relation Network for Few-Shot Learning. CVPR 2018.