Problems
Loading...
1 / 1

Implement Triplet Loss

Loss Functions
Medium

Implement Triplet Loss for embedding ranking. This loss ensures that an anchor embedding is closer to a positive example than to a negative example by a margin.

Triplet Loss Formula:

Distance function:

d(x,y)=xy22d(x, y) = \lVert x - y \rVert_2^2

Triplet Loss:

L=max(0,  d(a,p)d(a,n)+m)L = \max\left(0,\; d(a, p) - d(a, n) + m\right)

where a=anchor, p=positive, n=negative, m=margin

Function Arguments

  • anchor: array-like - Anchor embeddings (N, D) or (D,)
  • positive: array-like - Positive embeddings (same class)
  • negative: array-like - Negative embeddings (different class)
  • margin: float = 1.0 - Margin parameter (m)
Loading visualization...

Examples

Input: anchor=[[1,0]], positive=[[2,0]], negative=[[5,0]], margin=1.0

Output: 0.0

d(a,p)=1, d(a,n)=16 → max(0, 1-16+1) = 0

Input: anchor=[[0,0]], positive=[[3,0]], negative=[[1,0]], margin=1.0

Output: 8.0

d(a,p)=9, d(a,n)=1 → max(0, 9-1+1) = 9

Input: anchor=[1,0], positive=[2,0], negative=[5,0], margin=1.0

Output: 0.0

Single vectors (1D input) also supported

Hint 1

Compute squared Euclidean distance: np.sum() for batch processing.

Hint 2

Handle single vectors by reshaping.

Hint 3

Use np.maximum() to apply the max function element-wise.

Requirements

  • Use squared Euclidean distance
  • Return scalar mean loss across batch
  • Support both single vectors and batch input
  • Must be vectorized (no Python loops)

Constraints

  • 1 ≤ N ≤ 1024 samples
  • margin ≥ 0
  • NumPy only; time limit: 300ms
Try Similar Problems