Compute contrastive loss for pairs of embeddings. A label of 1 marks a similar pair, while 0 marks a dissimilar pair. First compute each Euclidean distance:
di=∥ai−bi∥2Then compute each pair loss:
ℓi=yidi2+(1−yi)max(0,m−di)2Here, ai and bi are the two embeddings, di is their distance, yi is the pair label, m is the margin, and ℓi is the pair loss. A one-dimensional embedding represents one pair; a two-dimensional input contains one pair per row. Return the mean or sum as a Python float according to reduction.
Input: a = [1.0, 0.0], b = [1.0, 0.0], y = [1], margin = 1.0, reduction = "mean"
Output: 0.0
Explanation: The similar embeddings have zero distance, so their squared-distance loss is zero.
Input: a = [0.0, 0.0], b = [0.5, 0.0], y = [0], margin = 1.0, reduction = "mean"
Output: 0.25
Input: a = [[0.0, 0.0], [1.0, 1.0]], b = [[0.0, 0.0], [2.0, 2.0]], y = [1, 0], margin = 1.0, reduction = "mean"
Output: 0.0
Convert a one-dimensional difference to shape (1, D) before reducing over axis 1.
Use np.linalg.norm(a - b, axis=1) for the pairwise distances.
Build the positive and negative terms separately before applying the reduction.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: array
Accepts: number
Accepts: string
Compute contrastive loss for pairs of embeddings. A label of 1 marks a similar pair, while 0 marks a dissimilar pair. First compute each Euclidean distance:
di=∥ai−bi∥2Then compute each pair loss:
ℓi=yidi2+(1−yi)max(0,m−di)2Here, ai and bi are the two embeddings, di is their distance, yi is the pair label, m is the margin, and ℓi is the pair loss. A one-dimensional embedding represents one pair; a two-dimensional input contains one pair per row. Return the mean or sum as a Python float according to reduction.
Input: a = [1.0, 0.0], b = [1.0, 0.0], y = [1], margin = 1.0, reduction = "mean"
Output: 0.0
Explanation: The similar embeddings have zero distance, so their squared-distance loss is zero.
Input: a = [0.0, 0.0], b = [0.5, 0.0], y = [0], margin = 1.0, reduction = "mean"
Output: 0.25
Input: a = [[0.0, 0.0], [1.0, 1.0]], b = [[0.0, 0.0], [2.0, 2.0]], y = [1, 0], margin = 1.0, reduction = "mean"
Output: 0.0
Convert a one-dimensional difference to shape (1, D) before reducing over axis 1.
Use np.linalg.norm(a - b, axis=1) for the pairwise distances.
Build the positive and negative terms separately before applying the reduction.
Sign in to take notes on this problem
Accepts: array
Accepts: array
Accepts: array
Accepts: number
Accepts: string