mindspore.ops.SoftMarginLoss

View Source On Gitee
class mindspore.ops.SoftMarginLoss(reduction='mean')[source]

SoftMarginLoss operation.

Creates a criterion that optimizes a two-class classification logistic loss between input tensor \(x\) and target tensor \(y\) (containing 1 or -1).

\[\text{loss}(x, y) = \sum_i \frac{\log(1 + \exp(-y[i]*x[i]))}{\text{x.nelement}()}\]

where \(x.nelement()\) is the number of elements of x.

Parameters

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.

Inputs:
  • logits (Tensor) - Predict data. Data type must be float16 or float32.

  • labels (Tensor) - Ground truth data, with the same type and shape as logits.

Outputs:

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

Raises
  • TypeError – If logits or labels is not a Tensor.

  • TypeError – If dtype of logits or labels is neither float16 nor float32.

  • ValueError – If shape of logits is not the same as labels.

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

Supported Platforms:

Ascend GPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor, ops
>>> loss = ops.SoftMarginLoss()
>>> logits = Tensor(np.array([[0.3, 0.7], [0.5, 0.5]]), mindspore.float32)
>>> labels = Tensor(np.array([[-1, 1], [1, -1]]), mindspore.float32)
>>> output = loss(logits, labels)
>>> print(output)
0.6764238