- Introduced by
- Xing, E. P.; Jordan, M. I.; Russell, S.; Ng, A. Y.
- Year
- 2003 (foundational); refined 2009 (LMNN)
- Type
- Representation learning / supervised distance optimization
- Family
- Machine learning
What does it do?
Metric learning trains a distance or similarity function from labelled or pairwise-annotated data, so that examples treated as similar lie close together in the learned space and dissimilar examples lie further apart.
Unlike a fixed distance such as Euclidean, the learned metric is shaped by the task's own notion of similarity, which can improve nearest-neighbour classification, clustering, and retrieval that operate in the learned space.
The intuition behind the method
Standard distances such as Euclidean treat all feature dimensions equally, but in many problems some features are far more informative than others, and the relevant dimensions can differ between classes. Metric learning adjusts the geometry of the feature space using information about which pairs of examples should be close and which should be far apart. A simple nearest-neighbour classifier or clustering algorithm run on the adjusted space can then group examples more appropriately, because the space encodes what 'similar' means for the specific task. The quality of the result depends on how well the supervision captures that notion of similarity.
History
Xing et al. (2003) formulated distance metric learning as a convex optimisation problem with pairwise constraints. Weinberger and Saul (2009) introduced large margin nearest neighbour (LMNN) for k-NN classification. Deep metric learning later extended these ideas to neural-network embeddings, and it is now widely used in few-shot learning and visual representation research.
When to use it
Choose metric learning when the downstream task is inherently similarity-based, for example few-shot classification, face verification, medical image retrieval, speaker identification, or product recommendation, and when a fixed Euclidean distance performs poorly because features differ in relevance. It is well suited to moderate-to-large labelled datasets and high-dimensional inputs such as images or text embeddings, and to open-set or retrieval settings where test classes may not appear in training. Avoid it when there are very few labelled examples per class, so that too few pairs or triplets exist to fit the metric. It is also not the best choice when the goal is simple tabular classification or regression that logistic regression or gradient boosting serves well, or when the model must be read in terms of explicit feature coefficients.
Limitations and considerations
- Triplet and contrastive losses depend on pair or triplet mining; random sampling yields mostly easy, uninformative pairs and can slow training considerably.
- Linear Mahalanobis methods have a matrix M of size d by d, so the number of parameters grows quadratically with feature dimensionality, which becomes prohibitive in very high dimensions without dimensionality reduction.
- Requires labelled or pairwise-constraint data; in fully unsupervised settings, what can be learned depends on additional assumptions that the method does not supply.
- Evaluation is indirect: metric quality has to be judged through a downstream task rather than a single training loss value.
Source conditions do not replace independent scientific review or validation by an analysis engine.
Strengths
- Adapts the geometry of the feature space to the specific task, which can improve nearest-neighbour and clustering accuracy compared with a fixed distance.
- Supports few-shot recognition: once a metric has been learned, new classes can be classified from a handful of examples without retraining the whole model.
- Can transfer across domains: a metric learned on one dataset may be fine-tuned for a related task with comparatively little additional data.
- Model-agnostic: the learned embedding can feed downstream algorithms such as k-NN, SVM, or k-means without retraining those components.
- Contrastive and triplet formulations can be scaled to large datasets through mini-batch sampling.
Applications
- Face verification and recognition: learning whether two face images show the same person.
- Few-shot image classification: classifying new visual categories from one or a few examples.
- Medical image retrieval: finding similar scan regions or histopathology patches in large databases.
- Speaker and voice verification in biometric authentication systems.
- Product recommendation and visual search in e-commerce.
How it works
How it works
From labelled or pairwise-annotated data, positive pairs (same class or explicitly similar) and negative pairs (different class or explicitly dissimilar) are defined. These constraints encode what 'close' and 'far' mean for the task and form the supervision signal for training the metric.
A parametric distance function is chosen. The most common choice is a Mahalanobis distance governed by a positive semi-definite matrix M, which generalises axis-aligned scaling to full cross-feature reweighting. Another option is a neural-network embedding followed by Euclidean or cosine distance.
Formula
d_M(x_i,x_j)=\sqrt{(x_i-x_j)^\top M (x_i-x_j)},\; M \succeq 0An objective is formulated to bring positive pairs together and push negative pairs apart, respecting a margin or soft constraint. Common objectives include the contrastive loss, the triplet loss (the anchor-positive distance should be smaller than the anchor-negative distance by a margin), and the large-margin nearest-neighbour (LMNN) hinge loss.
The metric parameters (M or the neural-network weights) are optimised by gradient descent or semi-definite programming. For triplet-based objectives, mini-batch sampling strategies such as hard negative mining matter: random sampling tends to produce triplets that already satisfy the margin, which gives little gradient and slows convergence.
At inference, the learned metric or embedding is applied to new data. Downstream tasks such as nearest-neighbour classification, k-means clustering, image retrieval, or recommendation operate in the learned space, where distances are intended to reflect the similarity encoded by the training constraints.
Common pitfalls
- Using random triplet sampling instead of hard or semi-hard negative mining, which can leave most triplets with near-zero loss and stall training.
- Applying hard negative mining too aggressively: the hardest negatives are sometimes mislabelled or near-duplicate examples, which can destabilise training and fit label noise. Semi-hard negatives, or a warm-up phase with random sampling, are common mitigations.
- Evaluating the metric only on the training classes; performance on unseen classes, which is often the actual generalisation target, may be much lower.
- Comparing embeddings with Euclidean distance without deciding whether to L2-normalise them first, so that embedding norms rather than directions drive the result. Cosine similarity is already insensitive to scale, so normalisation matters mainly when Euclidean distance is used.
- Treating the learned embedding as interpretable in terms of the original features without additional analysis, such as linear probing or SHAP.
- Applying a learned metric to a shifted data distribution without re-validation or fine-tuning.
Frequently asked questions
What is the difference between metric learning and contrastive learning?
Contrastive learning is a family of metric learning objectives, such as the contrastive loss, that pull positive pairs together and push negative pairs apart. Metric learning is the broader framework, which also includes Mahalanobis methods, triplet losses, and proxy-based objectives.
How many examples per class do I need?
The requirement depends on the method. Linear Mahalanobis methods are lower-capacity models than deep embeddings and can be fitted with fewer examples per class, although their number of parameters grows with the square of the feature dimension. Deep metric learning generally needs many examples per class to learn useful embeddings. Pre-trained backbones can reduce this requirement substantially. Very few labelled examples per class is a case where metric learning should not be used (see When to use). No universal threshold applies, so set the number by validating on held-out classes with your own data.
Is metric learning the same as dimensionality reduction?
Not exactly. Methods such as PCA or UMAP reduce dimensions without direct supervision. Metric learning uses class or pairwise supervision to shape the geometry, so the resulting space is task-discriminative rather than merely compact.
Can metric learning handle imbalanced classes?
It can, but pair and triplet sampling should be stratified or class-balanced so that the dominant class does not fill most of each batch. The choice of objective under class imbalance should be validated on your own data.
When should I use metric learning instead of a standard classifier?
Prefer metric learning when you need to generalise to classes unseen at training time (open-set recognition, few-shot learning), or when the task is retrieval rather than prediction over a fixed set of classes.
Related methods
Sources
Xing, E. P., Jordan, M. I., Russell, S., & Ng, A. Y. (2003). Distance metric learning with application to clustering with side-information. In Advances in Neural Information Processing Systems (NIPS), 16, 505–512.
Open publication referenceWeinberger, K. Q., & Saul, L. K. (2009). Distance metric learning for large margin nearest neighbor classification. Journal of Machine Learning Research, 10, 207–244.
Open publication reference