AI Logic

Loss Functions

Triplet Loss

Updated:

Diagram of Triplet Loss. The left side shows the embedding space before training: the positive p of the same person as the anchor a is far, and the negative n of a different person is near. p is pulled toward a, and n is pushed away from a. The right side shows the space after training: p is near a, and n lies outside the distance to p by the margin α. On the far right are the legend and the training goal d(a, p)² + α < d(a, n)²

Background and Overview

Triplet Loss is a loss function that uses sets of three examples (triplets) to learn embeddings in which "the distance between examples of the same kind" is shorter than "the distance to examples of a different kind" by a margin. It is used for tasks such as face recognition, where there are a huge number of classes and people unseen during training must also be distinguished.

A triplet consists of the following three examples.

  • Anchor xax^a: the reference example (a face photo of some person)
  • Positive xpx^p: an example of the same kind as the anchor (another photo of the same person)
  • Negative xnx^n: an example of a different kind from the anchor (a photo of another person)

With f(x)f(x) denoting the embedding output by the network, Triplet Loss is as follows.

L=∑i[ ∥f(xia)−f(xip)∥22−∥f(xia)−f(xin)∥22+α ]+L = \sum_{i} \Bigl[\ \lVert f(x_i^a) - f(x_i^p) \rVert_2^2 - \lVert f(x_i^a) - f(x_i^n) \rVert_2^2 + \alpha\ \Bigr]_+

[ ⋅ ]+=max⁡(0, ⋅ )[\,\cdot\,]_+ = \max(0,\ \cdot\,), and α\alpha is the margin. As in the figure at the top, the goal is a state in which the anchor–positive distance plus α\alpha still falls short of the anchor–negative distance.

This loss was popularized by FaceNet, the face recognition system of Schroff et al. at Google (2015). FaceNet embeds face photos into 128-dimensional vectors and learns so that the distance between vectors directly reflects how similar the faces are. Once this space exists, deciding whether two faces are the same person is a distance threshold, identifying someone is finding the closest enrolled face, and grouping people is clustering by distance. The paper says it took the idea of this loss from metric learning for nearest-neighbor classification (classifying with the label of the closest example) by Weinberger et al. (2005).

Theory (How the Loss Is Computed)

FaceNet's Triplet Loss is computed in the following steps.

  1. Pass the three images through the same network (a convolutional neural network in FaceNet) to obtain dd-dimensional embeddings f(xa), f(xp), f(xn)f(x^a),\ f(x^p),\ f(x^n).
  2. Normalize the embeddings to unit length (∥f(x)∥2=1\lVert f(x) \rVert_2 = 1). All embeddings lie on a sphere of radius 1, so distances stay within a fixed range (0 to 4 in squared distance).
  3. Compute the squared anchor–positive distance dap=∥f(xa)−f(xp)∥22d_{ap} = \lVert f(x^a) - f(x^p) \rVert_2^2 and the squared anchor–negative distance dan=∥f(xa)−f(xn)∥22d_{an} = \lVert f(x^a) - f(x^n) \rVert_2^2.
  4. Take max⁡(0, dap−dan+α)\max(0,\ d_{ap} - d_{an} + \alpha) as the loss. FaceNet sets the margin to α=0.2\alpha = 0.2.
  5. Sum (or average) the loss over all selected triplets and update the network with backpropagation.

For example, with α=0.2\alpha = 0.2, dap=0.6d_{ap} = 0.6, and dan=0.7d_{an} = 0.7, the loss is max⁡(0, 0.6−0.7+0.2)=0.1\max(0,\ 0.6 - 0.7 + 0.2) = 0.1. The negative is farther than the positive, but the slack is only 0.10.1, so a loss remains. With dan=1.0d_{an} = 1.0, the loss is 0 and this triplet produces no gradient.

Triplet selection: Triplets with zero loss (easy triplets) do not help training, so FaceNet considers selecting triplets that violate the constraint essential for fast convergence. Relative to the anchor, negatives fall into three types.

Type of negativeConditionLoss
Easy negativedap+α≤dand_{ap} + \alpha \le d_{an}0 (not used in training)
Semi-hard negativedap<dan<dap+αd_{ap} < d_{an} < d_{ap} + \alphaGreater than 00 and less than α\alpha
Hard negativedan≤dapd_{an} \le d_{ap}α\alpha or more

FaceNet notes that searching the whole training set for the hardest triplets is computationally infeasible and tends to pick only mislabeled or poorly imaged faces, so it adopted selecting triplets within the mini-batch (online selection). Mini-batches of a few thousand images (about 1,800 in most experiments) are built so that each person has about 40 faces; all anchor–positive pairs in the mini-batch are used, and negatives are chosen from those satisfying dap<dand_{ap} < d_{an} (semi-hard).

