Triplet loss
三元组损失
Derive normalized triplet gradients, mine semi-hard negatives, and test a geometrically impossible margin.
triplet-lossStart with the problem
A query should be closer to a relevant item than to an irrelevant one. Triplet loss turns that ranking preference into a trainable constraint: choose an anchor a, a positive p and a negative n, then require a margin between the two distances. It does not require every member of a class to occupy exactly one point.
FaceNet used this objective on normalized face embeddings; its paper describes both the margin and selection of useful training triplets. Earlier LMNN expresses related relative-distance constraints for a learned linear metric. The objective is useful beyond the original application whenever the labels genuinely define the desired similarity. FaceNet: A Unified Embedding for Face Recognition and Clustering; Distance Metric Learning for Large Margin Nearest Neighbor Classification
The interesting part is often not writing the hinge, but selecting the triplets and differentiating through normalization. We will optimize three two-dimensional vectors, check all six derivatives and exhibit a margin that no unit-vector geometry can satisfy.
Definitions and derivation
Normalize nonzero raw embeddings u to z. The squared Euclidean distance on the unit sphere lies between zero and four. With nonnegative margin m:
When the hinge argument is positive, the derivatives with respect to normalized vectors are straightforward. If it is negative, all are zero. At exactly zero, our code chooses the zero subgradient:
These are not yet gradients of raw embeddings. Differentiating u divided by its norm projects the gradient onto the tangent plane and divides by the raw norm:
A semi-hard negative is farther than the positive but still inside the margin. The program selects the closest eligible negative, with strict bounds, and returns None when there is none. This is an explicit selection rule, not a requirement to substitute the hardest negative on failure. FaceNet motivates semi-hard selection because the hardest negatives can destabilize early training, and reports margin 0.2 for its experiments. Our small optimization also uses 0.2, without reproducing its dataset or network. FaceNet: A Unified Embedding for Face Recognition and Clustering
Run the calculation
Use CPython 3.12.4 and NumPy 1.26.4. Thirty steps of size 0.05 reduce the triplet loss from 0.587767469 to zero. Final positive and negative squared distances are approximately 0.038859346 and 0.243484331: their difference clears the 0.2 margin. The optimized objects are the six raw embedding coordinates, not an encoder trained to generalize to new inputs. The example also checks a semi-hard candidate list and the infeasible margin-five case.
import numpy as np
def objective(raw,margin=.2):
raw=np.asarray(raw,dtype=float);norm=np.linalg.norm(raw,axis=1,keepdims=True)
if raw.shape!=(3,2) or not np.isfinite(raw).all() or np.any(norm<1e-10) or not np.isfinite(margin) or margin<0:raise ValueError('Use three nonzero 2D vectors and a nonnegative margin.')
z=raw/norm;a,p,n=z;positive=float(np.sum((a-p)**2));negative=float(np.sum((a-n)**2));hinge=positive-negative+margin
if hinge>0:gz=np.array([2*(n-p),2*(p-a),2*(a-n)]);gradient=(gz-z*np.sum(gz*z,axis=1,keepdims=True))/norm
else:gradient=np.zeros_like(raw)
return max(0.,hinge),gradient,positive,negative
def semi_hard(positive,negatives,margin):
values=np.asarray(negatives,dtype=float);eligible=np.flatnonzero((values>positive)&(values<positive+margin));return None if not len(eligible) else int(eligible[np.argmin(values[eligible])])
def initial():return np.array([[1.,0],[.8,.6],[.9,-.1]])
if __name__=='__main__':
raw=initial();start=objective(raw)[0]
for _ in range(30):raw-=.05*objective(raw)[1]
loss,g,dp,dn=objective(raw);print('triplet loss before/after',round(start,9),round(loss,9),'positive / negative squared distance',round(dp,9),round(dn,9))
print('semi-hard choice',semi_hard(.4,[.1,.5,.8,1.4],.5),'no eligible choice',semi_hard(.4,[.1,1.4],.5))
best=np.array([[1.,0],[1,0],[-1,0]]);print('margin-five best-geometry loss',objective(best,5)[0],'unit-vector distance maximum',4)
triplet loss before/after 0.587767469 0.0 positive / negative squared distance 0.038859346 0.243484331
semi-hard choice 1 no eligible choice None
margin-five best-geometry loss 1.0 unit-vector distance maximum 4
When the method fails
On unit vectors, a negative can be at squared distance at most four while the positive distance cannot be below zero. A margin above four is impossible even for one triplet. For m=5, put the positive on the anchor and the negative at its antipode; the loss is still one. A nonzero residual here is not an optimizer bug.
Conversely, zero loss on one triplet gives only one ranking constraint. It neither calibrates a global verification threshold nor proves every class is separated. Labels may conflict, and batches without repeated classes cannot provide positives. Mining false negatives can actively punish useful similarities.
Enumerating all ordered triplets from N examples can grow cubically. A batch distance matrix costs for d-dimensional vectors, after which selection strategies determine which constraints receive gradients. Compare metric learning: a fixed linear PSD objective has different optimization structure from a neural encoder with a triplet loss. Distance Metric Learning for Large Margin Nearest Neighbor Classification
Exercises with answers
- Which negatives are semi-hard when positive distance is 0.4 and margin is 0.5: 0.1, 0.5, 0.8, 1.4?
Answer 1: 0.5 and 0.8; the program chooses 0.5.
- Does multiplying a raw vector by a positive scalar change its normalized location?
Answer 2: No, though the raw-coordinate gradient magnitude changes because the normalization Jacobian divides by its norm.
- What is the smallest possible loss for a single unit-vector triplet with margin five?
Answer 3: One, achieved by coincident anchor/positive and an antipodal negative.
- Why reject a zero raw vector?
Answer 4: Its normalized direction and the stated Jacobian are undefined.
Sources and next steps
Read FaceNet Sections 3.1–3.2 for the objective and mining assumptions, then LMNN’s fixed-neighbor formulation for the earlier relative-distance perspective. To turn this into an application, train a shared encoder, split identities or entities appropriately across evaluation, and report retrieval and threshold-based verification separately. A lower training triplet loss alone is insufficient. FaceNet: A Unified Embedding for Face Recognition and Clustering; Distance Metric Learning for Large Margin Nearest Neighbor Classification
Make a prediction, then check
What is the largest squared distance between two unit vectors?
Learning objectives
- Differentiate a triplet hinge through unit normalization.
- Check mining eligibility and the feasible range of margins.
Prerequisites & connections
Explore related knowledge →References
- FaceNet: A Unified Embedding for Face Recognition and Clustering
Florian Schroff; Dmitry Kalenichenko; James Philbin · 2015 - Distance Metric Learning for Large Margin Nearest Neighbor Classification
Kilian Q. Weinberger; Lawrence K. Saul · 2009
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.
- Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
- Four focused CPython 3.12.4 tests passed per chapter: finite-difference gradients, sample covariance, teacher/center update order, hidden-input isolation, independent least squares, PSD projection, margin feasibility, tied-branch derivatives and transported factor actions as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; teaching calculations, not image benchmarks.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
- Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
Source locations checked:
- FaceNet: A Unified Embedding for Face Recognition and Clustering · Physical pages 3–4, Sections 3.1–3.3 and Eqs. 1–3: unit embeddings, hinge margin, online mining, semi-hard negatives and experimental margin 0.2.
- Distance Metric Learning for Large Margin Nearest Neighbor Classification · Physical pages 10–12, fixed targets and relative pull/push margin constraints; Eq. 12.
Related topics