TripletMarginLoss#
- class torch.nn.TripletMarginLoss(margin=1.0, p=2.0, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='mean')[源代码]#
创建一个准则,用于根据输入张量 、、 和一个大于 的 margin 值来衡量样本之间的相对相似度。一个 triplet 由 a、p 和 n(即 anchor、positive example 和 negative example)组成。所有输入张量的形状都应为 。
距离交换(distance swap)在 V. Balntas, E. Riba 等人的论文 Learning shallow convolutional feature descriptors with triplet losses 中有详细描述。
每个样本在 mini-batch 中的损失函数为
其中
该范数使用指定的 p 值计算,并添加了一个小的常数 以提高数值稳定性。
另请参阅
TripletMarginWithDistanceLoss
,它使用自定义距离函数来计算输入张量的 triplet margin loss。- 参数
margin (float, optional) – 默认为 。
p (int, optional) – 成对距离的范数次数。默认为 。
eps (float, optional) – 用于数值稳定的小常数。默认为 。
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
,则损失值在每个小批次中而是求和。当reduce
为False
时忽略。默认值:True
reduce (bool, optional) – 已弃用 (参见
reduction
)。默认情况下,损失值在每个小批次中根据size_average
对观测值进行平均或求和。当reduce
为False
时,返回每个批次元素的损失值,并忽略size_average
。默认值:True
reduction (str, optional) – 指定要应用于输出的缩减:
'none'
|'mean'
|'sum'
。'none'
:不应用缩减;'mean'
:输出的总和除以输出中的元素数量;'sum'
:对输出求和。注意:《size_average》和《reduce》正在弃用中,在此期间,指定这两个参数中的任何一个都将覆盖《reduction》。默认为'mean'
。
- 形状
输入:形状为 或 的张量,其中 是向量维度。
输出:如果
reduction
为'none'
且输入形状为 ,则输出形状为 ;否则为标量。
示例
>>> 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()