Triplet Loss: Formula, Margin and Free Calculator

Triplet loss trains a network to place similar things close together and different things far apart in an embedding space. This page gives the formula, a free calculator that takes the two distances and the margin, a worked example with real numbers, and the mistakes that most often stall training.

What is triplet loss? The formula

Each training example is a triplet: an anchor \( a \), a positive \( p \) from the same class (another photo of the same person, say), and a negative \( n \) from a different class. The network maps each one to a vector, and \( d \) measures the distance between two of those vectors. The loss is:

\[ L(a, p, n) = \max\big(d(a,p) – d(a,n) + m,\; 0\big) \]

Here \( m > 0 \) is the margin. In words: the negative must be further from the anchor than the positive is, by at least \( m \). When that holds, the loss is exactly 0 and the triplet teaches the model nothing. When it does not, the loss equals the shortfall.

The idea is best known from FaceNet (Schroff, Kalenichenko and Philbin, 2015), which learned 128-dimensional face embeddings this way. FaceNet used squared Euclidean distance on embeddings scaled to unit length (see vector norms) and a margin of 0.2. You can read the original paper, FaceNet: A Unified Embedding for Face Recognition and Clustering (arXiv).

triplet loss chart

Triplet loss calculator

Enter the anchor-positive distance, the anchor-negative distance and the margin. If you have the embedding vectors instead, paste them in the second panel and the calculator will work out the distances for you.

L = —L = max(d(a, p) − d(a, n) + m, 0)
Loss L—
Gap d(a, n) − d(a, p)—
Triplet type—
d(a, n) needed for zero loss—
loss as d(a, n) changesyour triplet
Optional: get the distances from embedding vectors
Example loaded. Press the blue button to calculate.

Worked example with real numbers

Suppose the network maps an anchor face, a second photo of the same person and a photo of someone else to three vectors, and the distances come out as \( d(a,p) = 0.8 \) and \( d(a,n) = 1.1 \). Take a margin of \( m = 0.5 \).

  1. Compare the distances: \( 0.8 - 1.1 = -0.3 \). The negative is already 0.3 further from the anchor than the positive.
  2. Add the margin: \( -0.3 + 0.5 = 0.2 \). The model wanted a gap of 0.5 and only got 0.3.
  3. Clip at zero: \( \max(0.2, 0) = 0.2 \).

The loss is 0.2. Training will try to close that shortfall, either by pushing the negative out to \( d(a,n) = 1.3 \) or by pulling the positive in to \( d(a,p) = 0.6 \) (or a bit of both). Once the gap reaches 0.5, the loss for this triplet becomes 0.

Now look at three triplets with a margin of 0.2, one of each type:

Tripletd(a, p)d(a, n)LossType
10.51.40Easy: gap 0.9 is bigger than the margin
20.30.40.1Semi-hard: negative further, but by less than 0.2
31.20.90.5Hard: negative is closer than the positive

The mean over the batch is \( (0 + 0.1 + 0.5) / 3 = 0.2 \). Notice that triplet 1 contributes nothing: its loss is flat at zero, so backpropagation sends no gradient through it. If most of your triplets look like triplet 1, gradient descent barely moves.

When to use triplet loss, and when not to

This loss shines when you need a similarity measure rather than a fixed list of classes, especially when new classes appear after training:

  • Face verification and recognition: a new employee is enrolled from a single photo, with no retraining.
  • Image and product retrieval: find the items nearest to a query using k-nearest neighbours on the embeddings.
  • Person re-identification, speaker and signature verification, and similarity models in recommender systems.

It is a poor fit when you have a small, fixed set of classes with plenty of labelled examples each. There, an ordinary classifier trained with cross-entropy loss is simpler, faster and easier to tune. The number of possible triplets grows roughly with the cube of the dataset size, and most of them are easy, so the method needs careful triplet selection (called mining) to train well.

Triplet loss vs contrastive loss

The nearest alternative is contrastive loss (Hadsell, Chopra and LeCun, 2006), which works on pairs. With \( y = 1 \) for a similar pair and \( y = 0 \) for a dissimilar one:

\[ L = y\, d^2 + (1 - y)\,\max(m - d,\; 0)^2 \]

Label conventions differ between papers and libraries (some use \( y = 0 \) for similar pairs), so check which one your code expects.

Contrastive lossTriplet loss
Training unitA pair, labelled same or differentAnchor, positive and negative
What it asks forAbsolute distances: similar pairs near 0, dissimilar pairs beyond \( m \)Relative distances: the negative further than the positive by \( m \)
Loss is zero whenSimilar pair at distance 0, or dissimilar pair beyond \( m \)\( d(a,n) \ge d(a,p) + m \)
Main difficultyChoosing one global distance thresholdFinding informative triplets

Both share the \( \max(\cdot, 0) \) shape of hinge loss: once a constraint is met by the margin, the example stops contributing. For a wider view, see the guide to loss functions.

Common mistakes

  • Mixing squared and plain distances. The margin is measured in the same units as \( d \). FaceNet used squared Euclidean distance with \( m = 0.2 \); PyTorch's TripletMarginLoss uses plain Euclidean distance with a default margin of 1.0. A margin copied from one setting is not automatically right in the other.
  • Not normalising the embeddings. If the vectors can grow without limit, the network can satisfy any margin by scaling everything up. Normalising every embedding to unit length keeps the margin meaningful.
  • Only random triplets. Most are easy, so the loss sits at zero and learning stalls. FaceNet chose semi-hard negatives inside each mini-batch.
  • Only the hardest negatives, from the start. The FaceNet authors report this can lead to bad local minima early on, including a collapsed model that maps every input to the same point.
  • Splitting data by image, not by identity. If the same person appears in training and test sets, the test score is inflated, a form of data leakage.

Frequently asked questions

What margin should I use?

It depends on the distance and on whether embeddings are normalised. FaceNet used 0.2 with squared distances on unit-length embeddings; PyTorch defaults to 1.0 with plain Euclidean distance. Treat it as a hyperparameter and tune it on a validation set.

Why is my triplet loss stuck at exactly the margin?

That usually signals collapse. If every embedding is the same point, both distances are 0 and the loss is \( \max(0 - 0 + m, 0) = m \). Try easier mining at the start, a lower learning rate, or normalised embeddings.

Can triplet loss be negative?

No. The \( \max(\cdot, 0) \) clips it at zero, so the smallest value is 0, reached by any triplet whose negative is at least \( m \) further away than its positive.

Which distance should I use?

Euclidean distance (squared or not) is the most common. Cosine distance, \( 1 - \cos\theta \), also works and is closely related once vectors have unit length; try the cosine similarity calculator to see how the two compare.

What is a semi-hard negative?

A negative that is further from the anchor than the positive, but by less than the margin: \( d(a,p) < d(a,n) < d(a,p) + m \). It still gives a positive loss, without the instability of the very hardest negatives.

Related: Contrastive Loss: Formula, Margin and Free Calculator

Scroll to Top