Triplet Loss with Batch-Hard Mining

medium
Unit 12 · Mixed Precision & Metric Learning0/3 to milestone

Face recognition and image retrieval models learn embeddings where same-identity examples are close. The triplet loss pushes an anchor closer to a positive than to a negative by a margin:

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

Random triplets are mostly too easy. Batch-hard mining (Hermans et al., 2017) uses, for each anchor in the batch, its farthest positive and closest negative.

Implement, with Euclidean distances:

  • pairwise_distances(E): the (n, n) distance matrix, computed without Python loops, clipping tiny negative values to 0 before the square root
  • triplet_loss(a, p, n, margin): the mean loss for arrays of anchors, positives and negatives
  • batch_hard_triplet_loss(E, labels, margin): the mean over anchors that have at least one positive (another item with the same label) and one negative. Return 0.0 if there are none.
#metric-learning#embeddings#loss-functions2 visible + 2 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Triplet Loss with Batch-Hard Mining · TechGradify