評價此頁

TripletMarginWithDistanceLoss#

class torch.nn.modules.loss.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[原始碼]#

建立一個準則,用於衡量給定輸入張量aappnn(分別代表錨點、正例和負例)的三元組損失,以及一個用於計算錨點與正例(“正例距離”)和錨點與負例(“負例距離”)之間關係的非負實值函式(“距離函式”)。

未約簡的損失(即 reduction 設定為 'none')可以描述為:

(a,p,n)=L={l1,,lN},li=max{d(ai,pi)d(ai,ni)+margin,0}\ell(a, p, n) = L = \{l_1,\dots,l_N\}^\top, \quad l_i = \max \{d(a_i, p_i) - d(a_i, n_i) + {\rm margin}, 0\}

其中 NN 是批次大小;dd 是量化兩個張量接近程度的非負實值函式,稱為 distance_functionmarginmargin 是一個非負裕度,表示正例距離與負例距離之間的最小差值,該差值是使損失為 0 所必需的。輸入張量每個有 NN 個元素,可以具有距離函式能夠處理的任何形狀。

如果 reduction 不是 'none'(預設為 'mean'),則:

(x,y)={mean(L),if reduction=‘mean’;sum(L),if reduction=‘sum’.\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{`sum'.} \end{cases}

另請參閱 TripletMarginLoss,它使用 lpl_p 距離作為距離函式來計算三元組損失。

引數
  • distance_function (Callable, optional) – 一個量化兩個張量接近程度的非負實值函式。如果未指定,將使用 nn.PairwiseDistance。預設為 None

  • margin (float, optional) – 一個非負裕度,表示正例距離與負例距離之間的最小差值,該差值是使損失為 0 所必需的。較大的裕度會懲罰負例相對於正例不夠遠的案例。預設為 11

  • swap (bool, optional) – 是否使用 V. Balntas, E. Riba 等人論文《Learning shallow convolutional feature descriptors with triplet losses》中描述的距離交換。如果為 True,並且正例比錨點更接近負例,則在損失計算中交換正例和錨點。預設為 False

  • reduction (str, optional) – 指定應用於輸出的可選約簡:'none' | 'mean' | 'sum''none':不應用約簡;'mean':輸出的總和除以輸出中的元素數量;'sum':對輸出進行求和。預設為 'mean'

形狀
  • 輸入:(N,)(N, *),其中 * 表示距離函式支援的任何附加維度。

  • 輸出:如果 reduction'none',則為形狀為 (N)(N) 的張量,否則為標量。

示例

>>> # Initialize embeddings
>>> embedding = nn.Embedding(1000, 128)
>>> anchor_ids = torch.randint(0, 1000, (1,))
>>> positive_ids = torch.randint(0, 1000, (1,))
>>> negative_ids = torch.randint(0, 1000, (1,))
>>> anchor = embedding(anchor_ids)
>>> positive = embedding(positive_ids)
>>> negative = embedding(negative_ids)
>>>
>>> # Built-in Distance Function
>>> triplet_loss = \
>>>     nn.TripletMarginWithDistanceLoss(distance_function=nn.PairwiseDistance())
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # Custom Distance Function
>>> def l_infinity(x1, x2):
>>>     return torch.max(torch.abs(x1 - x2), dim=1).values
>>>
>>> triplet_loss = (
>>>     nn.TripletMarginWithDistanceLoss(distance_function=l_infinity, margin=1.5))
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
>>>
>>> # Custom Distance Function (Lambda)
>>> triplet_loss = (
>>>     nn.TripletMarginWithDistanceLoss(
>>>         distance_function=lambda x, y: 1.0 - F.cosine_similarity(x, y)))
>>> output = triplet_loss(anchor, positive, negative)
>>> output.backward()
參考

V. Balntas 等人:Learning shallow convolutional feature descriptors with triplet losses: https://bmva-archive.org.uk/bmvc/2016/papers/paper119/index.html

forward(anchor, positive, negative)[原始碼]#

執行前向傳播。

返回型別

張量