Search

Search papers and lessons

Triplet Loss

Level 3 · 9 min read

Triplet loss trains an embedding so that an anchor sits closer to a matching example than to a non-matching one by at least a fixed margin, which turns similarity into distance.

On this page

  • Colour = topic mix
  • Discrete math
  • Calculus
  • Linear algebra
  • Probability
  • Losses & regularization
  • Representation learning
  • ReadReady to readNot yet

TL;DR

Triplet loss is a training rule for embeddings, which are lists of numbers that stand for an item. You pick three items: an anchor, a positive that is the same kind of thing as the anchor, and a negative that is not. The loss is zero only when the anchor is closer to the positive than to the negative by a fixed margin. Training pushes matching items together and non-matching items apart, so later you can decide "same or different" by comparing distances.

Builds on: Loss Function, Euclidean Distance · Leads to: siamese networks trained at scale, Contrastive Learning

Where it's used

Face recognition. The FaceNet system, described in a 2015 paper, maps each face photo to a short vector and trains that mapping with triplets of face crops. Two photos are the same person when their vectors are close. Because the system compares distances, it does not need a fixed list of people to recognise, so new faces can be added by storing their vectors.

Image and product search. A shop can embed every product photo once, then embed a customer's photo and return the nearest stored vectors, using a nearest-neighbour search when the catalogue is large. Triplet loss is one way to make "nearest" mean "looks like the same kind of item".

Re-identifying people across cameras. A camera network needs to know that a person walking out of one camera's view is the same person entering another's. Embeddings trained with triplets let the system match people across cameras by distance, without knowing their identities in advance.

How it works

Work through one training step with 2-D vectors, so you can see the numbers. Let the anchor be a = (0, 0). The positive p is a different photo of the same thing, placed at p = (0.3, 0.4). The negative n is a different thing, placed at n = (0.6, 0). Use distances as the straight-line length between points, and set the margin α = 0.2.

  1. Measure the distances. The anchor to positive distance is d(a, p) = √(0.3² + 0.4²) = 0.5. The anchor to negative distance is d(a, n) = 0.6. Check: the negative is currently closer than the positive should be.
  2. Compare with the margin. The loss for this triplet is max(0, d(a, p) − d(a, n) + α) = max(0, 0.5 − 0.6 + 0.2) = max(0, 0.1) = 0.1. Check: the gap is 0.1 greater than zero, so the triplet is violated and the loss is positive.
  3. Update the embedding. Training moves the vectors so the loss shrinks: the positive moves toward the anchor and the negative moves away from it. Suppose the negative moves to (0.8, 0). Check: now d(a, n) = 0.8, and 0.5 − 0.8 + 0.2 = −0.1.
  4. Read the new loss. The loss is max(0, −0.1) = 0. The triplet now satisfies the margin, so it contributes nothing to the gradient.

The idea in one line: the anchor should be at least α closer to the positive than to the negative, and the loss measures how much that fails.

00.20.40.60.811.200.20.40.60.8distance to negative d(a, n)triplet loss
  • loss with d(a, p) = 0.5, margin 0.2
With the positive fixed at distance 0.5, the loss is zero once the negative is at least 0.7 away, and it grows as the negative gets closer. The two points are steps 2 and 4.

The math

Definition: Triplet loss

Let f be the embedding function that maps an input to a vector. For an anchor a, a positive p (same class) and a negative n (different class), with a margin α greater than zero, the triplet loss is

L(a,p,n)=max⁡(0,  d(f(a),f(p))−d(f(a),f(n))+α)L(a, p, n) = \max\bigl(0,\; d(f(a), f(p)) - d(f(a), f(n)) + \alpha\bigr)

where d(x, y) is the Euclidean distance ∥x−y∥2\lVert x - y \rVert_2. The training objective is the sum or average of L over a mini-batch of triplets, which is the batch that one gradient step uses.

Step 1 in symbols

The distances are dap=∥f(a)−f(p)∥2d_{ap} = \lVert f(a) - f(p) \rVert_2 and dan=∥f(a)−f(n)∥2d_{an} = \lVert f(a) - f(n) \rVert_2. In the walkthrough, dap=0.5d_{ap} = 0.5 and dan=0.6d_{an} = 0.6.

Step 2 in symbols

The margin test is dap+α≤dand_{ap} + \alpha \le d_{an}. The loss is the amount by which this fails: L=max⁡(0,dap−dan+α)L = \max(0, d_{ap} - d_{an} + \alpha). With dap=0.5d_{ap} = 0.5, dan=0.6d_{an} = 0.6 and α=0.2\alpha = 0.2, the value is 0.10.1.

Step 3 in symbols

Moving the negative to dan=0.8d_{an} = 0.8 gives 0.5−0.8+0.2=−0.10.5 - 0.8 + 0.2 = -0.1, so L=0L = 0. Gradient descent changes the network weights so that dand_{an} grows and dapd_{ap} shrinks, which is why the loss falls. The gradient is nonzero only for violated triplets: when L>0L > 0, ∂L/∂dap=1\partial L / \partial d_{ap} = 1 and ∂L/∂dan=−1\partial L / \partial d_{an} = -1.

Step 4 in symbols

