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')[原始碼]#
建立一個標準,用於根據輸入張量 , , 和一個大於 的 margin 來測量三元組損失。這用於測量樣本之間的相對相似性。一個三元組由 a、p 和 n(即 anchor、positive examples 和 negative examples)組成。所有輸入張量的形狀都應為 。
距離交換的詳細描述請參見論文 Learning shallow convolutional feature descriptors with triplet losses(作者:V. Balntas, E. Riba 等)。
每個小批次樣本的損失函式為:
其中
該範數使用指定的 p 值計算,並添加了一個小的常數 以提高數值穩定性。
另請參閱
TripletMarginWithDistanceLoss,它使用自定義距離函式來計算輸入張量的三元組邊距損失。- 引數
margin (float, optional) – 預設值: 。
p (int, optional) – 成對距離的範數次數。預設值: 。
eps (float, optional) – 用於數值穩定的小常數。預設值: 。
swap (bool, optional) – 距離交換的詳細描述請參見論文 Learning shallow convolutional feature descriptors with triplet losses(作者:V. Balntas, E. Riba 等)。預設值:
False。size_average (bool, optional) – 已棄用 (參見
reduction)。預設情況下,損失值在批次中的每個損失元素上取平均值。請注意,對於某些損失,每個樣本有多個元素。如果欄位size_average設定為False,則損失值在每個小批次中而是求和。當reduce為False時忽略。預設值:Truereduce (bool, optional) – 已棄用 (參見
reduction)。預設情況下,損失值在每個小批次中根據size_average對觀測值進行平均或求和。當reduce為False時,返回每個批次元素的損失值,並忽略size_average。預設值:Truereduction (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()