Foundations to Frontier
Tests
E. Deep Learning › E2 Loss Functions (one page each)

Triplet loss

The triplet loss trains an embedding with relative constraints: an anchor should be closer to a positive (same identity) than to a negative (different identity) by at least a margin, max(0, d(a, p) − d(a, n) + m). It powered FaceNet and remains a standard for re-identification and retrieval. Because almost all triplets are easy, which negatives are chosen matters: random, semi-hard, or hardest. This page covers the loss, its gradients, the number of triplets, mining strategies, normalised embeddings and batch-hard training. In the exercises you implement the loss and batch-hard mining, then compare negative mining strategies and find that semi-hard negatives gave the best embedding in every seed, while random negatives left over nine-tenths of each batch doing nothing.

Level 0: Foundation

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

Closer than the other one

The contrastive loss demands absolute distances: matching pairs at 0, non-matching beyond m. The triplet loss asks for something more relaxed. Take an anchor, a positive of the same identity and a negative of a different one; the anchor should be closer to the positive than to the negative, by a margin. Classes can have different spreads, as long as every example’s own kind is nearer than any other kind.

Metric learning: pull same-class points together, push others apart
input spacelearned embedding
1-nearest-neighbour test accuracy: in the embedding 0.935 · in the raw input space 0.940
The two rings and the two blobs are classes; rings are not linearly separable in the input. Contrastive loss pulls same-class pairs to distance 0 and pushes different-class pairs beyond the margin m. Triplet loss only asks each anchor to be closer to a positive than to a negative by m. InfoNCE normalises embeddings onto a circle and asks each anchor to pick its positive out of the batch; lower τ sharpens that choice. With 0 training steps you see the random initial embedding.
Why engineers care

Re-identifying the same vehicle or person across cameras, matching a satellite image patch to a map tile, and recognising a previously seen landmark are retrieval problems with open-ended identities. Triplet-trained embeddings are a standard solution, and choosing which triplets to train on decides whether training is fast or wasteful.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A triplet consists of…
  2. 2. The triplet loss is zero when…
  3. 3. Triplet loss was popularised by…

Level 1: Beginner

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

By hand

  • Loss: L = max(0, d(a, p) − d(a, n) + m), often with squared distances, as in FaceNet.
  • Example: a = (0, 0), p = (0.3, 0), n = (0.5, 0), squared distances, m = 0.2: max(0, 0.09 − 0.25 + 0.2) = 0.04.
  • Gradients (squared distances, active triplet): ∂L/∂a = 2(n − p), ∂L/∂p = 2(p − a), ∂L/∂n = 2(a − n). Inactive triplets give zero.
  • Easy, semi-hard and hard negatives:
    • easy: d(a, n) > d(a, p) + m, giving zero loss;
    • semi-hard: d(a, p) < d(a, n) < d(a, p) + m;
    • hard: d(a, n) < d(a, p).
  • Counting: a batch with classes of sizes c_k has Σ c_k(c_k − 1)(N − c_k) valid triplets: 16 200 for 10 classes of 6.
  • Normalised embeddings: on the unit sphere, squared distances lie in [0, 4], so margins such as 0.2 are meaningful.
📝 Quick check (Level 1)
0/3 answered
  1. 1. A negative with d(a, n) < d(a, p) is…
  2. 2. On the unit sphere, squared distances are at most…
  3. 3. Easy negatives contribute…

Level 2: Intermediate

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

Mining triplets

Exercise 1.

  • The loss and its three gradients match finite differences.
  • The valid-triplet count is checked: 16 200 in a batch of 60 with 10 classes of 6.
  • Batch-hard mining (Hermans, Beyer and Leibe, 2017) uses, for each anchor, its farthest positive and closest negative in the batch. It gives zero loss on a well-separated batch and positive loss on a mixed one.

Strategies.

  • Random triplets: simple, but most quickly become easy, so the gradient comes from few triplets.
  • Semi-hard (FaceNet): negatives farther than the positive but within the margin. They are informative without being misleading.
  • Hardest / batch-hard: the most informative per triplet, but sensitive to label noise and outliers. FaceNet reported that the hardest negatives early on could lead to bad local minima or a collapsed model.
  • Batch construction: P identities × K examples each (P×K batches) guarantee positives in every batch.
