Triplet Loss: Closer to the Positive by a Margin

Loss FunctionsMedium+10 XP+10

Triplet Loss: Closer to the Positive by a Margin

Triplet loss trains embeddings by comparing three points at once: an anchor, a positive (same class as the anchor), and a negative (a different class). It wants the anchor closer to its positive than to its negative, by at least a margin.

Let d(a, b) be squared Euclidean distance between two embeddings:

L=max⁡(0, d(a,p)−d(a,n)+margin)L = \max\bigl(0,\ d(a, p) - d(a, n) + \text{margin}\bigr)L=max(0, d(a,p)−d(a,n)+margin)

Task: write triplet_loss(anchors, positives, negatives, margin) returning the mean loss over all triplets, rounded to 4 decimal places.

  • Each of anchors, positives, negatives is a list of embedding vectors (lists of floats), one triplet per index.
  • If the anchor is already closer to its positive than to its negative by at least the margin, that triplet contributes zero loss.

Examples

anchors = [[0.0, 0.0]]
positives = [[3.0, 0.0]]
negatives = [[1.0, 0.0]]
margin = 1.0
returns 9.0
anchors = [[0.0, 0.0]]
positives = [[0.5, 0.0]]
negatives = [[5.0, 0.0]]
margin = 1.0
returns 0.0

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run