AI Wiki中文/EN

Metric learning

度量学习

Learn a PSD distance geometry, test its gradients, and distinguish retrieval success from optimality.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Start with the problem

A nearest-neighbor classifier is only as sensible as its notion of “near.” If a nuisance coordinate varies by eight units while a useful coordinate varies by two, ordinary Euclidean distance can consistently pick the wrong class. Metric learning uses supervised similarities to change that geometry.

A Mahalanobis model learns a positive-semidefinite matrix. Large Margin Nearest Neighbor, or LMNN, chooses same-label target neighbors in advance, pulls those neighbors closer, and penalizes differently labeled points that intrude on their margin. Target neighbors remain fixed during the original optimization; they are not every same-class example. Distance Metric Learning for Large Margin Nearest Neighbor Classification

Our four-point table makes the geometry visible. Its vertical coordinate is a distraction for class identity. The learned matrix suppresses that coordinate and keeps horizontal separation. We will also check whether an apparently successful training run actually minimizes its objective.

Definitions and derivation

For a difference vector δ=xi−xj\delta=x_i-x_j, learn a symmetric matrix M⪰0M\succeq0. If M=L⊤LM=L^\top L, the quadratic form is ordinary squared distance after a linear map:

dM(i,j)=δ⊤Mδ=∥Lδ∥22,M⪰0.d_M(i,j)=\delta^\top M\delta=\|L\delta\|_2^2,\qquad M\succeq0.

Let j(i) be the fixed target neighbor of i and Ni\mathcal N_i contain opposite-label points. Our LMNN-style objective uses unit margin, equal pull/push weights, averages by N and adds an explicit trace penalty of 0.01. That last term is an addition to the paper’s basic objective:

J(M)=12N∑idM(i,j(i))+12N∑i∑k∈Ni[1+dM(i,j(i))−dM(i,k)]++0.01tr⁡M.J(M)=\frac1{2N}\sum_i d_M(i,j(i))+\frac1{2N}\sum_i\sum_{k\in\mathcal N_i}[1+d_M(i,j(i))-d_M(i,k)]_++0.01\operatorname{tr}M.

Write Dij=(xi−xj)(xi−xj)⊤D_{ij}=(x_i-x_j)(x_i-x_j)^\top. Each active hinge contributes Dij−DikD_{ij}-D_{ik}; each pull contributes DijD_{ij}, with the averaging above. The trace contributes 0.01I0.01I. Take a subgradient step, symmetrize the result, then clip negative eigenvalues:

M+=Qdiag⁡(max⁡(λ1,0),…,max⁡(λd,0))Q⊤,Qdiag⁡(λ)Q⊤=sym⁡(M−ηG).M^+=Q\operatorname{diag}(\max(\lambda_1,0),\ldots,\max(\lambda_d,0))Q^\top,\qquad Q\operatorname{diag}(\lambda)Q^\top=\operatorname{sym}(M-\eta G).

Eigenvalue clipping is the nearest positive-semidefinite matrix in Frobenius norm for the symmetric tentative update. With fixed target neighbors, the objective is convex in M: distances and trace are linear, and each hinge is a maximum of affine functions. Convexity does not make a finite number of fixed subgradient steps an exact solver. Enumerating one target and all potential impostors costs O(N2d2)O(N^2d^2) naively; dense PSD projection costs O(d3)O(d^3). Distance Metric Learning for Large Margin Nearest Neighbor Classification

Run the calculation

Run CPython 3.12.4 and NumPy 1.26.4. The two classes are the two vertical columns. Starting at the identity, 1,500 projected steps of size 0.01 produce approximately diag(0.91,0); the objective falls from 51.02 to 0.0091. Nearest nonself neighbors on the training table change from all wrong to all correct. Their labels were used to fit the matrix, so this is not held-out accuracy or cross-validation. The program also evaluates the feasible matrix diag(0.25,0): its smaller objective 0.0025 proves the fixed-budget run is not globally optimal.

import numpy as np

X=np.array([[-1.,-4],[-1,4],[1,-3],[1,3]]);Y=np.array([0,0,1,1]);TARGET=np.array([1,0,3,2])


def objective(metric):
    m=np.asarray(metric,dtype=float);loss=.01*np.trace(m);gradient=.01*np.eye(2);active=0
    for i,j in enumerate(TARGET):
        difference=X[i]-X[j];positive=np.outer(difference,difference);loss+=.5*np.sum(m*positive)/4;gradient+=.5*positive/4
        for k in np.flatnonzero(Y!=Y[i]):
            delta=X[i]-X[k];constraint=positive-np.outer(delta,delta);hinge=1+np.sum(m*constraint)
            if hinge>0:loss+=.5*hinge/4;gradient+=.5*constraint/4;active+=1
    return float(loss),gradient,active


