Shortcuts

TripletMarginWithDistanceLoss

class torch.nn.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[源代码]

创建一个标准,用于衡量给定输入张量 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_function; 并且 marginmargin 是一个非负的边界值,表示正负距离之间的最小差异,以使损失为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 距离作为距离函数来计算输入张量的三重损失。

Parameters
  • distance_function (可调用对象, 可选) – 一个非负的实值函数,用于量化两个张量的接近程度。如果未指定,将使用nn.PairwiseDistance。默认值:None

  • margin (float, 可选) – 一个非负的边距,表示正负距离之间的最小差异,以使损失为0。较大的边距会惩罚负样本相对于正样本不够远离锚点的情况。默认值:11

  • swap (bool, 可选) – 是否使用论文《Learning shallow convolutional feature descriptors with triplet losses》中描述的距离交换方法,作者为V. Balntas, E. Riba 等人。如果为True,并且如果正样本比锚点更接近负样本,则在损失计算中交换正样本和锚点。默认值:False

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

Shape:
  • 输入:(N,)(N, *) 其中 * 表示距离函数支持的任意数量的附加维度。

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

示例:

>>> # 初始化嵌入
>>> 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)
>>>
>>> # 内置距离函数
>>> triplet_loss = \
>>>     nn.TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance())
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # 自定义距离函数
>>> 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()
>>>
>>> # 自定义距离函数 (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()
Reference:

V. Balntas 等人:通过三重损失学习浅层卷积特征描述符: http://www.bmva.org/bmvc/2016/papers/paper119/index.html

优云智算