Triplet lossMediumnumpylossmetric-learningembeddingstriplet
Triplet loss
Background
Triplet loss trains embeddings so that an anchor is closer to a "positive" (same class) than to a "negative" (different class) by at least a margin. It is the workhorse of metric learning — face recognition, image retrieval, and contrastive representation learning all use it to shape an embedding space where distance means dissimilarity.
Problem statement
Implement triplet_loss(anchor, positive, negative, margin=1.0) using squared-Euclidean distances:
Input
anchor,positive,negative—np.ndarray(N, D): the three embedding sets.margin—float: the required separation.
Output
Returns a float: the mean triplet loss over the batch ().
Examples
Example 1
Input: anchor = [[0, 0]], positive = [[2, 0]], negative = [[1, 0]], margin = 1.0
Output: 4.0
Explanation: and ; the positive is farther than the negative, so the loss is .
Constraints
- Use the squared Euclidean distance per embedding pair.
- The hinge zeroes out triplets that already satisfy the margin.
- Average over the batch; the result is .
Notes
- A loss of 0 means every triplet already respects the margin (anchor closer to its positive than its negative by at least
margin) — the "easy" triplets that contribute no gradient. - Mining hard / semi-hard triplets (those with positive loss) is what makes training efficient, since most random triplets are already easy.
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: 4.0
- •Easy triplet (positive near, negative far) -> 0
- •Equal distances -> loss equals the margin
- •Averages over the batch