Metric learning trains an embedding so that the distance between two inputs matches whether they are the same. The contrastive loss (Hadsell, Chopra and LeCun, 2006) scores one pair given its distance d and a flag s (1 for similar, 0 for dissimilar):
L = s * d^2 + (1 - s) * max(0, m - d)^2
Similar pairs are penalized by their distance. Dissimilar pairs are penalized only while they sit inside the margin m.
Implement contrastive_loss(distances, is_similar, margin=1.0), which applies the formula elementwise.
distances and is_similar have the same shape. is_similar holds 0 or 1 values.ValueError.ValueError.margin < 0 raises ValueError.is_similar values other than 0 and 1 raise ValueError.Use np.maximum(0.0, margin - d) for the hinge. The dissimilar term is zero whenever d is at least the margin.
No results yet
Run your code to check it against the examples, or submit to run every test.