Contrastive and Triplet Losses
Face unlock, "more like this" product search, duplicate-question detection and speaker verification share a problem that ordinary classification cannot solve: the classes at test time are people, products or questions the model has never seen. Instead of predicting a label, the model learns an embedding , a vector in which similar items are close and different ones are far apart. A new face is then recognised by its nearest stored embedding. The losses that shape such a space compare examples with each other instead of with a label: the contrastive loss works on pairs, the triplet loss on triples. This lesson implements both with their gradients and trains a small linear embedding with triplets.
Contrastive loss: pairs
Take pairs with a label for "same" and for "different", and let be the distance between their embeddings. The contrastive loss (Hadsell, Chopra and LeCun, 2006) is
Similar pairs are pulled together (their loss is , zero only at ); dissimilar pairs are pushed apart, but only until they are at least the margin apart. Without the margin, the easiest way to lower the loss would be to push everything infinitely far away. The gradient with respect to the first embedding is
and the gradient for is its negative.
import numpy as np
def contrastive(e1, e2, same, margin=1.0):
d = np.linalg.norm(e1 - e2, axis=1)
loss = same * d ** 2 + (1 - same) * np.maximum(0, margin - d) ** 2
return 0.5 * np.mean(loss), d
def contrastive_grad_e1(e1, e2, same, margin=1.0): # d loss / d e1 (e2 gets the opposite sign)
diff = e1 - e2
d = np.linalg.norm(diff, axis=1, keepdims=True)
pull = same[:, None] * diff
push = (1 - same)[:, None] * -np.maximum(0, margin - d) * diff / d
return (pull + push) / len(same)
e1 = np.array([[0.0, 0.0], [1.0, 1.0], [0.0, 1.0], [2.0, 0.0]])
e2 = np.array([[0.3, 0.4], [1.0, 1.2], [0.0, 1.6], [0.0, 0.0]])
same = np.array([1.0, 0.0, 0.0, 0.0]) # pair 0 similar, pairs 1-3 dissimilar
loss, d = contrastive(e1, e2, same)
print("distances", np.round(d, 3), " loss", round(loss, 4))
print("pair 3 is already farther than the margin, so it adds nothing")
h, num = 1e-6, np.zeros_like(e1)
for i in range(4):
for k in range(2):
E = np.zeros_like(e1); E[i, k] = h
num[i, k] = (contrastive(e1 + E, e2, same)[0] - contrastive(e1 - E, e2, same)[0]) / (2 * h)
print("gradient matches numeric:", np.allclose(contrastive_grad_e1(e1, e2, same), num, atol=1e-8))
print("gradient on e1:\n", np.round(contrastive_grad_e1(e1, e2, same), 4))distances [0.5 0.2 0.6 2. ] loss 0.1312
pair 3 is already farther than the margin, so it adds nothing
gradient matches numeric: True
gradient on e1:
[[-0.075 -0.1 ]
[ 0. 0.2 ]
[ 0. 0.1 ]
[ 0. 0. ]]
The similar pair at distance 0.5 costs ; the dissimilar pairs at 0.2 and 0.6 cost and ; the pair at distance 2 is already beyond the margin and costs nothing, so its gradient is zero. The total is , printed rounded to 0.1312. The gradient rows point the way: the first pair's moves towards (gradient descent subtracts it), the second and third move away.
Triplet loss: an anchor, a positive, a negative
The triplet loss (used by FaceNet, Schroff et al., 2015) compares two distances at once. For an anchor , a positive of the same identity and a negative of another identity,
It does not care about absolute distances, only that every negative is at least farther from the anchor than every positive. That is exactly what nearest-neighbour retrieval needs. (FaceNet uses squared distances and L2-normalised embeddings; both variants are common.)
Easy, semi-hard and hard negatives
Most random triplets are already satisfied and contribute nothing. Which triplets you train on, mining, matters more than the details of the loss:
import numpy as np
margin = 0.5
anchor = np.array([0.0, 0.0])
positive = np.array([1.0, 0.0]) # same identity, distance 1.0
negatives = {"n1": np.array([0.0, 2.0]), # far away
"n2": np.array([-1.2, 0.0]), # a bit farther than the positive
"n3": np.array([0.6, 0.3])} # closer than the positive
d_ap = np.linalg.norm(anchor - positive)
for name, neg in negatives.items():
d_an = np.linalg.norm(anchor - neg)
loss = max(0.0, d_ap - d_an + margin)
if d_an > d_ap + margin: kind = "easy (loss 0, no gradient)"
elif d_an > d_ap: kind = "semi-hard (right order, inside the margin)"
else: kind = "hard (negative closer than the positive)"
print(f"{name}: d(a,n) {d_an:.3f} loss {loss:.3f} {kind}")
hardest = min(negatives, key=lambda k: np.linalg.norm(anchor - negatives[k]))
print("batch-hard mining picks", hardest)n1: d(a,n) 2.000 loss 0.000 easy (loss 0, no gradient)
n2: d(a,n) 1.200 loss 0.300 semi-hard (right order, inside the margin)
n3: d(a,n) 0.671 loss 0.829 hard (negative closer than the positive)
batch-hard mining picks n3
- Easy negatives () have zero loss and zero gradient: wasted computation.
- Semi-hard negatives are farther than the positive but inside the margin; FaceNet trained on these.
- Hard negatives are closer than the positive. They carry the most signal but also include mislabelled pairs and outliers, and training only on the hardest ones (batch-hard mining: for each anchor, the farthest positive and the closest negative in the batch) can collapse all embeddings to one point early in training. A common recipe: start with semi-hard or random triplets, move to harder ones later.
Training a linear embedding with triplets
Three classes live in 6 dimensions; only the first two dimensions carry the class, the other four are loud noise ( against a class spread of 0.6). A random linear map to 2-D mixes noise and signal. Training with the squared-distance triplet loss on mini-batches of random triplets should teach it to look only at the signal dimensions. The gradient of with respect to is .
import numpy as np
rng = np.random.default_rng(0)
# 3 classes in 6-D: dims 0-1 carry the class, dims 2-5 are loud noise
centres = np.array([[0, 0], [3, 0], [0, 3]], dtype=float)
def make(n):
lab = rng.integers(0, 3, n)
X = np.column_stack([centres[lab] + rng.normal(0, 0.6, (n, 2)), rng.normal(0, 3, (n, 4))])
return X, lab
X_tr, y_tr = make(150)
X_te, y_te = make(300)
def sample_triplets(lab, k):
a = rng.integers(0, len(lab), k)
p = np.array([rng.choice(np.flatnonzero((lab == lab[i]) & (np.arange(len(lab)) != i))) for i in a])
n = np.array([rng.choice(np.flatnonzero(lab != lab[i])) for i in a])
return a, p, n
def triplet_loss(W, a, p, n, margin=1.0):
dap = ((X_tr[a] - X_tr[p]) @ W.T) ** 2
dan = ((X_tr[a] - X_tr[n]) @ W.T) ** 2
return np.maximum(0, dap.sum(1) - dan.sum(1) + margin)
def nn_accuracy(W): # 1-nearest-neighbour accuracy in embedding space
Etr, Ete = X_tr @ W.T, X_te @ W.T
s = (Ete ** 2).sum(1)[:, None] + (Etr ** 2).sum(1)[None, :] - 2 * Ete @ Etr.T
return np.mean(y_tr[s.argmin(1)] == y_te)
W = rng.normal(0, 1, (2, 6)) # embedding: 6-D input -> 2-D
W /= np.linalg.norm(W) # keep ||W|| = 1, else the loss can shrink by scaling
a, p, n = sample_triplets(y_tr, 2000)
print(f"before: triplet loss {triplet_loss(W, a, p, n).mean():.3f} 1-NN test accuracy {nn_accuracy(W):.3f}")
lr = 0.02
for step in range(200):
a, p, n = sample_triplets(y_tr, 64) # a fresh mini-batch of random triplets
act = triplet_loss(W, a, p, n) > 0 # only violating triplets have a gradient
dp, dn = X_tr[a[act]] - X_tr[p[act]], X_tr[a[act]] - X_tr[n[act]]
G = 2 * W @ (dp.T @ dp - dn.T @ dn) / len(a) # d/dW of ||W(a-p)||^2 - ||W(a-n)||^2
W -= lr * G
W /= np.linalg.norm(W) # project back onto ||W|| = 1
a, p, n = sample_triplets(y_tr, 2000)
print(f"after: triplet loss {triplet_loss(W, a, p, n).mean():.3f} 1-NN test accuracy {nn_accuracy(W):.3f}")
print("mean |weight| on the 2 signal dims:", round(np.abs(W[:, :2]).mean(), 3),
" on the 4 noise dims:", round(np.abs(W[:, 2:]).mean(), 3))before: triplet loss 8.247 1-NN test accuracy 0.407
after: triplet loss 0.071 1-NN test accuracy 0.983
mean |weight| on the 2 signal dims: 0.384 on the 4 noise dims: 0.017
After 200 steps the triplet loss falls from 8.247 to 0.071 and the 1-nearest-neighbour accuracy on 300 new points rises from 0.407 (barely above chance for three classes) to 0.983. The learned map puts almost all its weight on the two signal dimensions (mean absolute weight 0.384 against 0.017). The constraint is a safeguard. With squared distances, scaling by multiplies by , so every triplet that is already in the right order can be pushed past the fixed margin just by blowing up the embedding, without learning anything. With random triplets the hinge stops pushing once most triplets are satisfied, and the run happens to converge even without the constraint; with batch-hard mining, which always finds violators, an unconstrained grew without bound when we tried it. Deep networks get the same protection by L2-normalising each embedding.
When to use which
| Loss | Needs | Good for |
|---|---|---|
| contrastive (pairs) | "same/different" pairs | verification (is this the same person?), duplicate detection |
| triplet | identities, to build | retrieval and re-identification, where the ranking of neighbours matters |
| InfoNCE / NT-Xent (one positive against many negatives with a softmax) | many negatives per batch | self-supervised pretraining (SimCLR, CLIP), modern retrieval |
InfoNCE treats the problem as a classification of the positive among candidates with cross-entropy over similarity scores; it is the most common choice today. The embeddings these losses learn are evaluated with retrieval metrics (recall at , mean average precision), not with accuracy.
Pitfalls
- No margin, or no normalisation. The embedding either collapses (everything at one point) or explodes. Check the spread of embeddings during training.
- Leaking identities. Split train and test by identity (group splits), or the test measures memorised faces, not generalisation to new people.
- Hardest negatives from the start. Label noise makes the hardest negatives unreliable; mine gradually.
Practice
- Anchor-positive distance 1.0, anchor-negative distance 1.3, margin 0.5. What is the triplet loss, and what kind of negative is it?
Answer
. The negative is farther than the positive but inside the margin: semi-hard.
- Why does the contrastive loss need a margin for dissimilar pairs but not a "minimum distance" for similar pairs?
Answer
Similar pairs have a natural optimum, distance 0. Pushing dissimilar pairs apart has no natural end: without a margin the loss keeps rewarding larger distances, and the embedding grows without bound. The margin says "far enough".
Test yourself
In the contrastive loss, a dissimilar pair at distance with margin contributes…
- 0
- a negative loss
The triplet loss is zero when…
Why did the lesson keep while training with squared distances?
- To make training faster
- Otherwise scaling up can lower the loss without learning anything useful
- Because the margin is 1
- To avoid overfitting to the test set
Face images for an embedding model must be split into training and test sets…
- randomly by image
- by identity, so test people never appear in training
- by image size
- by time of day