mindspore.ops.margin_ranking_loss

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

MarginRankingLoss creates a criterion that measures the loss.

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

\[\text{loss}(input1, input2, target) = \max(0, -target * (input1 - input2) + \text{margin})\]
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_2, x_3, ..., x_R)\).

  • margin (float, optional) – Specify the adjustment factor of the operation. 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 input1. Otherwise, a scalar value will be returned.

Raises
  • TypeError – If margin is not a float.

  • TypeError – If input1, input2 or target is not a Tensor.

  • TypeError – If the types of input1 and input2 are inconsistent.

  • TypeError – If the types of input1 and target are inconsistent.

  • ValueError – If the shape of input1 and input2 are inconsistent.

  • ValueError – If the shape of input1 and target are inconsistent.

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

Supported Platforms:

Ascend GPU CPU

Examples

>>> import mindspore as ms
>>> from mindspore import Tensor, ops
>>> import numpy as np
>>> input1 = Tensor(np.array([0.3864, -2.4093, -1.4076]), ms.float32)
>>> input2 = Tensor(np.array([-0.6012, -1.6681, 1.2928]), ms.float32)
>>> target = ops.Sign()(Tensor(np.array([-2, -2, 3]), ms.float32))
>>> output = ops.margin_ranking_loss(input1, input2, target)
>>> print(output)
1.2293333