Contrastive lossMediumnumpylossmetric-learningembeddingssiamese
Contrastive loss
Background
Contrastive loss trains a Siamese embedding from pairs: similar pairs are pulled together while dissimilar pairs are pushed apart until they are at least a margin away. It is the pairwise cousin of triplet loss and the basis of Siamese networks for verification and similarity learning.
Problem statement
Implement contrastive_loss(x1, x2, label, margin=1.0). With Euclidean distance and label (1 = similar, 0 = dissimilar):
Input
x1,x2—np.ndarray(N, D): paired embeddings.label—np.ndarray(N,): 1 for similar pairs, 0 for dissimilar.margin—float: the minimum desired distance for dissimilar pairs.
Output
Returns a float: the mean contrastive loss ().
Examples
Example 1
Input: x1 = [[0,0],[0,0]], x2 = [[1,0],[0.5,0]], label = [1, 0], margin = 1.0
Output: 0.625
Explanation: the similar pair () has , contributing . The dissimilar pair () has , contributing . Mean .
Constraints
- is the (non-squared) Euclidean distance; the similar term squares , the dissimilar term squares the hinged margin gap.
- Dissimilar pairs already farther than
margincontribute 0. - Average over the batch; the result is .
Notes
- Similar pairs pull quadratically with (no margin); dissimilar pairs push only while inside the margin — once separated they stop contributing.
- This is the loss behind classic Siamese signature/face verification (Hadsell, Chopra & LeCun, 2006).
Python
Loading...
This problem ships 4 hidden tests. They run in your browser via Pyodide — no backend, no submission queue. Press ▶ Run tests to execute.
- •Reference example: 0.625
- •Identical similar pair -> 0
- •Dissimilar pair beyond the margin -> 0
- •Coincident dissimilar pair -> margin squared