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:
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 roottriplet_loss(a, p, n, margin): the mean loss for arrays of anchors, positives and negativesbatch_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.