AI Logic

Meta-Learning and Few-Shot Learning

Relation Network

Updated๏ผš

Training and classification flow of Relation Network. The left shows the flow of building an episode, classifying queries, and updating the weights from the mean squared error; the right shows the computation that passes the support set and the query through the embedding module f_ฯ•, sums the feature maps per class, concatenates them with the query's feature map, and outputs a relation score for each class with the relation module g_ฯ†

Background and Overview

Relation Network is a few-shot learning method that uses a neural network to score whether an example and the image in question (the query) belong to the same class. It was presented by Sung et al. at CVPR in 2018. The paper's title is "Learning to Compare," and its distinguishing feature is that it learns from data not only how to extract features but also how to compare them (the distance function).

The earlier Matching Networks uses cosine similarity and Prototypical Networks uses the squared Euclidean distance, both comparisons fixed by hand. Since only the embedding network is learned, accuracy depends on "whether an embedding can be built that is separable under that fixed distance." Relation Network makes the comparison part a deep network as well (the relation module) and trains it together with the embedding.

As an analogy, in handwriting analysis, instead of measuring with a fixed ruler such as "the difference in stroke thickness," it trains, from many cases, the very eye that judges "whether two samples were written by the same person." For new classes it needs no gradient computation for adaptation as MAML does; it classifies simply by passing the examples and the query through the network.

In the paper's experiments, it reached 99.6% on Omniglot 5-way 1-shot and 50.44% on miniImageNet 5-way 1-shot, outperforming or matching methods of the time. If class descriptions (attribute vectors) are used instead of example images, it can be applied directly to zero-shot learning as well.

There is a different module with the same name "Relation Network," proposed in 2017 by Santoro et al. at DeepMind for reasoning about relations between objects (A simple neural network module for relational reasoning). This article covers the few-shot learning method by Sung et al.

Training Procedure (Episodic Training)

The embedding module fฯ†f_\varphi and the relation module gฯ•g_\phi are trained jointly by repeatedly solving, as practice problems (episodes), the task of classifying after seeing KK examples from each of CC classes (CC-way KK-shot). The paper calls the set of examples the "sample set" during training and the "support set" at test time, but they play the same role.

  1. Select CC classes from the training classes, take KK images per class as the example set S={(xi,yi)}i=1mS = \{(x_i, y_i)\}_{i=1}^{m} (m=Kร—Cm = K \times C), and take part of the rest as the queries Q={(xj,yj)}j=1nQ = \{(x_j, y_j)\}_{j=1}^{n}.
  2. Pass the examples and the queries through the same embedding module fฯ†f_\varphi to get feature maps.
  3. When K>1K > 1, sum the examples' feature maps element-wise per class to form a single class feature map.
  4. Concatenate the class feature map and the query feature map along the channel (depth) dimension, and pass the result through the relation module gฯ•g_\phi to output a relation score between 0 and 1. Each query gets CC scores, one per class.
  5. Update ฯ†\varphi and ฯ•\phi with the mean squared error so that scores for same-class pairs approach 1 and scores for different-class pairs approach 0.

The formulas for steps 4 and 5 are as follows (Eqs. (1) and (2) of the paper). C(โ‹…,โ‹…)\mathcal{C}(\cdot, \cdot) denotes concatenation.

ri,j=gฯ•(C(fฯ†(xi),fฯ†(xj))),ฯ†,ฯ•โ†argโกminโกฯ†,ฯ•โˆ‘i=1mโˆ‘j=1n(ri,jโˆ’1(yi=yj))2r_{i,j} = g_\phi\bigl(\mathcal{C}(f_\varphi(x_i), f_\varphi(x_j))\bigr), \qquad \varphi, \phi \leftarrow \arg\min_{\varphi, \phi} \sum_{i=1}^{m} \sum_{j=1}^{n} \bigl(r_{i,j} - \mathbf{1}(y_i = y_j)\bigr)^2

At test time, the class with the highest score is the prediction. The right side of the figure at the top shows concatenation and scoring repeated for each pair of the query and a class, with class 2 getting the highest score.

The loss is the mean squared error rather than cross-entropy because, in the paper's view, the relation score is treated not as "classification" but as "regression of the degree of similarity." The position is that the only ground-truth values that can be generated automatically are 0 and 1, but what is to be predicted is a continuous degree of similarity.

Network Architecture and Why It Works

The paper's architecture for few-shot learning is as follows (Figure 2). A convolution block is "3ร—3 convolution (64 channels) โ†’ batch normalization โ†’ ReLU."

PartArchitectureRole
Embedding module fฯ†f_\varphi4 convolution blocks; only the first 2 have 2ร—2 max poolingTurns the examples and the query into feature maps. The later blocks skip pooling to leave spatial extent for the relation module's convolutions
Relation module gฯ•g_\phi2 convolution blocks (each with 2ร—2 max pooling) โ†’ fully connected 8-dim (ReLU) โ†’ fully connected 1-dim (sigmoid)Outputs a relation score between 0 and 1 from the concatenated feature maps