Why It Produces Useful Embeddings

Triplet Loss can produce embeddings that support decisions by distance for three reasons.

  • It turns the desired property directly into the loss: What face verification needs is the distance relationship "the same person is near, a different person is far." Triplet Loss makes this relationship the direct objective. Earlier deep learning methods reused an intermediate (bottleneck) layer of a network trained for classification as the embedding. FaceNet says that optimizing the embedding itself yielded a representation efficient enough to describe one face in 128 bytes.
  • It asks only for relative relationships, not absolute distances: A pairwise loss that dictates "pull the same person to within this distance" tries to collapse the faces of one person to a single point in the embedding. Triplet Loss only asks that they be "closer than other people," so the faces of one person can spread out while preserving differences in pose and lighting. FaceNet cites this as the reason Triplet Loss suits face verification.
  • The hinge form focuses training on the triplets that fall short: The loss has the same max⁡(0, ⋅ )\max(0,\ \cdot\,) form as the hinge loss, so triplets that already satisfy the margin produce no gradient. Training goes only to triplets not yet distinguished.

As an analogy, it is like organizing photos with only one arrangement rule: "place each photo of this person closer to this person's other photos than to anyone else's photos." Without deciding a spot for each person in advance, following the rule naturally gathers the photos of each person together.

Experimental Results

FaceNet was trained on 100–200 million face images of about 8 million identities and achieved the best accuracy of its time on standard face verification datasets.

DatasetFaceNetDeepFaceDeepID2+
LFW (face verification accuracy)99.63% ± 0.09 (with face alignment), 98.87% ± 0.15 (center crop only)—99.47%
YouTube Faces DB (video verification accuracy)95.12% ± 0.3991.4%93.2%

On LFW, the paper reports reducing the error of DeepFace by more than a factor of 7 and the error of DeepID2+ by 30%.

In a comparison of embedding dimensions (the rate of correctly accepting the same person at a 0.1% rate of falsely accepting different people), 64 dimensions gave 86.8%, 128 gave 87.9%, 256 gave 87.7%, and 512 gave 85.6%; the paper states that these differences are not statistically significant. Increasing the training images from 2.6 million to 26 million raised the same metric from 76.3% to 85.1% (a smaller model, 700 hours of training).

The FaceNet paper does not directly compare Triplet Loss with other losses (such as pairwise losses) under the same conditions. The numbers above are results of the whole system, including massive training data, network architecture, and face alignment, and do not show the effect of the loss alone.

Practical Considerations

Triplet selection largely decides whether training succeeds. With random selection, most triplets are easy with zero loss, and training stalls. Conversely, FaceNet reports that selecting only the hardest negatives can lead to bad local minima early in training, collapsing all inputs to the same point (a collapse such as f(x)=0f(x) = 0). Choosing semi-hard negatives avoids this.

Keep the following points in mind as well.

  • Put several examples of the same kind in each mini-batch: Forming anchor–positive pairs requires several images of the same person in one mini-batch. FaceNet selected about 40 images per person and also added random negatives. Fully random sampling, as in ordinary classification, cannot form pairs. The batch size also needs to be large enough to find hard triplets.
  • PyTorch's nn.TripletMarginLoss defines distance differently from FaceNet: By default it uses the non-squared distance ∥a−p∥2\lVert a - p \rVert_2, a default margin of 1.0, and no normalization of embeddings. To match FaceNet, normalize the embeddings and pass a squared-distance function to nn.TripletMarginWithDistanceLoss, or write it yourself. The appropriate margin also depends on the distance definition.
  • The number of triplets is enormous: The number of triplets from NN examples grows on the order of N3N^3, so not all can be used. Which triplets are chosen directly determines computation and training speed.
  • Training takes a long time: FaceNet trained for 1,000–2,000 hours on a CPU cluster and reports that while the decrease in loss slowed sharply after about 500 hours, performance kept improving with further training.

Comparison with Other Methods

Triplet Loss and related losses for learning embeddings are lined up from the same viewpoint.

Loss functionData used at onceWhat it asks forMain uses
Contrastive LossTwo examples (a pair) and a label for whether they are the same kindPull the same kind toward distance 0 and push different kinds beyond margin mm (absolute distances)Deciding whether two inputs are the same, dimensionality reduction
Triplet LossThree (anchor, positive, negative)Place the positive closer than the negative by α\alpha (relative distances)Face verification, image retrieval, nearest-neighbor search tasks
Intermediate layer of a network trained with a classification loss (cross-entropy)One example and a class labelPredict the class; the embedding is a by-productClassification with a fixed set of classes

