评价此页

TripletMarginWithDistanceLoss#

class torch.nn.modules.loss.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[源代码]#

创建一个准则,用于衡量给定输入张量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 是一个非负裕度,表示正例距离与负例距离之间的最小差值,该差值是使损失为 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) – 一个非负裕度,表示正例距离与负例距离之间的最小差值,该差值是使损失为 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 等人:Learning shallow convolutional feature descriptors with triplet losses: https://bmva-archive.org.uk/bmvc/2016/papers/paper119/index.html

forward(anchor, positive, negative)[源代码]#

执行前向传播。

返回类型

张量