Search

Search papers and lessons

Matching Networks for One Shot Learning

Oriol Vinyals, Charles Blundell, Timothy Lillicrap et al. · 2016

Matching Networks classify a new example by attending over a small labelled set, so they learn new classes from one example each without retraining, and they are trained on episodes that copy that test setting.

On this page

  • Colour = topic mix
  • Calculus
  • Discrete math
  • Linear algebra
  • Probability
  • Neural network basics
  • Learning basics
  • ReadReady to readNot yet

TL;DR

Matching Networks, from Vinyals and colleagues in 2016, classify a new example by comparing it with a small labelled set given at the same time. The network is not retrained for new classes, so a class seen once can be recognised. The authors also train the network on small tasks that look like the test situation, and this training is what makes one-shot accuracy high.

Builds on: Attention Mechanism, Cosine Similarity, Episodic Training, Long Short-Term Memory · Leads to: Prototypical Networks for Few-shot Learning, Few-Shot Learning

Why it mattered

Most deep learning systems learn a fixed list of classes and must be retrained to add one. This paper offered a trainable recipe for the opposite: the labelled examples are inputs to the network, and the network's job is to match a query against them. The episodic framing it popularised is common in later few-shot work. The paper's own numbers show the effect: on Omniglot, 5-way one-shot accuracy reached 98.1 percent, against 80.0 percent for a strong baseline classifier.

The problem

A standard classifier maps an image to one of the classes it was trained on. Adding a class means collecting many examples and running gradient updates. The authors call this a parametric approach: each training example has to be slowly written into the weights. Non-parametric methods such as K-Nearest Neighbors avoid this, because a new example is added just by storing it, but their accuracy depends heavily on the distance measure.

The paper asks for both properties at once: quick absorption of a new labelled example, and strong generalisation from common examples. The task is N-way k-shot classification. A support set holds k labelled examples from each of N classes not used in training, and a batch of unlabelled queries must be assigned to those N classes. Chance is 1/N.

How it works

The model is an attention lookup over the support set. Here is one tiny instance, with two-dimensional vectors so the numbers can be checked by hand.

  1. Start with a support set of two labelled examples. Their embeddings are g(x1)=(1,0)g(x_1) = (1, 0) with label A, and g(x2)=(0,1)g(x_2) = (0, 1) with label B. The labels are one-hot vectors, so A is (1,0)(1, 0) and B is (0,1)(0, 1).
  2. A query arrives. Its embedding is f(x^)=(2,1)f(\hat{x}) = (2, 1). The query points mostly toward the first support example, so it should look like class A.
  3. Compare the query with each support embedding using cosine similarity, which measures the angle between two vectors. The cosine with the first is 2 divided by the square root of 5, which is 0.894. The cosine with the second is 1 divided by the square root of 5, which is 0.447.
  4. Turn the two similarities into weights that add to 1, using a softmax. Exponentiate each: e to the 0.894 is 2.446, and e to the 0.447 is 1.564. Their sum is 4.010. The weights are 2.446 / 4.010 = 0.610 and 1.564 / 4.010 = 0.390.
  5. Output the weighted sum of the labels: 0.610 times (1, 0) plus 0.390 times (0, 1) gives (0.610, 0.390). The first entry is the probability of class A, so the prediction is A, which agrees with the check in step 2.

The paper calls the weighted sum a classifier, cSc_S, built from the support set SS. Changing S changes the classifier with no change to the network's weights.

The figure shows how one support example's weight moves as its cosine similarity to the query changes, with the competitor fixed at cosine 0.

−1−0.500.5100.20.40.60.81cosine similarity to the queryattention weight
  • weight on the example
Attention weight of one support example when its competitor sits at cosine 0. The weight rises from about 0.27 at cosine minus 1 to 0.73 at cosine 1.

The paper adds two training ideas on top of this lookup. The first is the episode: the network is trained on tasks shaped like the test, with a few classes and a few examples per class. The second is full context embeddings, where the support set itself changes how each embedding is computed. Both are formalised in the math section.

flowchart LR
  S[Support set with k examples per class] --> G[Embed each support example with g]
  Q[Query x hat] --> F[Embed the query with f]
  F --> C[Cosine similarity to each support embedding]
  G --> C
  C --> A[Softmax gives attention weights a]
  A --> Y[Weighted sum of one-hot labels]
  Y --> P[Predicted class is the largest entry]

Worked examples

