Metric and triplet learning
Quick answer
Metric learning shapes an embedding space so relevant examples are close and irrelevant examples are far apart. Triplet loss compares an anchor, a positive and a negative. Examples are static Python snippets tested locally on CPU; PyTorch is required for selected examples. ByteMind execution is unverified.
Squared distance triplet
a,p,n=[0,0],[1,0],[2,0]d=lambda x,y:sum((u-v)**2 for u,v in zip(x,y))print(max(0,d(a,p)-d(a,n)+2))Expected output (locally tested): 0. With squared distances the negative is far enough for this margin.
How it works
An embedding is a vector z=f(x). Euclidean distance is sqrt(sum((a_i-b_i)^2)); cosine similarity is a dot product divided by the product of norms and requires a defined zero-vector policy. For unit vectors squared Euclidean distance equals 2-2cosine similarity. A contrastive pair loss may use yd^2+(1-y)*max(0,m-d)^2 with y=1 for same class and margin m>0. Conventions vary, so define y and d. Triplet loss is max(0,d(a,p)-d(a,n)+m). Here d can be Euclidean or squared Euclidean; they are different objectives and margins are not interchangeable. PyTorch TripletMarginLoss defaults to p=2 Euclidean with epsilon and mean reduction, not squared distances. The goal is d(a,n)>=d(a,p)+m. A collapsed encoder sending all inputs to one vector fails margin constraints but optimizing can still be difficult. Evaluate retrieval with held-out identities, recall@k and rank metrics rather than training loss alone. Norm and distance scales affect nearest neighbors; apply the same preprocessing to gallery and queries.
Native Euclidean triplet and cosine
import torchfrom torch.nn import TripletMarginLossfrom torch.nn.functional import cosine_similaritya=torch.tensor([[0.,0.]],dtype=torch.float64);p=torch.tensor([[1.,0.]],dtype=torch.float64);n=torch.tensor([[2.,0.]],dtype=torch.float64)print(round(float(TripletMarginLoss(margin=2.,eps=0.)(a,p,n)),6),round(float(cosine_similarity(p,n)),6))Expected output (locally tested): 1.0 1.0. Euclidean triplet loss is one; parallel positive vectors have cosine similarity one.
Common mistakes
Do not confuse similarity (larger is closer) with distance (smaller is closer), use a cosine for a zero vector without policy, or compare squared-distance margins with Euclidean ones.
Practice and next steps
For anchor [0,0], positive [1,0], negative [2,0], compute triplet losses using Euclidean and squared distance at margin 2. Explain why they differ.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Metric and triplet learning — knowledge check
Apply metric and triplet learning to small examples and debugging scenarios.
Which pair should be close in triplet learning?
What is zero triplet loss condition?
What is default TripletMarginLoss distance type?
What can cosine similarity fail to distinguish?
What should retrieval evaluation isolate?