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

Triplet networks

Triplet networks learn embeddings from triples: an anchor, a positive of the same class and a negative of a different class. The triplet loss asks the anchor to be closer to the positive than to the negative by a margin. FaceNet (Schroff, Kalenichenko and Philbin, 2015) used it to learn 128-dimensional face embeddings and introduced semi-hard negative mining, since most random triplets quickly become too easy to teach anything. This page covers the triplet loss, easy, semi-hard and hard negatives, batch-hard mining and the link to large-margin nearest neighbours. In the exercises you implement the loss and batch-hard mining, then train with random, semi-hard and hard negatives on 40 classes and test one-shot transfer to 20 unseen classes. Semi-hard mining led early: 0.87 against 0.82 after 100 steps, the same order on three seeds. By 600 steps all three reached 0.85–0.88, when only 7% of random triplets still broke the margin.

Level 0: Foundation

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

Closer to friends than to strangers

A triplet network learns from three examples at once: an anchor, another example of the same kind (the positive), and an example of a different kind (the negative). The rule is simple: the anchor must be closer to the positive than to the negative, by at least a safety margin. Once most triplets obey the rule they teach nothing, so training looks for the tricky negatives that still break it. The demo classifies a negative as easy, semi-hard or hard.

Few-shot lab
Triplet loss 0.60; this negative is semi-hard. Easy negatives give no gradient, so training mines semi-hard and hard ones.
Why engineers care

Triplet-trained embeddings power face recognition, person re-identification across cameras, image retrieval and place recognition for robots, all of which need to recognise identities never seen in training.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A triplet contains…
  2. 2. The anchor must be closer to…
  3. 3. Triplets that already obey the margin…

Level 1: Beginner

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

By hand

  • Loss (FaceNet, squared distances): L = max(0, ‖f(a) − f(p)‖² − ‖f(a) − f(n)‖² + m).
    • d²_ap = 1 and d²_an = 4 with m = 1 gives 0; d²_an = 1.5 gives 0.5.
  • Negative types for a given anchor and positive:
    • hard: d_an < d_ap;
    • semi-hard: d_ap < d_an < d_ap + m;
    • easy: d_an ≥ d_ap + m, zero loss and zero gradient.
  • Batches: P classes × K samples. With 8 × 4 there are 96 anchor–positive pairs, each with 28 negatives, so 2688 triplets.
    • Batch-hard mining uses each anchor’s farthest positive and closest negative.
    • Semi-hard mining uses the closest negative that is still farther than the positive.
  • Relation to LMNN: large-margin nearest neighbours (Weinberger and Saul) learns a linear metric with a similar triplet hinge.
📝 Quick check (Level 1)
0/3 answered
  1. 1. Triplet loss for d²_ap = 1, d²_an = 1.5, m = 1:
  2. 2. A negative with d_an < d_ap is…
  3. 3. Triplets in an 8 × 4 batch:

Level 2: Intermediate

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

Triplet networks in code

Exercise 1.

  • The triplet loss was 0 with margin 1 and 1 with margin 4 on the test triple.
  • Negatives were classified correctly.
  • Batch-hard mining found each anchor’s farthest positive and closest negative.

Practice.

  • Use P × K batch sampling with batch-hard or semi-hard mining, as in pytorch-metric-learning (TripletMarginLoss with miners).
  • L2-normalise embeddings and use margins around 0.2 for unit vectors.
  • Pure hard mining from the start can collapse embeddings (everything maps to one point). Start with semi-hard or warm up.
emb = F.normalize(encoder(x), dim=-1)                       # batch of P classes x K samples
D2 = torch.cdist(emb, emb) ** 2
same = y[:, None] == y[None]
hard_pos = (D2 * same).max(1).values
hard_neg = (D2 + 1e9 * same).min(1).values
loss = F.relu(hard_pos - hard_neg + margin).mean()          # batch-hard triplet loss
🐍 Exercise 1: triplets and mining
Implement the triplet loss, classify negatives and perform batch-hard mining.
📝 Quick check (Level 2)
0/3 answered
  1. 1. Pure hard mining from the start can…
  2. 2. Typical margin for unit-length embeddings:
  3. 3. Batches are built as…

