Friday, December 4, 2026
HomeData ScienceMetric Learning and Few-Shot Learning – Siamese Networks, Triplet Loss, ArcFace and...

Metric Learning and Few-Shot Learning – Siamese Networks, Triplet Loss, ArcFace and Prototypical Networks

Table of Content

📋 KEY INSIGHTS

  • Metric learning trains an embedding function that maps inputs to a space where semantically similar examples are close and dissimilar examples are far apart — enabling classification without retraining when new classes appear.
  • The triplet loss trains on (anchor, positive, negative) triples: push the anchor closer to the positive (same class) than to the negative (different class) by at least a margin α.
  • ArcFace (and CosFace) replaces the standard softmax with an angular margin penalty, achieving state-of-the-art face recognition by maximising the angular separation between class centres in the embedding space.
  • Prototypical Networks compute a class prototype (mean embedding of support examples) and classify queries by nearest prototype — a simple, effective few-shot learner that generalises well across domains.
  • Hard negative mining is critical for triplet loss training: easy negatives (very dissimilar pairs) provide no gradient; only semi-hard negatives (closer than the margin but farther than the positive) drive learning.
  • Universal Sentence Encoder and sentence-transformers (SBERT) are metric learning applied to text: trained with contrastive or cosine similarity losses to produce semantically meaningful sentence embeddings for retrieval and clustering.

Standard classification trains a softmax head over a fixed set of classes — useless when new classes appear after training (a face recognition system cannot recognise a new employee without retraining; a product search engine cannot handle a new SKU). Metric learning solves this by learning an embedding space where the geometric structure reflects semantic similarity: given a good embedding, you can classify new examples by finding their nearest neighbours in the embedding space, without any model update. This enables few-shot learning, open-set recognition, and scalable retrieval over millions of items.

This guide covers the full metric learning landscape: contrastive loss and the original siamese networks, triplet loss and hard negative mining, angular margin losses (ArcFace, CosFace, SphereFace), Prototypical Networks and few-shot learning, and metric learning applications in face recognition, product search, and sentence embeddings.

Siamese Networks, Triplet Loss and Angular Margin Losses

Siamese networks (Bromley et al., 1993; LeCun group) apply the same weight-shared network to two inputs and compare their embeddings. The original application was signature verification: given two handwritten signatures, are they from the same person? The contrastive loss L = (1-y) × (1/2) × D^2 + y × (1/2) × max(0, m – D)^2, where y=0 for similar pairs and y=1 for dissimilar pairs and D is the Euclidean distance between embeddings, pulls similar pairs together and pushes dissimilar pairs beyond margin m. The key challenge with contrastive loss is pair sampling: with N training examples there are O(N^2) pairs, and most similar pairs are already embedded close together (easy positives) while most dissimilar pairs are already far apart (easy negatives) — providing no gradient signal. This is why triplet loss supplanted contrastive loss in most applications.

Triplet loss (Schroff et al., FaceNet, 2015) operates on (anchor a, positive p, negative n) triples: L = max(0, D(a,p) – D(a,n) + α). The loss is zero when the anchor is closer to the positive than to the negative by at least margin α, and positive otherwise. Hard negative mining selects negatives that violate or barely satisfy the margin: online semi-hard mining (sample negatives that are farther than the positive but within the margin) provides the most useful gradient signal. With hard mining and large-scale training data, FaceNet achieves 99.63% accuracy on the LFW (Labelled Faces in the Wild) benchmark using a 128-dimensional embedding. The triplet loss requires careful implementation — without mining, 99%+ of triples are easy and training stalls. The evaluation metric for metric learning is typically Recall@K (what fraction of queries have at least one true positive in the top-K retrieved results) or mean Average Precision (mAP) over a retrieval test set, computed using approximate nearest neighbour search over the full embedding database (see our vector databases guide for FAISS and HNSW implementation).

ArcFace (Deng et al., CVPR 2019) is currently the dominant face recognition loss. It modifies the standard softmax classifier by normalising both the embedding vector and the class weight vectors to unit length (constraining the problem to the hypersphere), then adding an additive angular margin m to the angle between the embedding and its true class centre before the softmax: L = -log(e^{s cos(θ_yi + m)} / (e^{s cos(θ_yi + m)} + Σ_{j≠yi} e^{s cos θ_j})). The margin m=0.5 (28.6°) forces each class’s embeddings to cluster more tightly around their class centre and farther from other class centres in angular space, dramatically improving inter-class separability. ArcFace achieves 99.82% on LFW and 98.36% on the challenging IJB-C benchmark, outperforming triplet loss-based methods with far simpler training (no pair/triplet sampling required — standard mini-batch training works). The angular margin is geometrically intuitive: in high-dimensional spaces, cosine similarity is more stable than Euclidean distance for normalised vectors, and the angular margin directly maximises the angular separation between class cones on the hypersphere.

