评价此页

TripletMarginWithDistanceLoss#

class torch.nn.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[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 是一个非负的边距,表示正例距离与负例距离之间的最小差值,达到此差值时损失为 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, *),其中 * 代表距离函数支持的任何额外维度。

  • 输出:一个形状为 (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 等人:Learning shallow convolutional feature descriptors with triplet losses: https://bmva-archive.org.uk/bmvc/2016/papers/paper119/index.html

forward(anchor, positive, negative)[source]#

执行前向传播。

返回类型

张量