评价此页

TripletMarginLoss#

class torch.nn.TripletMarginLoss(margin=1.0, p=2.0, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='mean')[源代码]#

创建一个准则,用于根据输入张量 x1x1x2x2x3x3 和一个大于 00 的 margin 值来衡量样本之间的相对相似度。一个 triplet 由 apn(即 anchorpositive examplenegative example)组成。所有输入张量的形状都应为 (N,D)(N, D)

距离交换(distance swap)在 V. Balntas, E. Riba 等人的论文 Learning shallow convolutional feature descriptors with triplet losses 中有详细描述。

每个样本在 mini-batch 中的损失函数为

L(a,p,n)=max{d(ai,pi)d(ai,ni)+margin,0}L(a, p, n) = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}

其中

d(xi,yi)=xiyipd(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p

该范数使用指定的 p 值计算,并添加了一个小的常数 ε\varepsilon 以提高数值稳定性。

另请参阅 TripletMarginWithDistanceLoss,它使用自定义距离函数来计算输入张量的 triplet margin loss。

参数
  • margin (float, optional) – 默认为 11

  • p (int, optional) – 成对距离的范数次数。默认为 22

  • eps (float, optional) – 用于数值稳定的小常数。默认为 1e61e-6

  • swap (bool, optional) – 距离交换(distance swap)在 V. Balntas, E. Riba 等人的论文《Learning shallow convolutional feature descriptors with triplet losses》中有详细描述。默认为 False

  • size_average (bool, optional) – 已弃用 (参见 reduction)。默认情况下,损失值在批次中的每个损失元素上取平均值。请注意,对于某些损失,每个样本有多个元素。如果字段 size_average 设置为 False,则损失值在每个小批次中而是求和。当 reduceFalse 时忽略。默认值:True

  • reduce (bool, optional) – 已弃用 (参见 reduction)。默认情况下,损失值在每个小批次中根据 size_average 对观测值进行平均或求和。当 reduceFalse 时,返回每个批次元素的损失值,并忽略 size_average。默认值:True

  • reduction (str, optional) – 指定要应用于输出的缩减:'none' | 'mean' | 'sum''none':不应用缩减;'mean':输出的总和除以输出中的元素数量;'sum':对输出求和。注意:《size_average》和《reduce》正在弃用中,在此期间,指定这两个参数中的任何一个都将覆盖《reduction》。默认为 'mean'

形状
  • 输入:形状为 (N,D)(N, D)(D)(D) 的张量,其中 DD 是向量维度。

  • 输出:如果 reduction'none' 且输入形状为 (N,D)(N, D),则输出形状为 (N)(N);否则为标量。

示例

>>> triplet_loss = nn.TripletMarginLoss(margin=1.0, p=2, eps=1e-7)
>>> anchor = torch.randn(100, 128, requires_grad=True)
>>> positive = torch.randn(100, 128, requires_grad=True)
>>> negative = torch.randn(100, 128, requires_grad=True)
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
forward(anchor, positive, negative)[源代码]#

执行前向传播。

返回类型

张量