mindspore.ops.cosine_embedding_loss

View Source On Gitee
mindspore.ops.cosine_embedding_loss(input1, input2, target, margin=0.0, reduction='mean')[source]

CosineEmbeddingLoss creates a criterion to measure the similarity between two tensors using cosine distance.

Given two tensors \(input1\), \(input2\), and a Tensor label \(target\) with values 1 or -1:

\[\begin{split}loss(input1, input2, target) = \begin{cases} 1-cos(input1, input2), & \text{if } target = 1\\ max(0, cos(input1, input2)-margin), & \text{if } target = -1\\ \end{cases}\end{split}\]
Parameters
  • input1 (Tensor) – Tensor of shape \((N, *)\) where \(*\) means, any number of additional dimensions.

  • input2 (Tensor) – Tensor of shape \((N, *)\), same shape and dtype as input1.

  • target (Tensor) – Contains value 1 or -1. Suppose the shape of input1 is \((x_1, x_2, x_3, ..., x_R)\), then the shape of target must be \((x_1, x_3, x_4, ..., x_R)\).

  • margin (float, optional) – Should be in [-1.0, 1.0]. Default: 0.0.

  • reduction (str, optional) –

    Apply specific reduction method to the output: 'none' , 'mean' , 'sum' . Default: 'mean' .

    • 'none': no reduction will be applied.

    • 'mean': compute and return the mean of elements in the output.

    • 'sum': the output elements will be summed.

Returns

Tensor or Scalar, if reduction is "none", its shape is the same as target. Otherwise, a scalar value will be returned.

Raises
  • TypeError – If margin is not a float.

  • ValueError – If reduction is not one of 'none', 'mean', 'sum'.

  • ValueError – If margin is not in range [-1, 1].

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor, ops
>>> intput1 = Tensor(np.array([[0.3, 0.8], [0.4, 0.3]]), mindspore.float32)
>>> intput2 = Tensor(np.array([[0.4, 1.2], [-0.4, -0.9]]), mindspore.float32)
>>> target = Tensor(np.array([1, -1]), mindspore.int32)
>>> output = ops.cosine_embedding_loss(intput1, intput2, target)
>>> print(output)
0.0003425479