Guidelines for choosing:

  • To distinguish classes unseen in training by distance, use Triplet Loss or Contrastive Loss: Both learn distance relationships directly instead of predicting classes.
  • If same-class examples may spread out, use Triplet Loss: It asks only for relative relationships, so it does not squeeze a class into a single point.
  • If only pair labels (same or different) are available, use Contrastive Loss: Triplet Loss needs both a same-kind and a different-kind example for each anchor.
  • Either way, triplet or pair selection needs care: How useful combinations are gathered affects the results more than the loss formula.

PyTorch example

Show code
python
import torch
import torch.nn as nn
import torch.nn.functional as F

# 1) PyTorch built-in: non-squared L2 distance, default margin 1.0, no normalization
anchor = torch.randn(32, 128, requires_grad=True)
positive = torch.randn(32, 128)
negative = torch.randn(32, 128)
criterion = nn.TripletMarginLoss(margin=1.0, p=2)
loss = criterion(anchor, positive, negative)

# 2) Match FaceNet Eq. (3): normalize embeddings to unit length, use squared distance and margin α = 0.2
def sq_dist(x, y):
    return (x - y).pow(2).sum(dim=1)

facenet_criterion = nn.TripletMarginWithDistanceLoss(distance_function=sq_dist, margin=0.2)
loss = facenet_criterion(F.normalize(anchor, dim=1), F.normalize(positive, dim=1), F.normalize(negative, dim=1))

# 3) Select triplets within the mini-batch (FaceNet Sec. 3.2): use all anchor-positive pairs,
#    and pick negatives from those satisfying d_ap < d_an (semi-hard).
#    The paper only says to pick ones satisfying Eq. (4); here the closest of them is chosen (one possible implementation)
def batch_semi_hard_triplet_loss(embeddings, labels, alpha=0.2):
    emb = F.normalize(embeddings, dim=1)
    d = torch.cdist(emb, emb).pow(2)                     # matrix of squared distances
    same = labels[:, None] == labels[None, :]
    eye = torch.eye(len(labels), dtype=torch.bool, device=emb.device)
    losses = []
    for a, p in (same & ~eye).nonzero():
        d_ap = d[a, p]
        candidates = (~same[a]) & (d[a] > d_ap)           # Eq. (4): negatives farther than the positive
        if candidates.any():
            d_an = d[a][candidates].min()
            losses.append(F.relu(d_ap - d_an + alpha))
    if not losses:
        return emb.sum() * 0.0
    return torch.stack(losses).mean()

# Build mini-batches with several images per person (here dummy data: 8 people × 4 images)
labels = torch.arange(8).repeat_interleave(4)
model = nn.Sequential(nn.Flatten(), nn.Linear(3 * 32 * 32, 256), nn.ReLU(), nn.Linear(256, 128))
images = torch.randn(32, 3, 32, 32)
loss = batch_semi_hard_triplet_loss(model(images), labels)
loss.backward()

FAQ

Q. What value should the margin α take?
A.

It depends on the distance definition. FaceNet used α=0.2\alpha = 0.2 with squared distances (range 0 to 4) between unit-length embeddings. When using a non-squared distance, as PyTorch's nn.TripletMarginLoss does, the same value does not necessarily carry over, so tune it on validation data.

Q. Why can it distinguish faces of people unseen in training?
A.

Because Triplet Loss does not learn to identify specific people; it learns the distance relationship "faces of the same person are near, faces of different people are far." If a new person's face is embedded with the same network, matching only requires measuring its distance to the enrolled faces.

Q. The loss quickly drops to 0 and training stalls.
A.

Most triplets may already satisfy the margin (they have become easy triplets). Select semi-hard or hard triplets that do not satisfy the margin from within the mini-batch. Conversely, if the loss does not decrease and all embeddings gather at the same point, check whether you are selecting only the hardest negatives.

References

  1. F. Schroff, D. Kalenichenko, and J. Philbin, "FaceNet: A Unified Embedding for Face Recognition and Clustering," CVPR, 2015.
  2. K. Q. Weinberger, J. Blitzer, and L. K. Saul, "Distance Metric Learning for Large Margin Nearest Neighbor Classification," NIPS 18, 2005.
  3. PyTorch Documentation, "torch.nn.TripletMarginLoss."
  4. PyTorch Documentation, "torch.nn.TripletMarginWithDistanceLoss."