Metric learning: learning a distance

A classification model picks one of a fixed set of classes. Metric learning does not pick. It learns a space where the same things sit close and different things sit far apart. Move the three points below, change the margin, and press "One training step".

Short answer. Metric learning trains a model that turns an input into a vector (an embedding) so that the same things end up close and different things end up far apart. Because it measures distance instead of picking a class, it can tell whether two things are "the same" even for people or objects it never saw in training, by comparing their embedding with a stored one. The best-known losses are contrastive loss, which looks at one pair, and triplet loss, which looks at three.

Put the negative

d(a, p)
d(a, n)
Loss
Negative

Black a is the anchor (the reference), green p is the positive (the same thing as the anchor), blue n is the negative (a different thing). The anchor stays put; you can drag p and n (with a keyboard, use the negative buttons and the margin slider). The solid circle has radius d(a, p) and the dashed circle d(a, p) + margin. A negative in the red area is hard, in the yellow band semi-hard, in the green outside easy. When the loss is above 0, arrows on p and n show which way the next step will move them (drawn longer so you can see them). This is a small calculation that moves the points directly, not the result of training a real model.

Try this. (1) As it starts (d(a, p) = 1.5, d(a, n) = 1.9, margin 1) the loss is 1.5 − 1.9 + 1 = 0.6: semi-hard. Press "One training step": p moves 0.25 toward the anchor and n 0.25 away, and the loss drops to 0.1. Press once more and it is 0. After that, pressing moves nothing. (2) Then press "hard": n lands at distance 0.5, half of the current d(a, p) = 1, and the loss is 1 − 0.5 + 1 = 1.5. Each step lowers it by 0.5: 1, 0.5, 0. (3) Press "Start over", then "easy": d(a, n) = 3.2 and the loss is 0. Leave n there and raise the margin to 2: the loss becomes 1.5 − 3.2 + 2 = 0.3 and the negative is now semi-hard.

Definitions

The text below uses three points on a plane. These are the textbook definitions. d(x, y) is the distance between two embeddings, and the experiment on this page uses the Euclidean distance.

metric learning
A way of training a model that turns inputs into vectors (embeddings), so that the distance between embeddings of the same thing is small and the distance between different things is large. It is also called distance metric learning.
contrastive loss
A loss measured on one pair of two inputs. d is the distance between the two embeddings, s is 1 for a pair of the same thing and 0 for a pair of different things, and m is the margin. A same pair is pulled toward distance 0, and a different pair is pushed only while it is closer than m. Below is the widely used form that the text uses.

L=sd2+(1−s)max(0,m−d)2

triplet loss
A loss measured on one group (a triplet) of an anchor a, a positive p that is the same thing as the anchor, and a negative n that is a different thing. It is 0 if the negative is at least the margin farther than the positive, and otherwise it is the amount that is missing. The FaceNet paper writes the same formula with squared distances between embeddings scaled to length 1.

L=max(0,d(a,p)−d(a,n)+margin)

margin
A spare distance of 0 or more that you choose. In the contrastive loss it is the distance a different pair should at least keep. In the triplet loss it is how much farther the negative should at least be than the positive.
easy, semi-hard, hard negative
Kinds of triplets, split by the distance of the negative compared with the anchor and the positive. A triplet that meets the first formula below has an easy negative (loss 0), the second a semi-hard negative, and the third a hard negative. Picking the triplets to train on is called triplet mining.

d(a,n)≥d(a,p)+margin

d(a,p)≤d(a,n)<d(a,p)+margin

d(a,n)<d(a,p)

L2 normalization
Dividing a nonzero vector by its Euclidean length so that its length becomes 1.

𝐯^=𝐯‖𝐯‖

1. How it differs from classification

A classification model ends with one score slot per class and picks the largest (trained with cross-entropy). So the classes must be fixed in advance. Train it to tell 100 employees' faces apart, and when person number 101 arrives there is no slot for them: the output layer has to change and the model has to be trained again.

Metric learning does not pick a class at the end. It outputs one vector (an embedding), and it is trained so that photos of the same person land close together and photos of different people land far apart. Then when a new person arrives, the model stays as it is: store the embedding of their photo and measure the distance to the next photo. It fits jobs that ask "are these two the same?", such as face verification or finding similar products.

FaceNet (see sources) maps face photos into a compact space where distances correspond to how similar the faces are. It optimizes the embedding itself directly rather than an intermediate bottleneck layer, and represents a face in 128 bytes. The paper reports 99.63% accuracy on LFW and 95.12% on YouTube Faces DB.

Training sentence embeddings with the same idea (pull pairs together, push non-pairs apart) is in section 3 of the embedding models page. This page is about the shape of the loss and which triplets to train on.

2. Contrastive loss: one pair at a time

The simplest form looks at one pair (two inputs). If the pair is the same thing, shrink the distance. If it is two different things, push them apart, but not forever: only while they are closer than the margin. The margin is the slack that says "different things should be at least this far apart". A widely used form of contrastive loss is:

L = s × d² + (1 − s) × max(0, m − d)²

For a same pair (s = 1) the second term drops out, L = d², and it pulls until the distance is 0. For a different pair (s = 0) L = max(0, m − d)², which is 0 once d reaches m, so it stops pushing. For example, with m = 1 a different pair at distance 0.4 gives (1 − 0.4)² = 0.36, and at 1.2 gives 0. This loss fixes the absolute size of distances: same pairs at 0, different pairs outside m.

3. Triplet loss: anchor, positive, negative

Triplet loss looks at three inputs as one group (a triplet): the anchor (the reference), the positive (the same thing as the anchor) and the negative (a different thing). For faces, the anchor and positive are two photos of the same person and the negative is a photo of someone else. FaceNet trains on triplets like this, of matching and non-matching faces.