Example
1. Tie in the support set (hand-computable)
  1. Support set: g(x1)=(1,0)g(x_1) = (1, 0) with label A, and g(x2)=(0,1)g(x_2) = (0, 1) with label B.
  2. Query: f(x^)=(1,1)f(\hat{x}) = (1, 1).
  3. Cosine with the first support: 1/2≈0.7071 / \sqrt{2} \approx 0.707. Cosine with the second: 1/2≈0.7071 / \sqrt{2} \approx 0.707. They are equal.
  4. Equal scores give equal weights: a1=a2=0.5a_1 = a_2 = 0.5.
  5. Output: y^=0.5(1,0)+0.5(0,1)=(0.5,0.5)\hat{y} = 0.5(1, 0) + 0.5(0, 1) = (0.5, 0.5).
  6. The two probabilities tie, so the output does not pick a label. Equal similarity means no evidence either way.
Example
2. Three classes, one example each (standard case)
  1. Support set: g(x1)=(1,0)g(x_1) = (1, 0) with label A, g(x2)=(0,1)g(x_2) = (0, 1) with label B, and g(x3)=(1,1)g(x_3) = (1, 1) with label C. This is 3-way 1-shot.
  2. Query: f(x^)=(2,1)f(\hat{x}) = (2, 1).
  3. Cosines: with g(x1)g(x_1) it is 2/5≈0.8942/\sqrt{5} \approx 0.894. With g(x2)g(x_2) it is 1/5≈0.4471/\sqrt{5} \approx 0.447. With g(x3)g(x_3) it is 3/10≈0.9493/\sqrt{10} \approx 0.949.
  4. Exponentials: e0.894≈2.446e^{0.894} \approx 2.446, e0.447≈1.564e^{0.447} \approx 1.564, e0.949≈2.582e^{0.949} \approx 2.582. Their sum is 6.5926.592.
  5. Weights: 2.446/6.592≈0.3712.446 / 6.592 \approx 0.371, 1.564/6.592≈0.2371.564 / 6.592 \approx 0.237, 2.582/6.592≈0.3922.582 / 6.592 \approx 0.392. They add to 1.
  6. Output: y^=(0.371,0.237,0.392)\hat{y} = (0.371, 0.237, 0.392). The largest entry is for C.
  7. Interpretation: the query is closest to g(x3)g(x_3), but the other two keep some weight. A rule that used only the single nearest neighbour would ignore them.

The math

Definition

A one-shot classifier of this kind takes a support set S={(xi,yi)}i=1kS = \{(x_i, y_i)\}_{i=1}^{k} of labelled examples and a query x^\hat{x}, and returns a probability over labels. Each yiy_i is a one-hot vector, so the output y^\hat{y} is a probability vector over the labels in SS.

Step 1 in symbols: the attention weights

Two embedding networks ff and gg map inputs to vectors. The cosine similarity between vectors uu and vv is c(u,v)=u⋅v∥u∥ ∥v∥c(u,v) = \dfrac{u \cdot v}{\|u\|\,\|v\|}. The attention weight for support example ii is

a(x^,xi)=ec(f(x^), g(xi))∑j=1kec(f(x^), g(xj)).a(\hat{x}, x_i) = \frac{e^{c(f(\hat{x}),\, g(x_i))}}{\sum_{j=1}^{k} e^{c(f(\hat{x}),\, g(x_j))}}.

The weights are positive and add to 1 over ii. Cosine values lie between minus 1 and 1, so the largest weight can be at most e2≈7.39e^{2} \approx 7.39 times the smallest.

Step 2 in symbols: the prediction

The output is

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

Because each yiy_i is one-hot, the entry of y^\hat{y} for a label yy is the sum of the attention weights on the support examples carrying yy. The predicted class is the label with the largest entry, written arg⁡max⁡yP(y∣x^,S)\arg\max_y P(y \mid \hat{x}, S) in the paper.

Step 3 in symbols: episodes and the training objective

A task TT is a distribution over label sets LL. An episode draws a label set L∼TL \sim T, then draws a support set SS and a batch BB from LL. Training maximises the log probability of the batch labels, averaged over episodes:

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

Here θ\theta holds the weights of ff and gg. The paper calls this a form of meta-learning: each episode teaches the network how to learn from a support set.

Step 4 in symbols: full context embeddings