def project_psd(matrix):
    symmetric=(matrix+matrix.T)/2;values,vectors=np.linalg.eigh(symmetric);return (vectors*np.maximum(values,0))@vectors.T


def nearest(metric):
    delta=X[:,None,:]-X[None,:,:];distance=np.einsum('ijd,df,ijf->ij',delta,metric,delta);np.fill_diagonal(distance,np.inf);ids=distance.argmin(axis=1);return ids,float(np.mean(Y[ids]==Y))


def train():
    m=np.eye(2);start=objective(m)[0]
    for _ in range(1500):m=project_psd(m-.01*objective(m)[1])
    return m,start,objective(m)[0]


if __name__=='__main__':
    m,start,end=train();print('metric',m.round(9).tolist(),'eigenvalues',np.linalg.eigvalsh(m).round(9).tolist(),'objective',round(start,9),round(end,9));print('training-table nearest nonself neighbors and accuracy',nearest(np.eye(2)),nearest(m))
    print('distinct points with zero learned distance',round(float((X[0]-X[1])@m@(X[0]-X[1])),9))
    print('feasible comparison objective',objective(np.diag([.25,0.]))[0],'fixed-budget run is not globally optimal')
metric [[0.91, 0.0], [0.0, 0.0]] eigenvalues [0.0, 0.91] objective 51.02 0.0091
training-table nearest nonself neighbors and accuracy (array([2, 3, 0, 1]), 0.0) (array([1, 0, 3, 2]), 1.0)
distinct points with zero learned distance 0.0
feasible comparison objective 0.0025 fixed-budget run is not globally optimal

When the method fails

A singular learned matrix can give distinct inputs zero distance. The square root of its quadratic form is a pseudometric on the original input space. Even with positive-definite M, the squared form itself need not satisfy the triangle inequality: on a line, the squared distance from 0 to 2 is four, larger than the sum of the two unit squared distances.

Labels can also encode the wrong similarity for deployment. Same product category is not necessarily same product; a change of camera or data source can invalidate the learned nuisance directions. Fit preprocessing and the metric on training data only, tune settings on validation data, then evaluate untouched queries against an appropriate gallery.

Nonlinear embedding models replace the global linear map with a neural encoder. FaceNet’s normalized embedding and triplet objective provide one such approach, but its training conditions cannot be inferred from this four-point calculation. FaceNet: A Unified Embedding for Face Recognition and Clustering

Exercises with answers

  1. Does diag(0.91,0) separate every distinct input?

Answer 1: No. Points with the same first coordinate have zero learned distance even if the second coordinate differs.

  1. Why keep target neighbors fixed?

Answer 2: Then the objective is convex in M. Re-selecting them during optimization defines a different procedure.

  1. Does 100% training-table neighbor accuracy establish an optimal objective?

Answer 3: No. The feasible matrix diag(0.25,0) has objective 0.0025, below the trained 0.0091.

  1. Project diag(2,−1) onto the PSD cone.

Answer 4: Clip its negative eigenvalue to zero, giving diag(2,0).

Sources and next steps

Read LMNN Sections 3.1–3.2 with the fixed-neighbor definition alongside its pull and push terms. Then compare triplet loss, which expresses relative distance constraints in a learned embedding. A useful extension is to add noisy features and a genuine train/validation/test split; report neighbor accuracy and optimization objective separately. Distance Metric Learning for Large Margin Nearest Neighbor Classification; FaceNet: A Unified Embedding for Face Recognition and Clustering

Make a prediction, then check

The learned matrix has a zero eigenvalue. What can happen?

Choose one answer

Learning objectives

  • Derive a PSD metric objective and projected subgradient update.
  • Separate training retrieval, held-out performance and objective optimality.

Prerequisites & connections

Explore related knowledge →

References

  1. Distance Metric Learning for Large Margin Nearest Neighbor Classification
    Kilian Q. Weinberger; Lawrence K. Saul · 2009
  2. FaceNet: A Unified Embedding for Face Recognition and Clustering
    Florian Schroff; Dmitry Kalenichenko; James Philbin · 2015

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-07 · Codex single-AI-author technical check: primary-source scope, explicit assumptions, original calculations, independent mathematical references and bilingual tests; not independent human or second-agent review.

  • Single-AI-author technical check: bounded primary-source reading, explicit assumptions, original calculations, runnable examples and matching bilingual equations, code and exercises. Not an independent human or second-agent review.
  • Four focused CPython 3.12.4 tests passed per chapter: finite-difference gradients, sample covariance, teacher/center update order, hidden-input isolation, independent least squares, PSD projection, margin feasibility, tied-branch derivatives and transported factor actions as applicable, plus bilingual structure. All eight programs use NumPy 1.26.4; teaching calculations, not image benchmarks.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points published topics to complete articles and removes corresponding pending wording, retaining directory entries for unwritten targets. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.