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.
★☆☆☆☆ 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.
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. A triplet consists of…
2. The triplet loss is zero when…
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.
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. A negative with d(a, n) < d(a, p) is…
2. On the unit sphere, squared distances are at most…
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.
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. A P×K batch contains…
2. Batch-hard uses, per anchor, …
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. As training proceeds, random triplets become mostly…
2. Normalising embeddings makes the margin…
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
K. Q. Weinberger, L. K. Saul (2009). “Distance metric learning for large margin nearest neighbor classification.” Journal of Machine Learning Research 10.
F. Schroff, D. Kalenichenko, J. Philbin (2015). “FaceNet: a unified embedding for face recognition and clustering.” Proc. CVPR.
A. Hermans, L. Beyer, B. Leibe (2017). “In defense of the triplet loss for person re-identification.” arXiv:1703.07737.
K. Musgrave, S. Belongie, S.-N. Lim (2020). “A metric learning reality check.” Proc. ECCV.
Semi-hard negatives gave the best embedding in exercise 2; hardest negatives were never better.
Practice
Show:
Level 0
Problem 1Level 0
Triplet loss (squared distances, m = 0.2) for a = (0, 0), p = (0.3, 0), n = (0.5, 0)?
0.09 − 0.25 + 0.2 = 0.04.
Problem 2Level 0
Triplet loss (m = 1) with d(a, p) = 1 and d(a, n) = 3?
max(0, 1 − 3 + 1) = 0.
Problem 3Level 0
Triplet loss (m = 1) with d(a, p) = 1 and d(a, n) = 1.5?
0.5.
Level 1
Problem 4Level 1
Valid triplets for labels (0, 0, 0, 1)?
3 × 2 × 1 = 6.
Problem 5Level 1
Valid triplets in a batch of 10 classes × 6 examples?
10 × 6 × 5 × 54 = 16 200.
Problem 6Level 1
Largest squared distance between unit vectors?
4.
Problem 7Level 1
∂L/∂a, first component, for a = (0, 0), p = (0.3, 0), n = (0.5, 0) (squared distances, active)?
2(0.5 − 0.3) = 0.4.
Level 2
Problem 8Level 2
How many of the negatives at distances (0.5, 1.1, 1.5) are semi-hard, given d(a, p) = 1 and m = 0.2?
Only 1.1 lies in (1, 1.2): 1.
Problem 9Level 2
Share of random triplets still active late in exercise 2?
0.060.
Problem 10Level 2
Semi-hard 1-NN accuracy, first seed?
0.928.
Problem 11Level 2
Hardest-negative 1-NN accuracy, first seed?
0.906.
Problem 12Level 2
Random-negative 1-NN accuracy, third seed?
0.844.
Problem 13Level 2
Share of random triplets doing nothing late in training (1 − active)?
1 − 0.06 = 0.94.
Level 3
Problem 14Level 3
Derive the gradients of the squared-distance triplet loss.
For an active triplet, L = ‖a − p‖² − ‖a − n‖² + m. Then ∂L/∂a = 2(a − p) − 2(a − n) = 2(n − p); ∂L/∂p = −2(a − p) = 2(p − a); ∂L/∂n = 2(a − n). The anchor moves toward the positive and away from the negative; the positive moves toward the anchor; the negative moves away. ∎
Problem 15Level 3
Explain why random triplets stop contributing during training.
Once the embedding roughly separates classes, a random negative is usually from a class far from the anchor, so d(a, n) exceeds d(a, p) + m and the hinge is zero, with zero gradient. In exercise 2, 94% of random triplets were in this state late in training. The few remaining active triplets are the informative ones, but they are averaged with many zeros, so the effective learning rate shrinks. Mining selects them directly. ∎
Problem 16Level 3
Discuss why hardest negatives can harm deep networks even though they did not here.
The hardest negative of an anchor is often an outlier, a mislabelled example or a genuinely ambiguous one. Its gradient pushes the embedding to separate points that should not be separated, and in a deep network, which can bend the embedding arbitrarily, this can produce collapsed or degenerate solutions early in training when all embeddings are close. A linear embedding has limited freedom, and exercise 2’s labels were clean, so these failure modes did not appear. Semi-hard negatives avoid the extremes and were at least as good in every seed. ∎
Problem 17Level 3
Design training for vehicle re-identification across traffic cameras.
Use P×K batches (for example 16 vehicles × 4 images from different cameras), so every anchor has cross-camera positives. Normalise embeddings and use a triplet loss with batch-hard or semi-hard mining, starting with semi-hard and moving to batch-hard once training is stable. Use hard negatives only from verified identities, since label noise turns mining against you. Evaluate with rank-1 accuracy and mAP on cameras not used in training, and check failure cases by colour and viewpoint. ∎
Level 4
Problem 18Level 4
Semi-hard 1-NN accuracy, second seed?
0.922.
Problem 19Level 4
Active-triplet share for hardest negatives?
0.579.
Problem 20Level 4
Mean distance between test embeddings for semi-hard?
1.298.
Coding practice
🐍 Code 1 (Level 0): triplet loss from distances
mean max(0, d_ap − d_an + m).
🐍 Code 2 (Level 1): counting triplets
Σ c(c − 1)(N − c).
🐍 Code 3 (Level 1): semi-hard test
d_ap < d_an < d_ap + m.
🐍 Code 4 (Level 0): normalise
Rows to unit length.
🐍 Code 5 (Level 0): sphere distances
Largest squared distance between unit vectors.
Topic test
A timed test drawn at random from this topic's question bank. Each attempt gets new questions. For a longer test across the whole chapter, see the chapter test, or mix topics in the question bag.
Triplet loss: topic test
10 questions, drawn at random from a bank of 21. Every attempt is different.
⏱ Time limit: 15 minutes. The test submits itself when time runs out.
Levels covered: 0, 1, 2, 3, 4. No hints or solutions until you submit.