TripletMarginLoss#
- class torch.nn.TripletMarginLoss(margin=1.0, p=2.0, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='mean')[原始碼]#
建立一個準則,用於根據輸入張量 、、 和一個大於 的 margin 值來衡量樣本之間的相對相似度。一個 triplet 由 a、p 和 n(即 anchor、positive example 和 negative example)組成。所有輸入張量的形狀都應為 。
距離交換(distance swap)在 V. Balntas, E. Riba 等人的論文 Learning shallow convolutional feature descriptors with triplet losses 中有詳細描述。
每個樣本在 mini-batch 中的損失函式為
其中
該範數使用指定的 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時忽略。預設值: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()