Explain contrastive and triplet loss — how do they train embedding spaces?
Written by the mlprep team · Updated
What is contrastive loss and triplet loss? When would you use metric learning approaches over cross-entropy classification?
The motivation: open-set recognition#
Cross-entropy trains a model to map inputs to a fixed set of classes. But what if at inference time you encounter classes not seen during training — new users in a face recognition system, new products to rank?
Metric learning instead trains the embedding space itself. The goal: embeddings of similar items are close, embeddings of dissimilar items are far. Then similarity search at inference time works without retraining.
Contrastive loss (Siamese networks)#
Given a pair of inputs (x₁, x₂) and a label y=1 (similar) or y=0 (dissimilar):
L = y · d² + (1-y) · max(0, m - d)²
where d = ||f(x₁) - f(x₂)||₂ and m is a margin.
- For similar pairs (y=1): minimize d² — pull them together.
- For dissimilar pairs (y=0): push d past margin m. If already d > m, zero loss — no gradient wasted on pairs that are already separated enough.
Triplet loss#
Given an anchor a, positive p (same class), and negative n (different class):
L = max(0, d(a,p) - d(a,n) + m)
Force d(a,p) + m < d(a,n): the positive must be closer than the negative by at least margin m.
Triplet loss considers relative distances, which is more meaningful than contrastive loss's absolute distance threshold. If the model correctly orders the triple (positive closer than negative by margin), loss is zero.
The hard negative mining problem#
With random sampling, most triplets quickly become "easy" — satisfied with large margin — and contribute zero gradient. Training stalls.
Solutions:
- Hard negative mining: find the hardest negatives (most similar to anchor but different class). Too hard = noisy gradients (semi-hard mining is better).
- Semi-hard mining: negatives that are farther than the positive but within the margin — providing signal without being trivial.
- Online mining: mine hard examples within each batch rather than across the whole dataset.
InfoNCE / NT-Xent (modern contrastive learning)#
Used in SimCLR, CLIP, and most modern self-supervised methods:
L = -log[exp(sim(z_i, z_j)/τ) / ∑_k exp(sim(z_i, z_k)/τ)]
This is cross-entropy where the "positive" is the augmented view and "negatives" are all other samples in the batch. Temperature τ controls how peaked the distribution is. Large batches = more negatives = better learning signal. This avoids explicit pair/triplet mining by treating the whole batch as negatives.
When to use metric learning vs classification#
Use metric learning when:
- New classes appear at inference (few-shot, face ID, product search)
- You want similarity search in embedding space
- Classes are very numerous (millions of products)
- You need calibrated distance semantics
Use classification when:
- Fixed, known class set
- You have abundant labeled data
- You don't need the embedding geometry
The key takeaway unlocks after you reveal an expert answer.
Key Takeaway
Contrastive loss: pull similar pairs together, push dissimilar pairs past a margin. Triplet loss: anchor must be closer to positive than negative by margin m — trains relative distance. Both suffer from easy-pair collapse; hard/semi-hard mining is essential. Modern self-supervised methods (SimCLR, CLIP) use InfoNCE which treats entire batch as negatives, avoiding explicit mining. Use metric learning when classes are open-set or you need embedding geometry; use cross-entropy for fixed class sets.
Follow-up Questions to Test Yourself
Interviewers often pivot here once you cover the core concept.
- What is the role of the temperature τ in InfoNCE/NT-Xent and how does it affect what the model learns?
- How does CLIP's training objective differ from standard supervised contrastive learning?
- If you had to build a product image similarity system at scale, would you use triplet loss or something else? Walk me through your design.
How confident do you feel explaining this?
Track your understanding or flag it to revisit before your next loop.
Related Questions
What is focal loss and when would you use it over cross-entropy?
Compare pointwise, pairwise, and listwise ranking losses
Explain cross-entropy loss — binary vs categorical, and why it works for classification
How would you design a RAG system that answers questions over a company's internal documents?