Metric learning

Also known as: distance metric learning · deep metric learning

On this page 8

Metric learning is a family of machine learning methods that learn a distance function from data, so that examples considered similar end up close together and dissimilar examples end up far apart. Instead of relying on a fixed measure such as raw Euclidean distance, the model adapts the geometry of the feature space to the task, which directly improves distance-based algorithms such as k-nearest neighbors, clustering and retrieval.

The field has two main branches. Distance metric learning in the classical sense learns a linear transformation or a Mahalanobis matrix, while deep metric learning trains a neural network that maps inputs into an embedding space where a simple distance is meaningful.

How metric learning reshapes distance

Metric learning starts from supervision about similarity rather than about class labels alone. The training signal may be class labels, pairs marked as similar or dissimilar, or triplets stating that an anchor is closer to one example than to another. The model then adjusts its parameters so that the learned distance respects these constraints.

In the classical setting, the learned distance is the Mahalanobis distance, d(x, y) = sqrt((x – y)T M (x – y)), where M is a positive semidefinite matrix. Factoring M as LT L shows that this is equivalent to applying a linear map L to the features and then measuring ordinary Euclidean distance. Learning M therefore means learning which feature directions matter and how strongly to weight them.

In deep metric learning, a network f maps each input to a vector, typically of 64 to 1,024 dimensions, and often normalized to unit length. Distances are then computed with Euclidean or cosine distance between embeddings. The table below summarizes the forms of supervision.

SupervisionWhat it statesTypical lossData requirement
PairsTwo items are similar or dissimilarContrastive lossPair labels
TripletsAnchor is closer to positive than negativeTriplet lossRelative judgments
Class labelsItems of one class should clusterProxy or classification lossesStandard labeled data
Augmented viewsTwo views of one item matchInfoNCE contrastive lossUnlabeled data
Forms of supervision in metric learning

Loss functions and classical algorithms

The loss function defines what kind of geometry the model learns. Contrastive loss pulls similar pairs together and pushes dissimilar pairs apart until they exceed a margin. Triplet loss requires the anchor-positive distance to be smaller than the anchor-negative distance by a margin, often between 0.1 and 1.0 for normalized embeddings.

Classical algorithms solve related problems with convex optimization. Large Margin Nearest Neighbor (LMNN) learns a Mahalanobis matrix that keeps each point’s target neighbors close while pushing differently labeled impostors outside a margin. Neighborhood Components Analysis (NCA) maximizes the expected accuracy of a stochastic nearest neighbor classifier. Information-Theoretic Metric Learning (ITML) regularizes the learned matrix toward a prior metric.

MethodModel typeObjectiveScales to
LMNNLinear (Mahalanobis)Margin between neighbors and impostorsThousands of samples
NCALinear (Mahalanobis)Soft nearest neighbor accuracyThousands of samples
Siamese networkDeepContrastive loss on pairsMillions of samples
Triplet networkDeepRelative distance with marginMillions of samples
Proxy-based lossesDeepDistance to learned class proxiesLarge label sets
ArcFace-style lossesDeepAngular margin on a hypersphereVery large identity sets
Representative metric learning methods

Sampling and training difficulties

The number of possible pairs and triplets grows quadratically or cubically with dataset size, and most of them are already easy. Training on random triplets therefore wastes computation and stalls learning, which makes mining informative examples a central engineering concern.

Hard negative mining selects negatives that are currently closer to the anchor than the positive. It speeds learning but can collapse the embedding or amplify label noise. Semi-hard mining, which selects negatives farther than the positive but still inside the margin, is a widely used compromise. Proxy-based losses avoid mining entirely by comparing each sample with a learned representative of each class.

Other practical issues include the embedding dimension, the batch composition and the temperature parameter in contrastive losses, all of which affect results noticeably and are usually set by hyperparameter tuning.

Metric learning overlaps with several neighboring ideas but differs in its goal: it optimizes distances, not class decisions. The comparison below clarifies the boundaries.

ConceptMain goalUses labelsRelation to metric learning
ClassificationPredict a fixed classYesCannot handle unseen classes without retraining
Dimensionality reduction (PCA)Preserve varianceNoUnsupervised, ignores similarity labels
Linear discriminant analysisSeparate classes linearlyYesClosed-form special case of a learned metric
Kernel trickImplicit nonlinear featuresOptionalFixed kernel rather than learned distance
Few-shot learningLearn from few examplesYesOften built on a learned metric
How metric learning differs from neighboring concepts

A key advantage is generalization to unseen classes. A classifier trained on 1,000 identities must be retrained to recognize a new person, while a metric model only needs to embed the new example and compare distances. This property makes metric learning the foundation of few-shot learning methods such as prototypical networks.

Applications and evaluation

Metric learning powers systems that must compare items rather than label them. Typical applications include face verification, person re-identification, product image retrieval, duplicate detection, signature verification and recommendation.

Evaluation follows the retrieval setting. Recall@K measures whether a correct match appears among the top K neighbors, while mean average precision and normalized mutual information of clusters measure overall structure. A careful protocol uses disjoint classes for training and testing, because metric learning is meant to generalize beyond the training labels.

Limitations and common mistakes

Metric learning is sensitive to experimental choices, and reported gains are often smaller than they appear. Comparative studies have shown that many newer losses perform similarly to well-tuned classical baselines when backbones and training settings are held equal.

  • Unfair benchmarks: comparing methods with different backbones or embedding sizes.
  • Embedding collapse: overly aggressive hard mining maps all inputs to nearly the same point.
  • Test-class leakage: tuning hyperparameters on the test classes inflates Recall@K.
  • Ignoring feature scaling in classical methods, which distorts the learned matrix.
  • Weak similarity labels: noisy pairs teach the model the wrong notion of closeness.

A plain-language summary

Metric learning teaches a computer what “similar” means for a specific job. A plain ruler measures every difference in the same way. Metric learning builds a smarter ruler.

Imagine sorting photos of people. Lighting and background should not matter, but the face should. The model learns to ignore unimportant differences and pay attention to important ones. Photos of the same person then end up close together, and photos of different people end up far apart. This makes searching and matching much more reliable.

An example from practice

An online furniture retailer wants shoppers to upload a photo of a chair and see visually similar items from a catalog of 400,000 products. A standard classifier cannot help, because new products arrive every week and there is no fixed list of classes.

The team trains a deep metric learning model with a proxy-based loss on 1.5 million product images grouped by product identity, producing 256-dimensional normalized embeddings. Every catalog image is embedded once and stored in an approximate nearest neighbor index. At query time, the uploaded photo is embedded and the closest products are returned in under 100 milliseconds.

On a held-out set of products the model never saw during training, Recall@10 rises from about 55 percent with generic pretrained features to about 80 percent with the learned metric. New products become searchable as soon as their images are embedded, with no retraining required.