Level 3: Advanced

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

Theory

Relative constraints.

  • The triplet loss constrains distances only relative to each other, so the embedding can rescale freely; normalising embeddings removes this freedom.
  • Compared with the contrastive loss, it does not force all same-class pairs to collapse to a point, which preserves intra-class variety.

Why mining matters.

  • As training proceeds, most triplets become easy and contribute zero gradient, so random sampling wastes compute and the effective batch size shrinks.
  • Mining selects triplets that still violate the margin.
  • Hard negatives give the largest gradients, but include label noise and outliers and can cause collapse. Semi-hard negatives are informative but safer (FaceNet).

When mining matters less. With few classes or easy data, random batches already contain enough active triplets early on, and all strategies reach similar final quality. Mining’s advantage grows with the number of classes, because random negatives then become easy far more often.

📝 Quick check (Level 3)
0/3 answered
  1. 1. Triplet losses constrain distances…
  2. 2. Easy triplets contribute…
  3. 3. Mining matters most with…

Level 4: Expert

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

Does negative mining matter?

History.

  • K. Q. Weinberger and L. K. Saul, “Distance metric learning for large margin nearest neighbor classification” (JMLR 2009).
  • F. Schroff, D. Kalenichenko and J. Philbin, “FaceNet: a unified embedding for face recognition and clustering” (CVPR 2015).
  • A. Hermans, L. Beyer and B. Leibe, “In defense of the triplet loss for person re-identification” (2017), with batch-hard mining.

Exercise 2.

  • World and encoder: the same nuisance-dominated world as the Siamese page, with 40 training and 20 unseen classes, and the same encoder (32 → 32 → 8).
  • Training: the triplet loss (margin 1) on batches of 8 classes × 4 samples, with random, semi-hard or hard negatives, 600 steps.
  • Test: 5-way one-shot accuracy on unseen classes every 100 steps, and the share of random triplets that still violate the margin at the end.
negatives after 100 steps 300 600
random 0.821 0.852 0.849
semi-hard 0.869 0.886 0.867
hard 0.855 0.886 0.876

Raw distances 0.393. Random triplets still active at the end: 7% (random training).

  • Mining speeds up early learning: after 100 steps, semi-hard mining led random by about 5 points; seeds 1 and 2 gave 0.88 vs 0.86 and 0.91 vs 0.88, the same order.
  • By the end the strategies are close (0.85–0.88, within the evaluation noise of about ±0.02). On this small problem, random batches keep enough informative triplets.
  • Most random triplets become useless: 93% satisfied the margin by the end. With thousands of classes, this fraction gets even larger, which is why FaceNet-scale training needs mining.
  • Triplets match or beat the Siamese contrastive loss on the same world (0.85–0.88 against 0.83).
🐍 Exercise 2 (research): does negative mining matter?
Train triplet embeddings with random, semi-hard and hard negatives and track one-shot accuracy on unseen classes.

Triplet networks in AI, robotics and aerospace

  • Re-identification: tracking people or vehicles across non-overlapping cameras.
  • Retrieval: finding similar parts, defects or satellite scenes in large archives.
  • Place recognition: matching views for robot and drone localisation.
  • Design lesson: watch the fraction of active triplets. When it falls toward zero, mine harder examples or use losses that consider many negatives at once.

References

  1. F. Schroff, D. Kalenichenko and J. Philbin (2015). “FaceNet: a unified embedding for face recognition and clustering.” Proc. CVPR.
  2. K. Q. Weinberger and L. K. Saul (2009). “Distance metric learning for large margin nearest neighbor classification.” JMLR 10.
  3. A. Hermans, L. Beyer and B. Leibe (2017). “In defense of the triplet loss for person re-identification.” arXiv:1703.07737.