TripletMarginLoss¶
- class torch.nn.TripletMarginLoss(margin=1.0, p=2.0, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='mean')[source][source]¶
建立一個準則,用於測量給定輸入張量 、、 以及一個邊界 (margin),其值大於 的 triplet loss。 這用於測量樣本之間的相對相似性。 一個 triplet 由 a、p 和 n 組成(即分別為 anchor、positive examples 和 negative examples)。 所有輸入張量的形狀應為 。
距離交換 (distance swap) 在 V. Balntas、E. Riba 等人的論文 Learning shallow convolutional feature descriptors with triplet losses 中有詳細描述。
mini-batch 中每個樣本的損失函數為
其中
此範數 (norm) 使用指定的 p 值計算,並加入一個小常數 以確保數值穩定性。
另請參閱
TripletMarginWithDistanceLoss
,它使用自定義距離函數計算輸入張量的 triplet margin loss。- 參數
margin (float, optional) – 預設值: 。
p (int, optional) – 用於計算成對距離的範數次方。預設值: 。
eps (float, optional) – 用於數值穩定性的小常數。預設值: 。
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
,則會針對每個小批次對損失求和。當reduce
為False
時,此參數將被忽略。預設值:True
reduce (bool, optional) – 已棄用 (請參閱
reduction
)。預設情況下,損失會根據size_average
在每個小批次的觀測值上進行平均或求和。當reduce
為False
時,會改為傳回每個批次元素的損失,並忽略size_average
。預設值:True
reduction (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()