npair_loss¶
- paddle.nn.functional. npair_loss ( anchor: Tensor, positive: Tensor, labels: Tensor, l2_reg: float = 0.002 ) Tensor [source]
-
Npair loss requires paired data. Npair loss has two parts: the first part is L2 regularizer on the embedding vector; the second part is cross entropy loss which takes the similarity matrix of anchor and positive as logits.
For more information, please refer to: Improved Deep Metric Learning with Multi class N pair Loss Objective
- Parameters
-
anchor (Tensor) – embedding vector for the anchor image. shape=[batch_size, embedding_dims], the data type is float32 or float64.
positive (Tensor) – embedding vector for the positive image. shape=[batch_size, embedding_dims], the data type is float32 or float64.
labels (Tensor) – 1-D tensor. shape=[batch_size], the data type is float32 or float64 or int64.
l2_reg (float, optional) – L2 regularization term on embedding vector, default: 0.002.
- Returns
-
A 0-D Tensor representing the npair loss, the data type is the same as anchor, the shape is [].
Examples
>>> import paddle >>> from typing import Literal >>> paddle.seed(2023) >>> dtype: Literal["float32"] = "float32" >>> anchor = paddle.rand(shape=(18, 6), dtype=dtype) >>> positive = paddle.rand(shape=(18, 6), dtype=dtype) >>> labels = paddle.rand(shape=(18,), dtype=dtype) >>> npair_loss = paddle.nn.functional.npair_loss(anchor, positive, labels, l2_reg = 0.002) >>> print(npair_loss) Tensor(shape=[], dtype=float32, place=Place(cpu), stop_gradient=True, 2.94269347)