評價此頁

TripletMarginLoss#

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

建立一個標準,用於根據輸入張量 x1x1, x2x2, x3x3 和一個大於 00 的 margin 來測量三元組損失。這用於測量樣本之間的相對相似性。一個三元組由 apn(即 anchorpositive examplesnegative examples)組成。所有輸入張量的形狀都應為 (N,D)(N, D)

距離交換的詳細描述請參見論文 Learning shallow convolutional feature descriptors with triplet losses(作者:V. Balntas, E. Riba 等)。

每個小批次樣本的損失函式為:

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) – 距離交換的詳細描述請參見論文 Learning shallow convolutional feature descriptors with triplet losses(作者:V. Balntas, E. Riba 等)。預設值: False

  • size_average (bool, optional) – 已棄用 (參見 reduction)。預設情況下,損失值在批次中的每個損失元素上取平均值。請注意,對於某些損失,每個樣本有多個元素。如果欄位 size_average 設定為 False,則損失值在每個小批次中而是求和。當 reduceFalse 時忽略。預設值:True

  • reduce (bool, optional) – 已棄用 (參見 reduction)。預設情況下,損失值在每個小批次中根據 size_average 對觀測值進行平均或求和。當 reduceFalse 時,返回每個批次元素的損失值,並忽略 size_average。預設值:True

  • reduction (str, optional) – 指定要應用於輸出的歸約方式: '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()
forward(anchor, positive, negative)[原始碼]#

執行前向傳播。

返回型別

張量