The Benefit of Learning How to Compare

Fixed distances such as cosine or Euclidean assume that features are compared element by element. The paper points out that with fixed-distance methods, accuracy depends entirely on whether the embedding network can produce "features that are well separated under that distance." The relation module processes the concatenated feature maps with convolutions and fully connected layers, so it can learn nonlinear criteria for "similar" that element-wise comparison cannot express.

On a 2D synthetic example, the paper shows that a deep relation module can represent match/mismatch patterns that cannot be solved by learning a fixed distance (the Mahalanobis distance) or by adding an embedding to it. On real Omniglot data as well, it visualizes that in the embedding space the matching examples are not necessarily clustered near the query, while in the relation module's intermediate representation, matching and mismatching pairs can be separated by a straight line.

The relation module does not structurally guarantee properties that ordinary distance functions satisfy (maximum similarity with itself, the same value when xix_i and xjx_j are swapped). The paper states that in the trained network these properties held approximately in numerical terms.

Experimental Results

Optimization uses Adam, with a learning rate of 10โˆ’310^{-3} halved every 100,000 episodes. All experiments train from scratch without extra data, and do no fine-tuning at test time.

Accuracies on Omniglot (1,200 characters plus rotations for training, 423 characters plus rotations for testing, averaged over 1000 episodes) are as follows.

Method (Omniglot)Fine-tuning5-way 1-shot5-way 5-shot20-way 1-shot20-way 5-shot
Matching NetworksNo98.1%98.9%93.8%98.5%
Prototypical NetworksNo98.8%99.7%96.0%98.9%
MAMLYes98.7 ยฑ 0.4%99.9 ยฑ 0.1%95.8 ยฑ 0.3%98.9 ยฑ 0.2%
Relation NetworkNo99.6 ยฑ 0.2%99.8 ยฑ 0.1%97.6 ยฑ 0.2%99.1 ยฑ 0.1%

The 5-way accuracies on miniImageNet (64 training, 16 validation, and 20 test classes, 84ร—84 images, averaged over 600 episodes) are as follows. ยฑ is the 95% confidence interval.

Method (miniImageNet)Fine-tuning1-shot5-shot
Matching Networks (FCE)No43.56 ยฑ 0.84%55.31 ยฑ 0.73%
Meta-Learner LSTMNo43.44 ยฑ 0.77%60.60 ยฑ 0.71%
MAMLYes48.70 ยฑ 1.84%63.11 ยฑ 0.92%
Prototypical NetworksNo49.42 ยฑ 0.78%68.20 ยฑ 0.66%
Relation NetworkNo50.44 ยฑ 0.82%65.32 ยฑ 0.70%

It was the highest in 1-shot, but fell short of Prototypical Networks in 5-shot. The paper notes, however, that the Prototypical Networks figures were obtained by training on large 30-way or 20-way episodes, and that training on 5-way episodes yields only 46.14% in 1-shot. Relation Network is trained on 5-way episodes.

Zero-Shot Learning

Instead of example images, the class attribute vector vcv_c is passed through a separate embedding (a fully connected MLP), concatenated with the image features, and scored by the relation module. For the image features, a GoogLeNet-family network (Inception-V2) or ResNet-101 pretrained on ImageNet is used. Under the conventional evaluation setting, it reached 84.5% on AwA animals (10 classes) and 62.0% on CUB birds (50 classes).

Caveats in Practice

Every pair of query and class is passed through the relation module, so computation grows in proportion to the number of classes and queries. Where fixed-distance methods only compute distances between embeddings, convolutions and fully connected layers are added. For tasks with many classes, estimate the computation time and memory before using it.

  • The output is not a probability. The relation scores are independent sigmoid outputs per class, so they do not necessarily sum to 1. If they are to be treated as probabilities, separate normalization is needed.
  • The architecture assumes no pooling in the later part of the embedding. Because the relation module contains convolutions, the concatenated feature maps must retain spatial extent. When swapping the embedding for a different network, also change the input size of the relation module accordingly (in the paper, 64 for Omniglot and 64ร—3ร—3=57664 \times 3 \times 3 = 576 dimensions for miniImageNet).
  • Match the comparison conditions. Even in the paper's comparison, episode size and the use of fine-tuning differ from method to method. When comparing on your own task, match the training conditions.
  • Because the embedding and relation modules include 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
Relation NetworkConcatenates the class feature map and the query feature map and scores them from 0 to 1 with a learned functionNo gradient computationThe comparison itself can be learned from dataPasses every pair through the relation module, increasing computation
Prototypical NetworksSquared Euclidean distance to each class's mean (prototype)No gradient computationSimple and fastAssumes an embedding separable under a fixed distance
Matching NetworksAttention over cosine similarity to each example, mixing labelsNo gradient computationPreserves per-example differencesComputation grows with the number of examples
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.

  • For classification that requires comparing fine differences that are hard to tell apart with a fixed distance, methods that also learn how to compare, like Relation Network, are candidates.
  • When you want lighter computation and shorter code, a safe order is to try Prototypical Networks first and consider Relation Network if it falls short.
  • 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 Relation Network (few-shot learning).
