All problems
Contrastive Loss
Problem
Compute the mean contrastive loss over pairs. For similar pairs (label 1) add d^2; for dissimilar pairs (label 0) add max(0, margin - d)^2.
Empty input returns 0.0.
Hint
Similar pairs are pulled together; dissimilar pairs are pushed at least margin apart.
Test cases
case 1
in: [[0.5,2],[1,0],1]
expected: 0.125
case 2
in: [[0.2,0.2],[1,0],1]
expected: 0.3400000000000001
case 3
in: [[0.5],[1],1]
expected: 0.25
case 4
in: [[],[],1]
expected: 0
Starter codePython
def contrastive_loss(distances, labels, margin):
# Your code here
pass4 test cases · run your code against them in the editor