Plain ff and gg embed each example alone. The paper lets the support set change the embeddings. The query embedding becomes f(x^,S)=attLSTM(f′(x^),g(S),K)f(\hat{x}, S) = \mathrm{attLSTM}(f'(\hat{x}), g(S), K), where KK is the number of reading steps. The appendix writes the reading steps as

h^k,ck=LSTM(f′(x^),[hk−1,rk−1],ck−1),hk=h^k+f′(x^),\hat{h}_k, c_k = \mathrm{LSTM}\big(f'(\hat{x}), [h_{k-1}, r_{k-1}], c_{k-1}\big), \qquad h_k = \hat{h}_k + f'(\hat{x}), rk−1=∑i=1∣S∣a(hk−1,g(xi)) g(xi),a(hk−1,g(xi))=softmax(hk−1Tg(xi)).r_{k-1} = \sum_{i=1}^{|S|} a(h_{k-1}, g(x_i))\, g(x_i), \qquad a(h_{k-1}, g(x_i)) = \mathrm{softmax}\big(h_{k-1}^{T} g(x_i)\big).

Here rk−1r_{k-1} is a read from the support set, fed back into the recurrent cell. The support embeddings are also made context-aware: g(xi,S)g(x_i, S) is a bidirectional LSTM run over the support set, plus a skip connection g′(xi)g'(x_i).

Results

Omniglot (1,623 characters from 50 alphabets, 20 drawings each). Table 1 of the paper reports Matching Networks with cosine matching and no fine-tuning at 98.1 percent for 5-way 1-shot, 98.9 percent for 5-way 5-shot, 93.8 percent for 20-way 1-shot and 98.5 percent for 20-way 5-shot. The Baseline Classifier, which matches features from a classifier trained on other characters, scores 80.0, 95.0, 69.5 and 89.1 percent on the same four settings. The Convolutional Siamese Net scores 96.7 and 88.0 percent in the 5-way 1-shot and 20-way 1-shot settings.

miniImageNet (60,000 images, 100 classes, 84 by 84 pixels, 80 training and 20 test classes). Table 2 reports 5-way accuracy. Matching Networks with full context embeddings and fine-tuning reach 46.6 percent in 1-shot and 60.0 percent in 5-shot, against 38.4 and 51.2 percent for the softmax Baseline Classifier with fine-tuning. Full context embeddings help on this harder set, adding 3.0 points in 1-shot without fine-tuning.

Full ImageNet, rand split. Table 3 gives 5-way 1-shot accuracy of 93.2 percent for Matching Networks against 87.6 percent for the Inception Classifier. The abstract's figures for ImageNet (87.6 to 93.2 percent) and Omniglot (88.0 to 93.8 percent) are the 1-shot results compared with the competing approaches.

Full ImageNet, dogs split. Here the model is 1 point below the Inception baseline on the held-out dog classes (58.8 against 59.8 percent). The authors attribute this to training episodes that sample classes uniformly from the whole class tree, whereas the test set is fine-grained.

Language. On the Penn Treebank one-shot sentence task, chance is 20 percent. Matching Networks reach 32.4, 36.1 and 38.2 percent with support sets of 1, 2 and 3 examples per class. An LSTM language model trained on all words reaches 72.8 percent, but it has seen far more data, so it is an upper bound and not a fair rival.

Limits. The cost of each gradient update grows with the support set, which the conclusion names as the main drawback. Performance also drops when the label distribution is fine-grained, as on the dogs split. And the model needs a per-query computation over the support set at test time, so it is not free to run at scale. A standard classifier is simpler when the classes are fixed, large and known in advance.

Reading guide

Read the paper in this order, with the lessons it needs.

Read next: Prototypical Networks for Few-shot Learning, which simplifies the same episodic setting by comparing queries with class averages.

Check yourself

QuestionGiven support embeddings g(x1)=(1,0)g(x_1) = (1, 0) and g(x2)=(0,1)g(x_2) = (0, 1) and a query f(x^)=(3,1)f(\hat{x}) = (3, 1), which support example gets the larger attention weight, and why?Show answer
The first. The cosine with (1, 0) is 3 divided by the square root of 10, about 0.949. The cosine with (0, 1) is 1 divided by the square root of 10, about 0.316. A larger cosine gives a larger exponential, so the first example gets more weight.
QuestionA support set has three examples, each with cosine similarity 0 to the query. What is the attention weight on each?Show answer
Each weight is e to the 0 divided by the sum of three e to the 0 terms, which is 1 divided by 3, about 0.333. With equal scores the softmax spreads the weight evenly, so the output is the average of the three one-hot labels.
QuestionWhy does the paper train on episodes with a few classes and a few examples per class, instead of ordinary minibatches of the full training set?Show answer
Test time gives the model a small support set of new classes. Training on episodes of the same shape matches the training conditions to the test conditions. The paper's argument is that the training procedure must be chosen to match inference, so the model learns to use a support set rather than to memorise fixed classes.
QuestionIn the 5-way 1-shot Omniglot results, the Matching Networks model scores 98.1 percent and the Baseline Classifier scores 80.0 percent. What is the error ratio?Show answer
Error rates are one minus accuracy: 1.9 percent and 20.0 percent. Their ratio is 1.9 divided by 20.0, which is 0.095. So the Matching Networks model makes about one tenth of the baseline's errors on this task.
QuestionGive one reason a standard classifier might be preferred to a Matching Network in a real system.Show answer
When the set of classes is fixed and large, and all labelled data is available in advance, a standard classifier trained with gradient descent is simpler to build and cheaper to run at test time. A Matching Network pays for its flexibility with a per-query cost that grows with the support set.

Sources

Read the full paper

Oriol Vinyals, Charles Blundell, Timothy Lillicrap et al., 2016. arXiv:1606.04080