Overview
Triplet loss trains an embedding space by comparison. Each training item is a triple: an anchor, a positive that should be near it, and a negative that should be far. The loss looks at two distances from the anchor and asks only that the negative be farther than the positive by some margin. If that already holds, the triple costs nothing. If not, the loss is the amount by which it fails. No absolute distance is demanded, only the right ordering with a gap, which lets classes with different spreads coexist.
A short history
Kilian Weinberger and Lawrence Saul used a triplet constraint in their large margin nearest neighbour method in the mid 2000s. The loss became widely known through FaceNet, published in 2015 by Florian Schroff, Dmitry Kalenichenko and James Philbin at Google, which learned face embeddings where distance reflects identity. Their work also showed that the way triplets are selected matters as much as the loss.
How it works
- Take three batches of embeddings of shape (N, D): anchors, positives and negatives.
- Compute the anchor to positive distance and the anchor to negative distance for each row, Euclidean or squared according to
squared.distancesreturns both. - Compute the violation: positive distance minus negative distance plus the margin.
- The loss for the row is the violation if it is positive, otherwise zero.
- Reduce over the batch with
reduction. - In
backward, rows that violate the margin pull the positive toward the anchor and push the negative away. Rows that satisfy it get zero gradient.
Watch out for
- Most random triples already satisfy the margin and give no gradient. Progress depends on mining triples that still violate it.
- Training only on the very hardest negatives can collapse every embedding to one point, where all distances are zero and the loss sits at the margin.
- The margin is in the units of the embedding. Without normalising the embeddings, the model can meet it by scaling everything up.
- The number of possible triples grows with the cube of the dataset size. The template scores the triples you supply. Choosing them is your job.
Use cases
When to use it
Metric learning for face recognition, person re-identification and image or text retrieval, where you can say which of two items is more similar to a third but not how similar in absolute terms.
In industry
- Face recognition
- FaceNet trained embeddings with triplets of two photos of one person and one photo of another, so identity can be checked by distance.
- Person re-identification
- Systems that match a person across different cameras train with triplet loss and hard example mining within each batch.
- Visual product search
- Shopping services learn embeddings in which a customer's photo of an item lies closer to the matching catalogue image than to other products.
Choosing it: what must hold
- Labels or signals that let you form an anchor, a positive of the same identity and a negative of a different one.
- A mining strategy that finds hard or semi-hard negatives, since most random triplets already satisfy the margin.
- Batches built to contain several examples per identity.
When to choose something else
| If | Use instead |
|---|---|
| You only have pairs labelled similar or dissimilar | Contrastive loss |
| You have large batches and want to use every other item as a negative | InfoNCE |
| Identities form a fixed set known in advance | Softmax cross-entropy over identities |
Math foundations
The two distances
How far the anchor is from the positive and from the negative. With
squaredon, the squared distances are used in their place.The loss
Zero when the negative is at least farther from the anchor than the positive. Otherwise it is the shortfall.
Which triples contribute
A triple is easy when the negative is beyond and gives zero loss. It is semi-hard when , and hard when the negative is closer than the positive.
Gradients for an active triple
For Euclidean distances these are unit vectors. Following the negative gradient, the positive moves toward the anchor, the negative moves away, and the anchor does both.
With squared distances
The form used in FaceNet. The gradients are no longer unit vectors: they grow with the separation, and the anchor's gradient depends only on where the positive and negative are.
Symbols
- the anchor, positive and negative embeddings
- distance from the anchor to the positive
- distance from the anchor to the negative
- the margin,
marginin the config, default 1 - the loss for one triple
- the loss for one triple with squared distances
Worked by hand
Margin and a positive at distance . Try three negatives, at distances 2.0, 1.2 and 0.5.
The first negative is easy and contributes nothing. The second is semi-hard and costs 0.6. The third is hard, closer than the positive, and costs 1.3.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import TripletLoss
from config import TripletLossConfig
loss = TripletLoss(TripletLossConfig(margin=1.0))
anchor = np.array([[0.0, 0.0]])
positive = np.array([[0.6, 0.8]]) # distance 1.0 from the anchor
negative = np.array([[0.0, 1.5]]) # distance 1.5 from the anchor
print(loss.forward(anchor, positive, negative)) # max(0, 1.0 - 1.5 + 1.0) = 0.5
g_anchor, g_positive, g_negative = loss.backward(anchor, positive, negative)Read the implementation (64 lines)
"""Triplet margin loss: max(0, d(anchor, positive) - d(anchor, negative) + margin).
NumPy only. `forward` returns the loss, `backward` its gradients with respect to the anchor, the positive and the
negative.
"""
from __future__ import annotations
import numpy as np
try:
from .config import TripletLossConfig
except ImportError: # run from the template's own folder
from config import TripletLossConfig
def _embeddings(*arrays) -> list:
"""All inputs as float arrays of one shape (N, D). Raises ValueError otherwise."""
out = [np.asarray(a, dtype=float) for a in arrays]
if out[0].ndim != 2 or any(a.shape != out[0].shape for a in out):
raise ValueError(f"embeddings must all have one shape (N, D), got {[a.shape for a in out]}")
return out
def _reduce(per_row: np.ndarray, reduction: str):
"""Reduce one loss value per row: "mean" and "sum" give a float, "none" returns the (N,) array."""
if reduction == "mean":
return float(per_row.mean())
return float(per_row.sum()) if reduction == "sum" else per_row
class TripletLoss:
"""Asks the negative to be at least `margin` farther from the anchor than the positive."""
def __init__(self, config: TripletLossConfig | None = None) -> None:
self.config = config or TripletLossConfig()
def distances(self, anchor: np.ndarray, positive: np.ndarray, negative: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Anchor-positive and anchor-negative distances, each (N,). Squared when the config says so."""
anchor, positive, negative = _embeddings(anchor, positive, negative)
sq_ap, sq_an = ((anchor - positive) ** 2).sum(axis=1), ((anchor - negative) ** 2).sum(axis=1)
if self.config.squared:
return sq_ap, sq_an
return np.sqrt(sq_ap + self.config.eps), np.sqrt(sq_an + self.config.eps)
def forward(self, anchor: np.ndarray, positive: np.ndarray, negative: np.ndarray):
"""anchor, positive, negative: (N, D) embeddings. Returns a float, or (N,) for "none"."""
d_ap, d_an = self.distances(anchor, positive, negative)
return _reduce(np.maximum(0.0, d_ap - d_an + self.config.margin), self.config.reduction)
def backward(self, anchor: np.ndarray, positive: np.ndarray, negative: np.ndarray) -> tuple[np.ndarray, ...]:
"""Gradients of the reduced loss with respect to anchor, positive and negative, each (N, D).
Rows that already satisfy the margin get zero gradient. For "none" the per-row gradients are returned
unscaled.
"""
anchor, positive, negative = _embeddings(anchor, positive, negative)
d_ap, d_an = self.distances(anchor, positive, negative)
active = ((d_ap - d_an + self.config.margin) > 0).astype(float)[:, None]
if self.config.squared:
unit_ap, unit_an = 2.0 * (anchor - positive), 2.0 * (anchor - negative)
else: # derivative of a distance is the unit vector along the difference
unit_ap, unit_an = (anchor - positive) / d_ap[:, None], (anchor - negative) / d_an[:, None]
scale = active / len(d_ap) if self.config.reduction == "mean" else active
return scale * (unit_ap - unit_an), scale * -unit_ap, scale * unit_an
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 6, run with
python3 -m unittest -v
Practice
Build TripletLoss(TripletLossConfig(margin=1.0, reduction="none")). Place an anchor at the origin and a positive at (0.8, 0), and try negatives at (2, 0), (1.2, 0) and (0.5, 0). Check distances, forward and the three arrays from backward against the worked example. Then set all three points equal and read the loss.
Check on learning
- After a few epochs, 99 percent of randomly drawn triples have zero loss. Is the embedding nearly perfect?
A way to think about it
Random negatives are mostly unrelated items that are easy to separate. Ask how the model does on the rare look-alike negatives that retrieval quality depends on.
- If every embedding collapses to the same point, what is the loss, and why might hardest-negative mining lead there?
A way to think about it
With all distances zero the loss equals the margin for every triple. Look at the gradient on the anchor when the negative is much closer than the positive, and where it moves things.
- Triplet loss constrains only the difference of two distances. Contrastive loss constrains each distance on its own. What freedom does that give triplet loss?
A way to think about it
A class with naturally varied members can stay spread out, provided others stay farther still. Consider what forcing every same-class pair to distance zero would do.
- Why are embeddings usually normalised to unit length before this loss is applied?
A way to think about it
On the unit sphere distances are bounded, so the margin has a fixed meaning. Otherwise doubling all embeddings doubles every distance gap and satisfies the margin without learning.
- With
squaredon, the anchor's gradient is and does not involve the anchor's own position. What does that imply about how the anchor moves?A way to think about it
Gradient descent moves the anchor in the direction , away from the negative and toward the positive side, and that direction is the same wherever the anchor sits.