快捷方式

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。较大的 margin 会惩罚负例相对于正例而言离锚点不够远的情况。默认值: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, *) 其中 * 表示距离函数支持的任意数量的附加维度。

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

示例

>>> # 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, et al.: Learning shallow convolutional feature descriptors with triplet losses: https://bmva-archive.org.uk/bmvc/2016/papers/paper119/index.html

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

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

查看教程

资源

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

查看资源