L = max(0, d(a, p) − d(a, n) + margin)

The form in the FaceNet paper. The paper (section 3.1) writes the same loss with squared distances, keeps every embedding at length 1 and sets the margin to 0.2. The experiment on this page uses plain distances because they are easier to read off the picture. The meaning of a semi-hard negative (farther than the positive but still inside the margin) matches section 3.2 of the paper.

If the negative is at least the margin farther away than the positive (d(a, n) ≥ d(a, p) + margin), the loss is 0. Otherwise the shortfall is the loss. Unlike contrastive loss there is no absolute rule for "how close is close"; it only asks for an order: the positive is closer than the negative by the margin.

What one training step does. When the loss is above 0, the gradients for p and n are:

∂L/∂p = (p − a) ÷ d(a, p)        ∂L/∂n = −(n − a) ÷ d(a, n)

Moving against the gradient (gradient descent) brings p closer to the anchor and takes n farther from it. The experiment's "One training step" moves each by 0.25, so the loss drops by 0.5 per step until it reaches 0. The experiment keeps the anchor fixed to make it easier to see, but in real training the anchor gets a gradient too: ∂L/∂a = −(∂L/∂p + ∂L/∂n).

To be honest. Real training does not move points directly. It changes the model's weights, and then the embedding the model produces for the same photo moves the way these arrows point (as in section 3 of the embedding models page).

4. Which triplets to use

Negatives fall into three kinds by their distance from the anchor. These are the colored regions in experiment 1.

NegativeConditionLossWhat it teaches
easy negatived(a, n) ≥ d(a, p) + margin0nothing (gradient 0)
semi-hard negatived(a, p) ≤ d(a, n) < d(a, p) + marginabove 0, at most marginthe order is right but the slack is short
hard negatived(a, n) < d(a, p)above marginthe order itself is wrong

There are a great many triplets. Experiment 2 below has only 12 points, yet 288 triplets (12 anchors × 3 other points in the same group × 8 points in other groups). And as training goes on, most of them become easy and their loss is 0. Picking triplets at random wastes most steps, so you pick the ones whose loss is above 0, that is, triplets with a hard or semi-hard negative. This is called triplet mining. FaceNet uses online triplet mining, which picks the triplets during training.

Step
Triplets with loss > 0
Mean distance within a group
Mean distance between groups

The 12 points (4 per group) are placed by a fixed-seed random generator, so they are the same every time you open the page. Each press adds up the gradients of all 288 triplets (margin 1) and moves the points, 5 times. Unlike experiment 1, the anchors move too. This is a small calculation that moves the points directly, not the result of training a real model.

Try this. (1) At first 220 of 288 triplets have a loss above 0, and the mean distance within a group (2.61) is longer than between groups (2.5). Only 2 of the 12 points have their nearest point in the same group. (2) Each press brings the triplets with a loss above 0 down to 150, 73, 26, 0. After 20 steps the mean distance within a group is 0.41 and between groups 2.77, and for all 12 points the nearest point is in the same group. (3) After that, pressing moves nothing, because every triplet has become easy.

5. How to use it: store, then measure distance

A trained model is a function that turns one input into one embedding. There are two ways to use it.

enroll   stored[name] = model(photo)               # once; the model is not retrained
search   nearest = the stored embedding closest to model(new photo)
decide   d = distance(model(new photo), stored[name])
         "same person" if d < threshold

6. Common mistakes: the margin and normalization

7. When to use what

OptionGoodBadUse when
Classification (cross-entropy)One score per class; simple to train and evaluateA new class means changing the output layer and training againThe classes are fixed and rarely change
Contrastive loss (pairs)Each pair only needs "same" or "different"Fixes absolute sizes: distance 0 for same pairs, outside the margin for different pairsYour data comes as same pairs and different pairs
Triplet lossOnly asks for an order: the positive is closer than the negative by the marginThere are very many triplets and most quickly become easy, so you need mining (section 4)Classes keep growing (people, products) and you have data grouped by what is the same

Frequently asked

When a new person joins, do I have to retrain the model?

No. Keep the model as it is, run the new person's photo through it and store the embedding that comes out. When the next photo arrives, measure the distance between its embedding and the stored one. A classification model with one output slot per class has no slot for the new person, so its output layer has to change and it has to be trained again.

Why is a triplet with a loss of 0 useless?

Where the loss is 0 its gradient is 0 too, so that triplet does not move any point. It means the negative is already at least the margin farther away than the positive, so there is nothing left to learn. In experiment 2 on this page all 288 triplets reach 0 after 20 steps, and pressing again moves nothing. That is why you pick triplets with hard or semi-hard negatives, whose loss is above 0.

What margin should I use?

No single value fits every dataset. But if the embeddings are normalized to length 1, the distance between two points lies between 0 and 2, so with a margin above 2 no triplet can ever reach a loss of 0. With a margin of 0 the loss is 0 as soon as the negative is even slightly farther away, so the gap between groups stays narrow. Measure on data not used for training and choose.

Words

Words used hereWhat books call it
learning a distancemetric learning, distance metric learning
the vector an input turns intoembedding
pull same pairs, push different pairs out to the margincontrastive loss
the reference · the same thing · a different thing, and the group of threeanchor · positive · negative, triplet
the loss measured on threetriplet loss
the slack a different thing must keepmargin
loss 0 · order right but slack short · order wrongeasy negative · semi-hard negative · hard negative
picking triplets to train ontriplet mining, online triplet mining
the distance cut-off for "same"threshold
making the length 1L2 normalization
straight-line distanceEuclidean distance

Sources

← Self-supervised learning: representations without labelsConvolution and CNNs →