快捷方式

TripletMarginLoss

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

创建一个准则,该准则根据输入张量 x1x1x2x2x3x3 和一个大于 00 的边界值(margin)来度量三元组损失(triplet loss)。这用于度量样本之间的相对相似性。一个三元组由 apn 组成(分别表示 锚点(anchor)正例(positive examples)负例(negative examples))。所有输入张量的形状应为 (N,D)(N, D)

距离交换(distance swap)在 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,该类使用自定义距离函数计算输入张量的三元组边界损失。

参数
  • 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) – 指定应用于输出的归约(reduction)方式:'none' | 'mean' | 'sum''none': 不应用归约,'mean': 输出总和除以输出中的元素数量进行平均,'sum': 对输出求和。注意:size_averagereduce 正在弃用过程中,在此期间,指定这两个参数中的任何一个都将覆盖 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()

文档

访问 PyTorch 的全面开发者文档

查看文档

教程

获取针对初学者和高级开发者的深度教程

查看教程

资源

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

查看资源