235. 计算 batch-hard triplet loss
重要性 人脸识别和检索任务中的 embeddings 通常使用这种挖掘出的 triplets 进行训练。
Batch-hard mining 会为每个 anchor 在 batch 中挑选其最远的 positive 和最近的 negative。
编写 batch_hard_triplet(E, labels, margin)。E 是 (n, d) 的 embeddings,labels 是 (n,)。使用 Euclidean distances。对于每个 anchor i:hardest positive = 与其具有相同 label 且 j != i 的最大距离,hardest negative = 与其具有不同 label 的最小距离。Loss_i = max(0, pos - neg + margin)。返回所有至少包含一个 positive 和一个 negative 的 anchor 的平均 loss。
def batch_hard_triplet(E, labels, margin)示例 1
输入: E = [[0], [1], [3]], labels [0, 0, 1], margin 1: anchor 0
输出: 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.
示例 2
输入: E = [[0], [1], [3]], labels = [0, 0, 1], margin = 1.0
输出: 0.0
示例 3
输入: E = [[0], [2], [1.5], [5]], labels = [0, 0, 1, 1], margin = 1.0
输出: 2.375
约束条件
- Python 3 with NumPy. Code runs in your browser.
- Your code must pass all 3 tests to be accepted.
提示 1
构建距离矩阵以及用于相同 label 和不同 label pair 的 boolean masks。
提示 2
在计算 positives 时排除 anchor 本身。
提示 3
Hardest negative 是最小距离。
提示 4
跳过没有 positive 或没有 negative 的 anchor。
常见错误
- 使用了最远的 negative。
- 将 anchor 本身包含在 its own positive 中(距离为 0)。
理解思路
Triplet loss 通过训练 embeddings,使得 positive(相同 label)与 anchor 的距离应比 negative(不同 label)至少近一个 margin。Batch-hard mining 增加了难度:对于每个 anchor,使用其在 batch 中最远的 positive 和最近的 negative。
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.
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. 应用场景:人脸验证、行人重识别以及检索任务中的 metric learning。
Shape 与数据流
E (n, d) -> D (n, n) same (n, n) minus diagonal, diff (n, n) per anchor: max over same, min over diff