# TripletMarginLoss¶

class paddle.nn. TripletMarginLoss ( margin=1.0, p=2.0, epsilon=1e-06, swap=False, reduction='mean', name=None ) [source]

Creates a criterion that measures the triplet loss given an input tensors $$x1$$, $$x2$$, $$x3$$ and a margin with a value greater than $$0$$. This is used for measuring a relative similarity between samples. A triplet is composed by input, positive and negative (i.e., input, positive examples and negative examples respectively). The shapes of all input tensors should be $$(N, *)$$.

The loss function for each sample in the mini-batch is:

$L(input, pos, neg) = \max \{d(input_i, pos_i) - d(input_i, neg_i) + {\rm margin}, 0\}$

where

$d(x_i, y_i) = \left\lVert {\bf x}_i - {\bf y}_i \right\rVert_p$
Parameters
• margin (float, Optional) – Default: $$1$$.

• p (int, Optional) – The norm degree for pairwise distance. Default: $$2$$.

• epsilon (float, Optional) – Add small value to avoid division by zero, default value is 1e-6.

• swap (bool, Optional) – The distance swap change the negative distance to the distance between positive sample and negative sample. For more details, see Learning shallow convolutional feature descriptors with triplet losses. Default: False.

• reduction (str, Optional) – Indicate how to average the loss by batch_size. the candicates are 'none' | 'mean' | 'sum'. If reduction is 'none', the unreduced loss is returned; If reduction is 'mean', the reduced mean loss is returned; If reduction is 'sum', the summed loss is returned. Default: 'mean'

• name (str,Optional) – Name for the operation (optional, default is None). For more information, please refer to Name.

Call Parameters:

input (Tensor):Input tensor, the data type is float32 or float64. the shape is [N, *], N is batch size and * means any number of additional dimensions, available dtype is float32, float64.

positive (Tensor):Positive tensor, the data type is float32 or float64. The shape of label is the same as the shape of input.

negative (Tensor):Negative tensor, the data type is float32 or float64. The shape of label is the same as the shape of input.

Returns

Tensor. The tensor variable storing the triplet_margin_loss of input and positive and negative.

Examples

import paddle

input = paddle.to_tensor([[1, 5, 3], [0, 3, 2], [1, 4, 1]], dtype=paddle.float32)
negative = paddle.to_tensor([[2, 1, -3], [1, 1, -1], [4, -2, 1]], dtype=paddle.float32)
loss = triplet_margin_loss(input, positive, negative)
print(loss)
# Tensor([0.        , 0.57496738, 0.        ])

triplet_margin_loss = paddle.nn.TripletMarginLoss(margin=1.0, swap=True, reduction='mean', )
loss = triplet_margin_loss(input, positive, negative,)
print(loss)
# Tensor([0.19165580])

forward ( input, positive, negative )

Defines the computation performed at every call. Should be overridden by all subclasses.

Parameters
• *inputs (tuple) – unpacked tuple arguments

• **kwargs (dict) – unpacked dict arguments