評價此頁

TripletMarginLoss#

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

建立一個準則,用於根據輸入張量 x1x1x2x2x3x3 和一個大於 00 的 margin 值來衡量樣本之間的相對相似度。一個 triplet 由 apn(即 anchorpositive examplenegative example)組成。所有輸入張量的形狀都應為 (N,D)(N, D)

距離交換(distance swap)在 V. Balntas, E. Riba 等人的論文 Learning shallow convolutional feature descriptors with triplet losses 中有詳細描述。

每個樣本在 mini-batch 中的損失函式為

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,它使用自定義距離函式來計算輸入張量的 triplet margin loss。

引數
  • 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) – 指定要應用於輸出的縮減:'none' | 'mean' | 'sum''none':不應用縮減;'mean':輸出的總和除以輸出中的元素數量;'sum':對輸出求和。注意:《size_average》和《reduce》正在棄用中,在此期間,指定這兩個引數中的任何一個都將覆蓋《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)[原始碼]#

執行前向傳播。

返回型別

張量