快捷方式

TripletMarginWithDistanceLoss

class torch.nn.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[source][source]

创建一个准则,该准则根据输入张量 aappnn(分别代表锚点、正样本和负样本),以及一个非负实值函数(“距离函数”)来衡量三元组损失。该距离函数用于计算锚点与正样本之间的关系(“正距离”)以及锚点与负样本之间的关系(“负距离”)。

未经约简的损失(即 reduction 设置为 'none' 时)可表示为

(a,p,n)=L={l1,,lN},li=max{d(ai,pi)d(ai,ni)+margin,0}\ell(a, p, n) = L = \{l_1,\dots,l_N\}^\top, \quad l_i = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}

其中 NN 是批处理大小;dd 是一个非负实值函数,用于量化两个张量之间的接近程度,被称为 distance_functionmarginmargin 是一个非负的边界值(margin),表示正距离与负距离之间的最小差异,当差异达到或超过此值时损失为 0。输入张量每个有 NN 个元素,可以是距离函数可以处理的任何形状。

如果 reduction 不是 'none'(默认为 'mean'),则

(x,y)={mean(L),if reduction=‘mean’;sum(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}

另请参阅 TripletMarginLoss,它使用 lpl_p 距离作为距离函数来计算输入张量的三元组损失。

参数
  • distance_function (Callable, optional) – 一个非负实值函数,用于量化两个张量之间的接近程度。如果未指定,将使用 nn.PairwiseDistance。默认值: None

  • margin (float, optional) – 一个非负边界值(margin),表示正距离与负距离之间的最小差异,当差异达到或超过此值时损失为 0。较大的边界值会惩罚负样本相对于正样本与锚点不够远的那些情况。默认值: 11

  • swap (bool, optional) – 是否使用 V. Balntas, E. Riba 等人的论文 Learning shallow convolutional feature descriptors with triplet losses 中描述的距离交换。如果为 True,并且正样本比锚点更接近负样本,则在损失计算中交换正样本和锚点。默认值: False

  • reduction (str, optional) – 指定要应用于输出的(可选)约简方式: 'none' | 'mean' | 'sum''none':不应用约简, 'mean':输出的总和将被输出中的元素数量除, 'sum':输出将被求和。默认值: 'mean'

形状
  • 输入: (N,)(N, *) 其中 * 代表距离函数支持的任意数量的额外维度。

  • 输出: 如果 reduction'none',则形状为 (N)(N) 的张量,否则为标量。

示例

>>> # Initialize embeddings
>>> embedding = nn.Embedding(1000, 128)
>>> anchor_ids = torch.randint(0, 1000, (1,))
>>> positive_ids = torch.randint(0, 1000, (1,))
>>> negative_ids = torch.randint(0, 1000, (1,))
>>> anchor = embedding(anchor_ids)
>>> positive = embedding(positive_ids)
>>> negative = embedding(negative_ids)
>>>
>>> # Built-in Distance Function
>>> triplet_loss = \
>>>     nn.TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance())
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # Custom Distance Function
>>> def l_infinity(x1, x2):
>>>     return torch.max(torch.abs(x1 - x2), dim=1).values
>>>
>>> triplet_loss = (
>>>     nn.TripletMarginWithDistanceLoss(distance_function=l_infinity, margin=1.5))
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # Custom Distance Function (Lambda)
>>> triplet_loss = (
>>>     nn.TripletMarginWithDistanceLoss(
>>>         distance_function=lambda x, y: 1.0 - F.cosine_similarity(x, y)))
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
参考文献

V. Balntas 等人:学习具有三元组损失的浅层卷积特征描述符: https://bmva-archive.org.uk/bmvc/2016/papers/paper119/index.html

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取面向初学者和高级开发者的深入教程

查看教程

资源

查找开发资源并获得问题的解答

查看资源