Compute batch-hard triplet loss

MediumLosses

Why it matters Face recognition and retrieval embeddings are trained with mined triplets like this.

Batch-hard mining picks, for each anchor, its farthest positive and its closest negative in the batch.

Write batch_hard_triplet(E, labels, margin). E is (n, d) embeddings, labels is (n,). Use Euclidean distances. For each anchor i: hardest positive = max distance to a j != i with the same label, hardest negative = min distance to a j with a different label. Loss_i = max(0, pos - neg + margin). Return the mean over anchors that have at least one positive and one negative.

Signaturedef batch_hard_triplet(E, labels, margin)

Example

E = [[0], [1], [3]], labels [0, 0, 1], margin 1: anchor 0 gives max(0, 1 - 3 + 1) = 0, anchor 1 gives max(0, 1 - 2 + 1) = 0, anchor 2 has no positive, so the loss is 0.0.

Understand the idea

Triplet loss teaches embeddings that a positive (same label) should be closer to the anchor than a negative (different label), by at least a margin. Batch-hard mining makes it tough: for each anchor, use its farthest positive and its closest negative in the batch. Worked example: E = [0, 2, 3, 7], labels [0, 0, 1, 1], margin 1. Anchor at 0: positive distance 2, nearest negative min(3, 7) = 3, loss max(0, 2 - 3 + 1) = 0. Anchor at 2: positive 2, nearest negative min(1, 5) = 1, loss 2 - 1 + 1 = 2. Anchor at 3: farthest positive 4, nearest negative min(3, 1) = 1, loss 4 - 1 + 1 = 4. Anchor at 7: positive 4, nearest negative min(7, 5) = 5, loss 0. Mean = (0 + 2 + 4 + 0) / 4 = 1.5. Rule: pairwise Euclidean distances; pos_i = max over j != i with the same label; neg_i = min over j with a different label; loss_i = max(0, pos_i - neg_i + margin); average over anchors that have both. Used in: face verification, person re-identification and metric learning for retrieval.

Shapes and data flow

E (n, d) -> D (n, n)
same (n, n) minus diagonal, diff (n, n)
per anchor: max over same, min over diff
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 3.

  • Sample 1: examplebatch_hard_triplet([[0], [1], [3]], [0, 0, 1], 1.0)
  • Sample 2: violationsbatch_hard_triplet([[0], [2], [1.5], [5]], [0, 0, 1, 1], 1.0)
  • Test 3: randombatch_hard_triplet(_E, _y, 0.5)