Foundations to Frontier
Tests
E. Deep Learning › E15 Metric Learning and Few-Shot Learning

Relation networks

Relation networks (Sung and colleagues, CVPR 2018) learn the comparison itself. Instead of a fixed distance such as Euclidean or cosine, a small neural relation module takes a query embedding and a support embedding together and outputs a similarity score between 0 and 1. It is trained end to end with the encoder on few-shot episodes, regressing scores to 1 for matching pairs and 0 otherwise. In principle a learned metric can capture similarities that no fixed distance can. This page covers the relation module, pair scoring and the MSE objective, and when a learned metric helps. In the exercises you implement pair construction and the relation module, then compare it with a fixed squared-distance metric (same encoder, same 1-shot episodes) on unseen classes. The learned module brought no gain: 0.821 against 0.830, and 0.85 vs 0.90 and 0.87 vs 0.90 on two more seeds.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Let a network decide what “similar” means

Prototypical and matching networks compare examples with a fixed ruler: distance or angle. A relation network instead learns the ruler. It feeds a pair of examples, a new one and a labelled one, into a small network that outputs how related they are, from 0 to 1. In principle this can capture notions of similarity that a simple distance would miss. Whether it actually helps is an empirical question. The demo compares support examples with attention; a relation network replaces those similarities with learned scores.

Few-shot lab
Attention over 6 support examples (cosine similarities 0.9, 0.7, 0.2, -0.1, 0.5, -0.4): top weight 0.65. Matching networks predict the attention-weighted average of the support labels.
Why engineers care

Some similarity judgements are not simple distances: two signals may “match” through a learned relationship (a fault signature under different operating conditions). Learned comparison modules can model this, but they need to earn their extra complexity.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A relation network learns…
  2. 2. Its relation module takes…
  3. 3. Scores range…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

By hand

  • Score: r(q, s_k) = g([f(q), f(s_k)]), a relation module g (an MLP or small CNN) on the concatenated embeddings, with a sigmoid output.
  • Pairs: every query is paired with every support (or class prototype): 25 queries × 5 supports = 125 pairs.
  • Objective:
    • MSE regression to 1 for matching pairs and 0 otherwise: scores (0.9, 0.2) against targets (1, 0) give (0.01 + 0.04)/2 = 0.025;
    • only 1/N of the pairs are positive (0.2 for 5-way).
  • Size: an MLP 2d → h → 1 with d = 8 and h = 16 has 2·8·16 + 16 + 16 + 1 = 289 parameters.
  • Prediction: the support class with the highest score.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Pairs for 25 queries and 5 supports:
  2. 2. MSE of scores (0.9, 0.2) vs targets (1, 0):
  3. 3. Share of positive pairs in 5-way:

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.

Relation networks in code

Exercise 1.

  • Pairs were built query-major.
  • A zero-weight relation module gave scores of 0.5.
  • Targets marked the matching support for each query.

Practice.

  • The original model compares convolutional feature maps with a small CNN relation module. For vector embeddings, an MLP works.
  • Cross-entropy over the per-query scores often trains better than MSE.
  • Always compare against a fixed-metric baseline (prototypical network) with the same encoder and episodes.
fq, fs = enc(query), enc(support)                              # (Q, d), (N, d)
pairs = torch.cat([fq.repeat_interleave(N, 0), fs.repeat(Q, 1)], -1)
scores = relation(pairs).sigmoid().view(Q, N)
loss = F.mse_loss(scores, F.one_hot(query_labels, N).float())
🐍 Exercise 1: pairs and relation scores
Build query–support pairs, score them with a relation module and form the regression targets.
📝 Quick check (Level 2)
0/3 answered
  1. 1. The original relation module was…
  2. 2. An alternative to MSE:
  3. 3. A fair comparison uses…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Expressiveness.

  • A fixed metric imposes a geometry: classes must be separable by distance in embedding space.
  • A learned relation module can implement any (approximately) continuous similarity function of the pair, including asymmetric or non-metric ones.
  • In principle this is strictly more flexible, since a relation module can emulate Euclidean distance.

Why flexibility may not pay.

  • The relation module is trained on training classes only. If the encoder can already make classes Euclidean-separable, the extra module mainly adds parameters that must generalise to unseen classes, a new source of overfitting.
  • With little data, the simpler inductive bias of a fixed metric often generalises better. Later analyses found many few-shot gains came from better encoders and training, not from the comparison function.

When it helps. If the natural similarity in the data really is not distance-like (relations between parts, matches across modalities), a learned comparator can capture what a fixed metric cannot.

📝 Quick check (Level 3)
0/3 answered
  1. 1. A learned relation module can emulate…
  2. 2. Its risk on unseen classes:
  3. 3. Learned comparators help most when similarity is…

Level 4: Expert

★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.

Does a learned metric beat a fixed one?

History.

  • F. Sung, Y. Yang, L. Zhang, T. Xiang, P. H. S. Torr and T. M. Hospedales, “Learning to compare: relation network for few-shot learning” (CVPR 2018).
  • Relation networks for reasoning were introduced by Santoro and colleagues (2017).

Exercise 2.

  • World and encoder: the same nuisance-dominated world (40 training, 20 unseen classes) and the same encoder (32 → 32 → 8).
  • Training: 5-way 1-shot episodes for 1500 steps, with either:
    • a fixed metric: softmax over negative squared distances;
    • a learned relation module: a 16 → 16 → 1 MLP on concatenated embeddings, trained with MSE.
  • Test: 300 one-shot episodes on unseen classes. The relation-network gradients were checked against finite differences (maximum error 7 × 10⁻¹¹), so the result is not a bug.
comparison one-shot accuracy (unseen classes)
fixed squared distance 0.830
learned relation module 0.821
  • The learned metric brought no gain: it was slightly worse here and on seeds 1 and 2 (0.852 vs 0.897, 0.874 vs 0.901).
  • The reason: in this world, classes differ in a few latent factors that a good encoder makes distance-separable, so Euclidean distance is already the right comparison. The relation module adds parameters that must generalise to unseen classes.
  • This is a null result for flexibility, not a refutation: with genuinely non-metric similarity, the outcome could differ.
🐍 Exercise 2 (research): does a learned metric beat a fixed one?
Train the same encoder with a fixed squared-distance metric and with a learned relation module, and compare one-shot accuracy on unseen classes.

Relation networks in AI, robotics and aerospace

  • Cross-modal matching: comparing an image with a sensor signature or a description, where no shared distance is obvious.
  • Condition monitoring: learning when two signals indicate the same fault under different operating conditions.
  • Design lesson: a learned comparator must beat a fixed metric with the same encoder; otherwise prefer the simpler model.

References

  1. F. Sung et al. (2018). “Learning to compare: relation network for few-shot learning.” Proc. CVPR.
  2. A. Santoro et al. (2017). “A simple neural network module for relational reasoning.” NeurIPS.
  3. W.-Y. Chen et al. (2019). “A closer look at few-shot classification.” ICLR.