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.
- 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.
- 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.
- 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)²
L: the loss of one pair. Smaller is better.d: the distance between the embeddings of the two inputs in the pair.s: 1 if the pair is the same thing, 0 if it is two different things.m: the margin.max(0, x): 0 if x is below 0, otherwise x.
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)
a,p,n: the embeddings of the anchor, positive and negative.d(x, y): the distance between two embeddings. The experiments on this page use straight-line (Euclidean) distance.margin: the slack: the negative must be at least this much farther away than the positive.max(0, x): 0 if negative.
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)
∂L/∂p: how much and which way L changes when p moves a little (the gradient).(p − a) ÷ d(a, p)is the length-1 vector from the anchor toward p.∂L/∂n: the gradient for n: the opposite of the length-1 vector from the anchor toward n.- When the loss is 0, both gradients are 0.
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.
| Negative | Condition | Loss | What it teaches |
|---|---|---|---|
| easy negative | d(a, n) ≥ d(a, p) + margin | 0 | nothing (gradient 0) |
| semi-hard negative | d(a, p) ≤ d(a, n) < d(a, p) + margin | above 0, at most margin | the order is right but the slack is short |
| hard negative | d(a, n) < d(a, p) | above margin | the 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
- Find the nearest. Store the embeddings of what you know, and find the one closest to the new input's embedding (k-nearest neighbors). When there are many stored, finding it quickly is vector search. Finding similar products from a product photo works this way.
- Decide with a threshold. If the distance between two embeddings is shorter than the threshold, treat them as "the same person". Face verification works this way. Lowering the threshold makes fewer mistakes of letting someone else in and more mistakes of turning the right person away. Choose the threshold by measuring on pairs not used for training.
6. Common mistakes: the margin and normalization
- Margin too small. With a margin of 0 the loss is 0 as soon as the negative is even slightly farther than the positive (lower the margin to 0 in experiment 1 and the yellow band disappears). The gap between the same group and other groups stays narrow, and a single threshold has a hard time telling them apart.
- Margin too large. The loss rarely reaches 0, so almost every triplet keeps pushing. If the embeddings have length 1, the distance between two points lies between 0 and 2, so with a margin above 2, d(a, p) − d(a, n) + margin is always above 0 and no triplet can ever reach a loss of 0.
- Why normalize the embeddings. Without a length limit, a triplet whose order is already right (d(a, p) < d(a, n)) can reach a loss of 0 just by scaling every embedding up by the same factor, which widens the gap between the two distances. The model could lower the loss by growing the size instead of fixing the order. Fixing every embedding to length 1 (L2 normalization) closes that path, and the margin always means the same thing. Also, between length-1 vectors d² = 2 − 2 × cos, so ranking by straight-line distance and ranking by cosine similarity give the same order (dot product and cosine).
7. When to use what
| Option | Good | Bad | Use when |
|---|---|---|---|
| Classification (cross-entropy) | One score per class; simple to train and evaluate | A new class means changing the output layer and training again | The 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 pairs | Your data comes as same pairs and different pairs |
| Triplet loss | Only asks for an order: the positive is closer than the negative by the margin | There 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 here | What books call it |
|---|---|
| learning a distance | metric learning, distance metric learning |
| the vector an input turns into | embedding |
| pull same pairs, push different pairs out to the margin | contrastive loss |
| the reference · the same thing · a different thing, and the group of three | anchor · positive · negative, triplet |
| the loss measured on three | triplet loss |
| the slack a different thing must keep | margin |
| loss 0 · order right but slack short · order wrong | easy negative · semi-hard negative · hard negative |
| picking triplets to train on | triplet mining, online triplet mining |
| the distance cut-off for "same" | threshold |
| making the length 1 | L2 normalization |
| straight-line distance | Euclidean distance |
Sources
- Schroff, Kalenichenko, Philbin, FaceNet: A Unified Embedding for Face Recognition and Clustering, 2015 (a compact space where distances correspond to face similarity, optimizing the embedding directly rather than a bottleneck layer, training on triplets of matching and non-matching faces, online triplet mining, 128 bytes per face, LFW 99.63% and YouTube Faces DB 95.12%).
← Self-supervised learning: representations without labelsConvolution and CNNs →