The contrastive (pairwise) loss trains an embedding so that similar pairs end up close and dissimilar pairs at least a margin m apart: d² for similar pairs and max(0, m − d)² for dissimilar ones. It is the loss of Siamese networks for verification (is this the same person, place or part?) and the starting point of metric learning. This page covers the loss, its gradient, pair sampling, the role of the margin, and how it relates to triplet and InfoNCE losses. In the exercises you implement it and show that scaling the margin only rescales the embedding, then learn an embedding that lifts nearest-neighbour accuracy from 0.26 to about 0.9 on data dominated by nuisance dimensions, finding that balanced pair sampling did no better than random sampling.
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.
Learning what “similar” means
Sometimes the goal is not to name a class but to compare two things: are these two images of the same runway, these two sensor signatures from the same engine, these two faces the same person? A network maps each input to a point (an embedding), and the contrastive loss shapes that map using labelled pairs. It pulls points from a matching pair together and pushes points from a non-matching pair apart until they are at least a margin m away. Afterwards, distance in the embedding means dissimilarity.
1-nearest-neighbour test accuracy: in the embedding 0.950 · in the raw input space 0.940
The two rings and the two blobs are classes; rings are not linearly separable in the input. Contrastive loss pulls same-class pairs to distance 0 and pushes different-class pairs beyond the margin m. Triplet loss only asks each anchor to be closer to a positive than to a negative by m. InfoNCE normalises embeddings onto a circle and asks each anchor to pick its positive out of the batch; lower τ sharpens that choice. With 0 training steps you see the random initial embedding.
Why engineers care
Verification and retrieval show up across robotics and aerospace: place recognition for loop closure in SLAM, matching a part to a catalogue, re-identifying a vehicle across cameras, and comparing a telemetry window with known fault signatures. These tasks have many classes, often unseen during training, so a learned distance generalises where a fixed classifier cannot.
📝 Quick check (Level 0)
0/3 answered
1. The contrastive loss trains…
2. Dissimilar pairs are pushed apart until…
3. A Siamese network…
Level 1: Beginner
★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.
By hand
Loss for a pair at distance d with label s (1 = similar): L = s·d² + (1 − s)·max(0, m − d)². Hadsell et al. include a factor ½.
Examples with m = 1:
a similar pair at d = 1 costs 1;
a dissimilar pair at d = 0.5 costs 0.25;
a dissimilar pair at d = 5 costs 0.
Gradients with respect to the first embedding, with Δ = e₁ − e₂:
similar pairs: 2Δ, pulling the two together;
dissimilar pairs inside the margin: −2(m − d)Δ/d, pushing them apart;
dissimilar pairs beyond the margin: 0.
Distances: Euclidean d = ‖e₁ − e₂‖, or cosine distance 1 − cos θ on normalised embeddings.
Scale: without normalisation, multiplying the embedding and the margin by c multiplies the loss by c², so the margin only sets the scale.
📝 Quick check (Level 1)
0/3 answered
1. A dissimilar pair at distance 2 with margin 1 costs…
2. A similar pair at distance 0.5 costs…
3. Without normalisation, the margin mainly sets…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 25 minUndergraduate students and practising engineers.
Pairs in code
Exercise 1.
The pairwise distance matrix, the contrastive loss and its gradient are checked by finite differences.
Scaling both the embedding and the margin by 4 scales the loss by 16, so for an unnormalised embedding the margin’s value is arbitrary.
Sampling pairs.
With K balanced classes, random pairs are similar only about 1/K of the time. Many implementations sample balanced pairs.
Batch-all: use every pair in a batch, which is cheap with a distance matrix.
Hard-negative mining: use the closest dissimilar examples. It speeds learning but can collapse the embedding if used from the start.
Normalise embeddings, or add weight decay, if the scale drifts.
d = F.pairwise_distance(e1, e2); loss = (s * d**2 + (1 - s) * F.relu(m - d)**2).mean()
🐍 Exercise 1: the contrastive loss
Implement pairwise distances, the contrastive loss and its gradient, and a batch-all version; check how the loss scales with the margin.
📝 Quick check (Level 2)
0/3 answered
1. With 10 balanced classes, random pairs are similar about…
2. Hard-negative mining from the start can…
3. Batch-all uses…
Level 3: Advanced
★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.
Theory
Energy view. LeCun’s energy-based framework treats d as an energy: low for compatible pairs, high for incompatible ones. Pulling positives together alone would collapse every embedding to one point, at zero energy. The negative term, a hinge on the energy, prevents that collapse. The margin limits how much effort goes into negatives that are already far apart.
Relation to other losses.
Triplet loss (E2-11) uses relative constraints, d(a, p) + m < d(a, n), which do not force positives to distance 0.
InfoNCE (E2-12) uses many negatives at once with a softmax.
Both were developed because absolute contrastive constraints can be too rigid, for example when classes have very different spreads.
What it learns. For a linear embedding, the contrastive loss learns a projection like linear discriminant analysis: it amplifies directions that separate classes and shrinks directions that only vary within classes (the nuisance directions). This is a learned Mahalanobis distance. Nonlinear embeddings can unfold manifolds, as in the demo’s rings.
📝 Quick check (Level 3)
0/3 answered
1. Without the negative term, the contrastive loss would…
2. A linear contrastive embedding defines…
3. Triplet loss differs by using…
Level 4: Expert
★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.
Margin and sampling
History.
J. Bromley et al. (1993) introduced Siamese networks for signature verification.
S. Chopra, R. Hadsell and Y. LeCun (2005) used a contrastive energy loss for face verification.
R. Hadsell, S. Chopra and Y. LeCun (2006) gave the margin form used today (DrLIM).
Later work moved to triplet (2015) and InfoNCE-style (2018–2020) objectives.
Exercise 2. Ten classes whose means differ in 5 informative dimensions, plus 15 nuisance dimensions with standard deviation 3. Raw nearest-neighbour accuracy is only 0.262. A linear 4-D embedding is trained with the contrastive loss for 1000 steps of 64 pairs, with margin 0.5 or 2, and with random pairs (about 10% similar) or balanced pairs (50% similar).
margin
pair sampling
1-NN test accuracy per seed
mean distance between class centres
within / between ratio
0.5
random
0.952, 0.922, 0.884
0.73
0.244
0.5
balanced
0.908, 0.912, 0.886
0.48
0.226
2.0
random
0.958, 0.928, 0.882
2.94
0.238
2.0
balanced
0.908, 0.910, 0.882
1.92
0.225
The learned metric removed the nuisance. Nearest-neighbour accuracy rose from 0.26 to 0.88–0.96.
The margin only set the scale. A fourfold larger margin made the embedding almost exactly four times larger (0.73 → 2.94 and 0.48 → 1.92), with the same scale-free separation ratio and the same accuracy, as Exercise 1 predicts.
Balanced sampling did not help. Its accuracy was within noise of random sampling, here and in three further seeds, and its embeddings were more compact. With a linear model and plentiful negatives, the natural pair mix was fine.
🐍 Exercise 2 (research): margin and sampling
Learn a linear embedding with the contrastive loss using margins 0.5 and 2 and random or balanced pair sampling; compare nearest-neighbour accuracy, embedding scale and scale-free class separation.
Contrastive learning in AI, robotics and aerospace
Place recognition: Siamese and contrastive embeddings match current camera views to a map for loop closure and relocalisation.
Verification: “same part, same vehicle, same signature?” tasks use pairwise losses because new identities appear after deployment.
Health monitoring: embeddings of telemetry windows place similar operating states together, so new faults show up as points far from all known states.
References
J. Bromley, I. Guyon, Y. LeCun, E. Säckinger, R. Shah (1993). “Signature verification using a Siamese time delay neural network.” Advances in NeurIPS 6.
S. Chopra, R. Hadsell, Y. LeCun (2005). “Learning a similarity metric discriminatively, with application to face verification.” Proc. CVPR.
R. Hadsell, S. Chopra, Y. LeCun (2006). “Dimensionality reduction by learning an invariant mapping.” Proc. CVPR.
K. Musgrave, S. Belongie, S.-N. Lim (2020). “A metric learning reality check.” Proc. ECCV.
In exercise 2, balanced pair sampling gave no gain over random sampling.
Practice
Show:
Level 0
Problem 1Level 0
Contrastive loss (m = 1) for a similar pair at distance 1?
1.
Problem 2Level 0
Contrastive loss (m = 1) for a dissimilar pair at distance 0.5?
(1 − 0.5)² = 0.25.
Problem 3Level 0
Contrastive loss (m = 1) for a dissimilar pair at distance 5?
0.
Level 1
Problem 4Level 1
Distance between embeddings (0, 0) and (3, 4)?
5.
Problem 5Level 1
Factor by which the loss changes when embedding and margin are both multiplied by 4?
4² = 16.
Problem 6Level 1
Expected share of similar pairs when sampling randomly from 10 balanced classes?
0.1.
Problem 7Level 1
Cosine similarity between (1, 0) and (0, 1)?
0.
Level 2
Problem 8Level 2
First component of ∂L/∂e₁ for a dissimilar pair e₁ = (0, 0), e₂ = (0.5, 0), m = 1 (no averaging)?
Δ = e₁ − e₂ = (−0.5, 0) and d = 0.5, so −2(m − d)Δ/d has first component −2 × 0.5 × (−0.5)/0.5 = 0.5. Gradient descent moves e₁ in the −0.5 direction, away from e₂.
Problem 9Level 2
Raw 1-NN accuracy in exercise 2?
0.262.
Problem 10Level 2
Best 1-NN accuracy (margin 2, random pairs, first seed)?
0.958.
Problem 11Level 2
Mean distance between class centres for margin 2, random pairs?
2.94.
Problem 12Level 2
The same quantity for margin 0.5?
0.73.
Problem 13Level 2
Within/between ratio for margin 0.5, balanced pairs?
0.226.
Level 3
Problem 14Level 3
Prove that scaling the embedding and margin together scales the contrastive loss by c².
Replace e by ce and m by cm (c > 0). Distances become cd. Similar pairs: (cd)² = c²d². Dissimilar pairs: max(0, cm − cd)² = c²max(0, m − d)². Every term is multiplied by c², so the loss is too, and its minimisers correspond one-to-one by scaling. ∎
Problem 15Level 3
Explain why the contrastive loss needs its negative term.
With only the similar-pair term Σd², the loss is zero, its minimum, when every embedding is the same point, for example W = 0 for a linear map. That embedding carries no information. The negative term charges for dissimilar pairs closer than m, so collapse costs about m² per negative pair, and the optimum must separate classes while keeping each class compact. ∎
Problem 16Level 3
Explain how a linear contrastive embedding raised accuracy from 0.26 to about 0.9.
In the raw space, nearest neighbours are dominated by the 15 nuisance dimensions with variance 9, which carry no class information. The contrastive loss pulls same-class pairs together, so it shrinks the projection of the nuisance directions (they create within-class distance). It pushes different-class pairs apart, so it keeps and enlarges the informative directions. The learned W is a Mahalanobis metric that effectively discards the nuisance, and nearest neighbours in the 4-D embedding mostly share a class. ∎
Problem 17Level 3
Design training for a place-recognition embedding for drone loop closure.
Build pairs from flight logs: images taken within a few metres of each other (by GPS or SLAM pose) are similar, and images more than, say, 50 m apart are dissimilar; ambiguous distances are left out. Use a shared CNN and normalised embeddings, with a contrastive or triplet loss, and mine hard negatives (look-alike places) only after a warm-up period. Evaluate recall@k for retrieving the correct place on flights from other days, seasons and altitudes. Exercise 2 suggests trying random pairs before elaborate balancing. ∎
Level 4
Problem 18Level 4
1-NN accuracy for margin 0.5, random pairs, third seed?
0.884.
Problem 19Level 4
Mean distance between class centres for margin 2, balanced pairs?
1.92.
Problem 20Level 4
1-NN accuracy for margin 0.5, balanced pairs, second seed?
0.912.
Coding practice
🐍 Code 1 (Level 0): pairwise distances
Euclidean distance matrix.
🐍 Code 2 (Level 0): contrastive loss
d² or max(0, m − d)².
🐍 Code 3 (Level 0): same-class mask
Label equality without the diagonal.
🐍 Code 4 (Level 1): hardest negative
Closest example of another class.
🐍 Code 5 (Level 0): cosine similarity
a·b/(‖a‖‖b‖).
Topic test
A timed test drawn at random from this topic's question bank. Each attempt gets new questions. For a longer test across the whole chapter, see the chapter test, or mix topics in the question bag.
Contrastive loss: topic test
10 questions, drawn at random from a bank of 21. Every attempt is different.
⏱ Time limit: 15 minutes. The test submits itself when time runs out.
Levels covered: 0, 1, 2, 3, 4. No hints or solutions until you submit.