MethodLoss TypeSamplingKey Strength
Contrastive (Siamese)PairwiseO(N^2) pairsSimple; original formulation
Triplet (FaceNet)TripletSemi-hard miningFlexible margin; widely used
ArcFaceClassification + angular marginStandard mini-batchSOTA face recognition; simple training
Prototypical NetworksSoftmax over distancesEpisode-based (N-way K-shot)Few-shot; interpretable prototypes
SBERT / SimCSEContrastive (cosine)In-batch negativesSentence embeddings; retrieval

Prototypical Networks, Few-Shot Learning and Text Metric Learning

a group of water drops
Photo by GuerrillaBuzz on Unsplash

Prototypical Networks (Snell et al., NeurIPS 2017) are the simplest and most effective few-shot learning algorithm. In an N-way K-shot episode: N classes are sampled, each with K support examples and several query examples. The class prototype c_k is the mean embedding of the K support examples for class k. Queries are classified by softmax over negative distances to prototypes: p(y=k|x) ∝ exp(-D(f(x), c_k)). Training samples many such episodes so the embedding network f learns to produce embeddings where the prototype structure generalises to new classes. Prototypical Networks outperform more complex meta-learners (MAML, Matching Networks) on most benchmarks with far less computational overhead — the prototype mean is a sufficient statistic for the class when the embedding space is well-structured. The connection to centroid-based clustering is direct: Prototypical Networks are essentially k-means in embedding space, applied episodically — the class prototypes are the cluster centroids, and query classification is nearest-centroid assignment.

Few-shot learning benchmarks (miniImageNet, tieredImageNet, Meta-Dataset) evaluate 5-way 1-shot and 5-way 5-shot accuracy. Modern methods combine Prototypical Networks with pre-training on large datasets: a ViT pre-trained on ImageNet-21k provides embeddings that are already so well-structured that simple nearest-neighbour or prototype classification achieves competitive few-shot accuracy without any meta-learning fine-tuning. This suggests that the meta-learning component of few-shot learning is less important than the quality of the representations — the same conclusion that drives foundation model research, where large-scale pre-training produces representations that transfer across tasks with minimal task-specific data.

Metric learning applied to text produces sentence embeddings that capture semantic similarity: sentences with similar meaning should be close in embedding space, regardless of surface form (“The cat sat on the mat” and “A feline rested on the rug” should be nearby). SBERT (Sentence-BERT, Reimers and Gurevych, 2019) fine-tunes BERT with a siamese architecture on natural language inference pairs using a cosine similarity loss: sentence pairs labelled as “entailment” are positive pairs, “contradiction” pairs are negatives. SimCSE (Gao et al., 2021) achieves better results with a simpler approach: pass the same sentence through the model twice with different dropout masks to create positive pairs (the two noisy versions of the same sentence should be similar) and use all other sentences in the batch as negatives. The resulting sentence embeddings power semantic search in vector databases, clustering of support tickets and customer feedback, and duplicate question detection — anywhere that semantic similarity between texts needs to be computed at scale without keyword matching.

Product search and recommendation at scale is one of the highest-impact metric learning applications. Amazon, Alibaba, and Pinterest train two-tower embedding models: a query tower maps search queries to an embedding, and an item tower maps product images and text to an embedding. The model is trained with in-batch softmax — treating all other items in a mini-batch as negatives — and evaluated by Recall@100 on a held-out query set. The trained embeddings are indexed with approximate nearest neighbour search (FAISS, HNSW), enabling retrieval from catalogues of hundreds of millions of items in under 10 milliseconds. The two-tower architecture connects to our deep learning recommendation systems guide, where the same dual-encoder structure is used for retrieval in neural collaborative filtering — the core difference being that metric learning explicitly optimises the embedding space geometry with a contrastive objective, while collaborative filtering optimises rating prediction accuracy.

✦ SUMMARIZE THIS ARTICLE WITH AI

Leave feedback about this

  • Rating

Durgesh Kekare
Durgesh Kekarehttps://www.dataexpertise.in
Durgesh Kekare is a data science educator and founder of DataExpertise.in. With expertise in Python, machine learning, and analytics, he helps 10,000+ learners break into data careers.

Latest Posts

List of Categories