評價此頁

TripletMarginWithDistanceLoss#

class torch.nn.TripletMarginWithDistanceLoss(*, distance_function=None, margin=1.0, swap=False, reduction='mean')[source]#

建立一個準則,用於測量給定輸入張量 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, *),其中 * 代表距離函式支援的任何額外維度。

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

示例

>>> # 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)[source]#

執行前向傳播。

返回型別

張量