nn.TripletMarginLoss(margin=0.2)        # plain distances
# batch-hard: D = torch.cdist(E, E); hp = (D * same).max(1); hn = (D + 1e9 * ~diff).min(1)
🐍 Exercise 1: triplet loss and batch-hard mining
Implement the triplet loss with squared or plain distances and its gradients, count valid triplets, and implement the batch-hard loss.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A P×K batch contains…
  2. 2. Batch-hard uses, per anchor, …
  3. 3. Hardest negatives are sensitive to…

Level 3: Advanced

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

Theory

Relative versus absolute constraints. Triplet constraints d(a, p) + m < d(a, n) are invariant to adding a constant to all distances. They do not force positives together if they are already well separated from negatives, so classes may have different internal spreads, which suits real identities.

Why mining matters. The number of triplets grows cubically, but as training proceeds almost all become easy, and the average gradient over random triplets shrinks toward zero. Training slows even though the embedding is far from optimal for the hard cases. Mining concentrates computation on active triplets. Too-hard negatives (outliers, mislabels or genuinely ambiguous examples) push the embedding in harmful directions. Semi-hard selection is a compromise.

Normalisation and margin.

  • Projecting embeddings onto the unit sphere fixes their scale, so the margin has a meaning. Without it, as with the contrastive loss, the embedding can simply grow until the margin is irrelevant.
  • With normalisation, the triplet loss becomes a constraint on cosine similarities.
  • Related losses (N-pair, lifted structure, multi-similarity, InfoNCE) generalise from one negative to many.
📝 Quick check (Level 3)
0/3 answered
  1. 1. As training proceeds, random triplets become mostly…
  2. 2. Normalising embeddings makes the margin…
  3. 3. Losses using many negatives at once include…

Level 4: Expert

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

Which negatives should you train on?

History.

  • K. Weinberger and L. Saul (2009) used triplet constraints in large-margin nearest neighbours (LMNN).
  • F. Schroff, D. Kalenichenko and J. Philbin (2015) trained FaceNet with semi-hard triplets.
  • A. Hermans, L. Beyer and B. Leibe (2017) defended batch-hard triplets for person re-identification.
  • K. Musgrave et al. (2020) found that many claimed improvements over the triplet loss shrank under fair comparison.

Exercise 2. The setting of E2-10: 10 classes, 5 informative and 15 nuisance dimensions. A linear 4-D embedding is projected onto the unit sphere and trained with the squared-distance triplet loss (m = 0.2) on batches of 64, with one triplet per anchor. The negative is chosen at random, semi-hard (falling back to the hardest if none) or hardest.

negatives 1-NN accuracy per seed mean distance between test embeddings triplets still active (last 50 steps)
random 0.894, 0.888, 0.844 1.275 0.060
semi-hard 0.928, 0.922, 0.886 1.298 0.560
hardest 0.906, 0.920, 0.874 1.280 0.579
  • Semi-hard negatives gave the best embedding in every seed. In three further seeds they matched or beat the hardest negatives every time and beat random negatives in two of three.
  • Random negatives wasted most of each batch. By the end only 6% of their triplets violated the margin, so 94% contributed nothing.
  • Hardest negatives did not collapse this linear embedding (its spread matched the others), contrary to FaceNet’s warning for deep networks. They were simply never better than semi-hard ones.
  • The differences were a few points. Mining matters, but with clean labels and a simple model it is not dramatic.
🐍 Exercise 2 (research): which negatives?
Train a normalised linear embedding with the triplet loss using random, semi-hard and hardest negatives; compare nearest-neighbour accuracy, embedding spread and the share of triplets still active.

Triplet loss in AI, robotics and aerospace

  • Re-identification: tracking the same vehicle, aircraft or person across non-overlapping cameras uses triplet-trained embeddings with P×K batches.
  • Map matching: aerial image patches are embedded so that patches of the same location are closer than patches of other locations, enabling GPS-free localisation.
  • Few-shot recognition: new part types or targets can be added by storing a few embeddings, without retraining.

References

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