Shortcuts

TripletMarginLoss

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

创建一个标准,用于衡量给定输入张量 x1x1, x2x2, x3x3 和一个大于 00 的边界的 triplet loss。 这用于衡量样本之间的相对相似性。一个 triplet 由 a, pn 组成(即 anchor, positive examplesnegative examples)。所有输入张量的形状应为 (N,D)(N, D)

距离交换在V. Balntas, E. Riba 等人发表的论文《Learning shallow convolutional feature descriptors with triplet losses》中有详细描述。

小批量中每个样本的损失函数为:

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,它使用自定义距离函数计算输入张量的三元组边缘损失。

Parameters
  • margin (float, 可选) – 默认值: 11.

  • p (int, 可选) – 成对距离的范数度。默认值:22

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

  • swap (bool, 可选) – 距离交换在论文 Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba 等人中有详细描述。默认值: False

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

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

  • reduction (str, 可选) – 指定应用于输出的reduction方式: 'none' | 'mean' | 'sum''none':不进行reduction, 'mean':输出的总和将除以输出中的元素数量,'sum':输出将被求和。注意:size_averagereduce 正在被弃用,在此期间, 指定这两个参数中的任何一个都将覆盖 reduction。默认值:'mean'

Shape:
  • 输入:(N,D)(N, D)(D)(D) 其中 DD 是向量维度。

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

示例:

>>> 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()
优云智算