• 文档 >
  • torch.nn >
  • TripletMarginWithDistanceLoss
快捷键

TripletMarginWithDistanceLoss

class torch.nn.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[source][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 作为距离函数来计算输入张量的三元组损失。

参数:
  • 距离函数(Callable,可选)- 一个非负的实值函数,用于量化两个张量之间的接近程度。如果未指定,则使用 nn.PairwiseDistance。默认: None

  • 阈值(float,可选)- 表示正负距离之间最小差值的非负阈值,该差值是损失为 0 所必需的。较大的阈值会惩罚负样本与锚点之间的距离不够远的情况,相对于正样本。默认: 11

  • 交换(bool,可选)- 是否使用论文《通过三元损失学习浅层卷积特征描述符》中描述的距离交换,作者为 V. Balntas,E. Riba 等。如果为 True,并且如果正样本比锚点更接近负样本,则在损失计算中交换正样本和锚点。默认: False

  • 缩减(str,可选)- 指定应用于输出的(可选)缩减方式: 'none' | 'mean' | 'sum''none' :不应用缩减, 'mean' :输出总和除以输出元素的数量, 'sum' :输出将被求和。默认: 'mean'

形状:
  • 输入: (N,)(N, *) 其中 * 代表距离函数支持的任意多个额外维度。

  • 输出:如果 reduction'none' ,则形状为 (N)(N) 的张量,否则为标量。

示例:

>>> # 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 等人:使用三元组损失学习浅层卷积特征描述符:https://bmva-archive.org.uk/bmvc/2016/papers/paper119/index.html


© 版权所有 PyTorch 贡献者。

使用 Sphinx 构建,并使用 Read the Docs 提供的主题。

文档

PyTorch 的全面开发者文档

查看文档

教程

深入了解初学者和高级开发者的教程

查看教程

资源

查找开发资源并获得您的疑问解答

查看资源