BLOGLLM Logo
Go Pro
Guest
Not signed in
所有博客课程练习面试准备系列标签书签价格
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboard游戏
Articles
练习 / Losses8 of 12 in topic

235. 计算 batch-hard triplet loss

MediumLosses

重要性 人脸识别和检索任务中的 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。

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.

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
主题
Losses
相似题目
  • 使用 focal loss 降低简单样本的权重Medium
  • 忽略 padding 的 token 级 KL 蒸馏Medium
  • 计算类别加权交叉熵Medium
  • 直接从 logits 计算二元交叉熵Easy
所有 Losses 道题目
反馈
235 / 903
Python 3solution.pyPython 空闲
1
2
3
4
5
6
import numpy as np
​
def batch_hard_triplet(E, labels, margin):
# your code here
pass
​

Run 会在浏览器中检查这些用例,无需登录。 Submit 会检查所有 3 个测试。

Ctrl/按 + 回车 运行
© BlogLLM, Bengaluru, India关于条款隐私退款DMCA联系我们RSS