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

Siamese networks

A Siamese network runs two inputs through the same encoder and compares their embeddings. It was introduced for signature verification (Bromley, LeCun and colleagues, 1993) and later used for face verification and one-shot learning (Koch and colleagues, 2015). Trained on pairs labelled "same" or "different" with a contrastive loss, it learns a distance in which same-class examples are close. Because it learns a comparison rather than a fixed set of classes, it can recognise new classes from a single example. This page covers weight sharing, the contrastive loss, pair sampling and verification versus one-shot classification. In the exercises you implement the contrastive loss, then train on 40 classes of synthetic observations dominated by nuisance variation, and test 5-way one-shot classification on 20 unseen classes. Raw distances gave 0.39 accuracy and the Siamese embedding 0.83 (two more seeds agree).

Level 0: Foundation

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

Two copies, one judgement: same or different?

A Siamese network has two identical branches that share all their weights. Each branch turns an input into a short vector, and the network compares the two vectors: close means “same kind,” far means “different.” Trained on many pairs, it learns what matters for telling things apart and what to ignore. Because it learns to compare rather than to name fixed classes, one example of a new class is enough to recognise others. The demo shows the contrastive loss for a pair.

Few-shot lab
Similar pair loss d² = 0.640; dissimilar pair loss max(0, m − d)² = 0.040. Similar pairs are pulled together; dissimilar pairs are pushed apart only until they are m apart.
Why engineers care

Verification problems (is this the same signature, face, part or fault signature as before?) and recognition of new classes from one example are common in inspection, security and robotics.

📝 Quick check (Level 0)
0/3 answered
  1. 1. The two branches of a Siamese network…
  2. 2. Same-class pairs should end up…
  3. 3. Siamese networks can recognise new classes from…

Level 1: Beginner

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

By hand

  • Embedding and distance: f(x), with d(a, b) = ‖f(a) − f(b)‖ (Euclidean), or cosine similarity, or a learned scoring head as in Koch and colleagues.
  • Contrastive loss (Hadsell, Chopra and LeCun, 2006): L = y d² + (1 − y) max(0, m − d)², with y = 1 for same pairs.
    • A same pair at d = 0.5 costs 0.25.
    • A different pair at d = 0.5 with m = 1 costs 0.25; at d = 2 it costs 0.
  • Pairs: n examples give n(n − 1)/2 pairs (320 k from 800). With 40 classes of 20, only 2.4% of random pairs match, so positive pairs are sampled on purpose.
  • Uses:
    • verification: threshold the distance;
    • one-shot classification: nearest support example. Chance is 1/N for N-way, 0.2 for 5-way.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Contrastive loss of a different pair at d = 2, m = 1:
  2. 2. Pairs from 800 examples:
  3. 3. Chance accuracy for 5-way:

Level 2: Intermediate

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

Siamese networks in code

Exercise 1.

  • The contrastive loss gave 0.25, 0.25 and 0 for the three test pairs.
  • A shared encoder doubled distances as expected.
  • Nearest-support labelling picked the right classes.

Practice.

  • Use one encoder module applied to both inputs, or batch both inputs together.
  • Sample balanced pairs and mine hard pairs as training progresses. Normalise embeddings when using cosine distance.
  • For verification, choose the threshold on a validation set for the target false-accept rate.
def forward(xa, xb):
    za, zb = encoder(xa), encoder(xb)                  # the SAME module: shared weights
    return (za - zb).norm(dim=-1)
d = forward(xa, xb)
loss = (y * d**2 + (1 - y) * F.relu(margin - d)**2).mean()
🐍 Exercise 1: contrastive loss
Implement the contrastive loss, Siamese distance and nearest-support labelling.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A verification threshold is chosen on…
  2. 2. Random pairs are mostly…
  3. 3. Weight sharing guarantees…

Level 3: Advanced

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

Theory

Learning a metric.

  • The contrastive loss shapes the embedding space: same pairs are pulled together, different pairs are pushed apart until they are m away.
  • The encoder must keep the features that distinguish classes and suppress nuisance variation (lighting, pose, noise) that would otherwise dominate raw distances.

Why it transfers.

  • The encoder is trained to compare, not to name the training classes.
  • If new classes differ along the same kinds of features as the training classes, the learned invariances still apply, and nearest-neighbour matching in embedding space works with one example per class.

Limits. The margin creates a trade-off: too small and classes overlap, too large and the loss focuses on hard negatives that may be noise. Pairwise losses also see only one relation at a time, which triplet and multi-class losses (next pages) improve on.

📝 Quick check (Level 3)
0/3 answered
  1. 1. The encoder learns to suppress…
  2. 2. Transfer to new classes works if they differ along…
  3. 3. Pairwise losses see…

Level 4: Expert

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

Does a learned metric transfer to unseen classes?

History.

  • J. Bromley, I. Guyon, Y. LeCun, E. Säckinger and R. Shah, “Signature verification using a Siamese time delay neural network” (NeurIPS 1993).
  • S. Chopra, R. Hadsell and Y. LeCun (CVPR 2005) and R. Hadsell, S. Chopra and Y. LeCun (CVPR 2006), the contrastive loss.
  • G. Koch, R. Zemel and R. Salakhutdinov, “Siamese neural networks for one-shot image recognition” (ICML Deep Learning Workshop, 2015).

Exercise 2.

  • World: 32-dimensional observations x = tanh([z_class, n]W). Each class has a 4-D code z_class; every sample adds 6-D nuisance n with standard deviation 1.5, which dominates raw distances.
  • Training: a Siamese encoder (32 → 32 → 8) trained with the contrastive loss on 40 classes (20 samples each), 1500 steps.
  • Test: 300 episodes of 5-way one-shot classification on 20 unseen classes, comparing raw distances, the embedding, and an oracle that recovers z_class exactly.
distance used 5-way one-shot accuracy (unseen classes)
raw observations 0.387
Siamese embedding 0.832
oracle (true class code) 0.999

Chance is 0.2.

  • The learned metric transfers: trained only on the 40 training classes, the embedding more than doubles one-shot accuracy on new classes, from 0.39 to 0.83. It has learned to discount the nuisance directions.
  • Raw distances are dominated by nuisance: two samples of the same class can differ more than samples of different classes.
  • There is room to improve (oracle 1.00): the small encoder only partly undoes the nonlinear mixing.
  • Seeds: seeds 1 and 2 gave 0.37 → 0.82 and 0.42 → 0.89.
🐍 Exercise 2 (research): does a learned metric transfer to unseen classes?
Train a Siamese encoder with the contrastive loss and test one-shot classification on unseen classes.

Siamese networks in AI, robotics and aerospace

  • Verification: matching parts, signatures, faces or fault signatures against a reference.
  • Place recognition: robots and drones match current views to remembered places (loop closure).
  • Change detection: comparing satellite or inspection images taken at different times.
  • Design lesson: when classes change or grow, learn a comparison instead of a classifier, and make sure training covers the nuisance variation you expect.

References

  1. J. Bromley et al. (1993). “Signature verification using a Siamese time delay neural network.” NeurIPS.
  2. R. Hadsell, S. Chopra and Y. LeCun (2006). “Dimensionality reduction by learning an invariant mapping.” Proc. CVPR.
  3. G. Koch, R. Zemel and R. Salakhutdinov (2015). “Siamese neural networks for one-shot image recognition.” ICML Deep Learning Workshop.