Once dan≥dap+αd_{an} \ge d_{ap} + \alpha, the max returns zero and the triplet is satisfied. The plot shows this as the flat part at zero.

Worked examples

Example
1. Tiny: one triplet, hand-computed
  1. Anchor a = (0, 0), positive p = (0.6, 0), negative n = (1, 0), margin α = 0.2.
  2. Distances: d(a, p) = 0.6 and d(a, n) = 1.
  3. Loss: max(0, 0.6 − 1 + 0.2) = max(0, −0.2) = 0.
  4. Interpretation: the positive is closer than the negative by more than the margin, so the triplet costs nothing.
Example
2. Standard: a violated triplet
  1. Anchor a = (0, 0), positive p = (0.3, 0.4), negative n = (0.6, 0), margin α = 0.2.
  2. Distances: d(a, p) = √(0.09 + 0.16) = 0.5 and d(a, n) = 0.6.
  3. Loss: max(0, 0.5 − 0.6 + 0.2) = max(0, 0.1) = 0.1.
  4. Gradient direction: d(a, p) should shrink and d(a, n) should grow until the gap reaches 0.2.
  5. Interpretation: the negative is too close, and the loss pushes it away until the margin holds.
Example
3. Realistic: a face-matching batch

A face system embeds crops into 128-dimensional unit-length vectors. Take one triplet with d(a, p) = 0.9 and d(a, n) = 1.3, and margin α = 0.2.

  1. Compute the loss: max(0, 0.9 − 1.3 + 0.2) = max(0, −0.2) = 0.
  2. Interpretation: the matching crop is 0.4 closer than the non-matching crop, which clears the 0.2 margin, so this triplet is easy and teaches nothing.
  3. Now take a second triplet with d(a, p) = 0.9 and d(a, n) = 1.0. The loss is max(0, 0.9 − 1.0 + 0.2) = 0.1.
  4. Interpretation: this triplet is hard and drives learning, so training should keep it and skip the easy one.

Try it: the same network sees a triplet with d(a, p) = 0.9 and d(a, n) = 1.05, margin α = 0.2. Is the triplet violated, and what is the loss?

Answer: 0.9 − 1.05 + 0.2 = 0.05, so the loss is max(0, 0.05) = 0.05. The triplet is violated, but only slightly.

Common mistakes and tradeoffs

It is tempting to think a loss of zero means the model is finished. In fact the loss is zero only for the triplets in the batch that happened to satisfy the margin. Other triplets can still violate it, so the loss must be measured over many triplets.

It is tempting to think any random negative is useful. In fact most random negatives are already far away, so their loss is zero and they give no gradient. Training works best when it picks hard or semi-hard negatives, those that are close to the anchor and still violate the margin. FaceNet did this by choosing triplets online from each batch.

It is tempting to think the margin can be any number. In fact the margin sets the scale of the embedding. If the margin is tiny, the embedding has little room between classes. If the vectors are not normalised, the network can make all distances larger without improving the ranking, so systems often scale the vectors to unit length first.

When to use it: when the set of classes is open or grows, such as faces or products, and you need to compare new items against stored ones. When not to use it: when you have a fixed set of classes and plenty of labels, because a Softmax classifier is usually simpler and trains faster. A cross-entropy objective on the classifier's outputs is the usual choice there. Alternatives include Contrastive Learning with pairs and Hinge Loss-style margin objectives on classifier scores.

History

Learning a distance so that similar items are close and dissimilar ones are far apart is older than deep learning. In the mid-2000s, large-margin nearest-neighbour methods trained linear metrics with a margin constraint of this kind. Deep networks made the idea practical for images. In 2015 the FaceNet paper trained a convolutional network with triplets, chose hard triplets online, and used the resulting embedding for face verification and clustering. The paper made the method standard for embedding learning, and it is still the reference people cite when they describe triplets.

Recap

  • An embedding maps an item to a vector; similar items should get nearby vectors.
  • A triplet is an anchor, a positive of the same kind, and a negative of a different kind.
  • The loss max(0, d(a, p) − d(a, n) + α) is zero when the positive is closer by at least the margin.
  • Learning uses violated triplets, so hard and semi-hard negatives matter most.

Read next: Siamese Network for the two-branch architecture that often uses this loss, and Contrastive Learning for the closely related pair-based objective.

Check yourself

QuestionWhat are the three items in a triplet, and what must be true of the positive and the negative relative to the anchor?Show answer

The anchor, a positive from the same class, and a negative from a different class. The positive should be closer to the anchor than the negative is, by at least the margin.

QuestionWith α = 0.2, d(a, p) = 0.4 and d(a, n) = 0.5, what is the triplet loss?Show answer

0.4 − 0.5 + 0.2 = 0.1, so the loss is max(0, 0.1) = 0.1.

QuestionWhy is training on random negatives often less useful than training on hard negatives?Show answer

Random negatives are usually far from the anchor already, so their loss is zero and they produce no gradient. Hard negatives violate the margin, so they produce the gradient that moves the embedding.

QuestionA face system is deployed to recognise new employees who were not in training. Why is a triplet-trained embedding a better fit than a softmax classifier over the training identities?Show answer

A softmax classifier has one output per training identity, so it cannot name a new person. A triplet-trained embedding compares distances, so a new person is enrolled by storing their vector and matching by distance.

Sources