Eq. (1): r = g_ฯ†(concat(f_ฯ•(xแตข), f_ฯ•(xโฑผ))); for K-shot, feature maps are summed element-wise per class
Eq. (2): minimize (r โˆ’ 1(yแตข = yโฑผ))ยฒ
"""

def conv_block(in_ch, out_ch, pool):
  # 3ร—3 convolution (64 channels) โ†’ batch normalization โ†’ ReLU (โ†’ 2ร—2 max pooling)
  layers = [nn.Conv2d(in_ch, out_ch, 3, padding=1), nn.BatchNorm2d(out_ch), nn.ReLU()]
  if pool:
    layers.append(nn.MaxPool2d(2))
  return nn.Sequential(*layers)


class RelationNetwork(nn.Module):
  def __init__(self, in_ch=3, hidden=64, image_size=84):
    super().__init__()
    # Embedding module f_ฯ•: only the first 2 blocks pool
    self.embed = nn.Sequential(
      conv_block(in_ch, hidden, True), conv_block(hidden, hidden, True),
      conv_block(hidden, hidden, False), conv_block(hidden, hidden, False),
    )
    # Relation module g_ฯ†: 2 convolution blocks (with pooling) โ†’ FC 8 โ†’ FC 1 (sigmoid)
    self.relation_conv = nn.Sequential(
      conv_block(hidden * 2, hidden, True), conv_block(hidden, hidden, True),
    )
    side = image_size // 4 // 4                       # 84 โ†’ 21 โ†’ 5 (differs slightly from the paper's 3ร—3 in border handling)
    self.fc1 = nn.Linear(hidden * side * side, 8)
    self.fc2 = nn.Linear(8, 1)

  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) relation scores (0 to 1)
    """
    z_s = self.embed(support_x)                        # (N*K, 64, h, w)
    z_q = self.embed(query_x)                          # (Q, 64, h, w)
    # K-shot: sum the feature maps element-wise per class
    z_c = torch.stack([z_s[support_y == k].sum(dim=0) for k in range(n_way)])  # (N, 64, h, w)
    Q, N = z_q.size(0), z_c.size(0)
    # Build every (query, class) pair and concatenate along the channel dimension
    pairs = torch.cat([
      z_c.unsqueeze(0).expand(Q, -1, -1, -1, -1),
      z_q.unsqueeze(1).expand(-1, N, -1, -1, -1),
    ], dim=2).flatten(0, 1)                            # (Q*N, 128, h, w)
    h = self.relation_conv(pairs).flatten(1)
    r = torch.sigmoid(self.fc2(F.relu(self.fc1(h))))   # (Q*N, 1)
    return r.view(Q, N)


# Usage (5-way 1-shot, 15 queries per class, 84ร—84 color images)
n_way, k_shot, n_query = 5, 1, 15
model = RelationNetwork(in_ch=3)
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
# Paper: halve the learning rate every 100,000 episodes
scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=100000, 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()
scores = model(support_x, support_y, query_x, n_way)
target = F.one_hot(query_y, n_way).float()            # 1 for same-class pairs, 0 otherwise
loss = F.mse_loss(scores, target, reduction="sum")    # Eq. (2) (averaging gives the same optimum)
optimizer.zero_grad()
loss.backward()
optimizer.step()
scheduler.step()

model.eval()                                          # batch normalization 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. Can the relation scores be used as probabilities?
A.

Not as they are. The scores are independent sigmoid outputs per class and do not necessarily sum to 1. For classification, simply choosing the class with the highest score is enough. If probabilities are needed, something like normalizing the scores is required.

Q. Why is it trained with the mean squared error rather than cross-entropy?
A.

Because the paper treats the relation score not as "classification of whether two items are the same class" but as "regression of the degree of similarity." Since the only ground truth that can be generated automatically is 0 or 1, the setup looks like classification, but the idea is that what is to be predicted is a continuous degree.

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

Prototypical Networks measures the distance between a class's representative point and the query with a fixed formula, the squared Euclidean distance. Relation Network concatenates the class feature map and the query feature map, passes them through a network, and learns the comparison itself. This increases expressiveness, but computation grows because every pair passes through the network.

References

  1. 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.
  2. Snell, J., Swersky, K., & Zemel, R. (2017). Prototypical Networks for Few-shot Learning. Advances in Neural Information Processing Systems 30 (NIPS 2017).
  3. Santoro, A., Raposo, D., Barrett, D. G. T., et al. (2017). A simple neural network module for relational reasoning. arXiv:1706.01427.