Metric learning
度量学习
Learn a PSD distance geometry, test its gradients, and distinguish retrieval success from optimality.
metric-learningStart 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 , learn a symmetric matrix . If , the quadratic form is ordinary squared distance after a linear map:
Let j(i) be the fixed target neighbor of i and 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:
Write . Each active hinge contributes ; each pull contributes , with the averaging above. The trace contributes . Take a subgradient step, symmetrize the result, then clip negative eigenvalues:
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 naively; dense PSD projection costs . 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
- 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.
- Why keep target neighbors fixed?
Answer 2: Then the objective is convex in M. Re-selecting them during optimization defines a different procedure.
- 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.
- 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?
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
- Distance Metric Learning for Large Margin Nearest Neighbor Classification
Kilian Q. Weinberger; Lawrence K. Saul · 2009 - 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:
- Distance Metric Learning for Large Margin Nearest Neighbor Classification · Physical pages 10–12, Sections 3.1–3.2 and Eqs. 10–13: fixed target neighbors, impostors, pull/push hinge objective.
- FaceNet: A Unified Embedding for Face Recognition and Clustering · Physical pages 3–4, Sections 3.1–3.2: normalized nonlinear embeddings and triplet constraints.
Related topics