mindspore.ops.multilabel_margin_loss

View Source On Gitee
mindspore.ops.multilabel_margin_loss(input, target, reduction='mean')[source]

Hinge loss for optimizing a multi-label classification.

Creates a criterion that optimizes a multi-label multi-classification hinge loss (margin-based loss) between input \(x\) (a 2D mini-batch Tensor) and output \(y\) (which is a 2D Tensor of target class indices). For each sample in the mini-batch:

\[\text{loss}(x, y) = \sum_{ij}\frac{\max(0, 1 - (x[y[j]] - x[i]))}{\text{x.size}(0)}\]

where \(x \in \left\{0, \; \cdots , \; \text{x.size}(0) - 1\right\}\), \(y \in \left\{0, \; \cdots , \; \text{y.size}(0) - 1\right\}\), \(0 \leq y[j] \leq \text{x.size}(0)-1\), and \(i \neq y[j]\) for all \(i\) and \(j\). \(y\) and \(x\) must have the same size. The criterion only considers a contiguous block of non-negative targets that starts at the front. This allows for different samples to have variable amounts of target classes.

Parameters
  • input (Tensor) – Predict data, \(x\) in the formula above. Tensor of shape \((C)\) or \((N, C)\), where \(N\) is the batch size and \(C\) is the number of classes. Data type must be float16 or float32.

  • target (Tensor) – Ground truth data, \(y\) in the formula above, with the same shape as input, data type must be int32 and label targets padded by -1.

  • 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

  • outputs (Union[Tensor, Scalar]) - The loss of MultilabelMarginLoss. If reduction is "none", its shape is \((N)\). Otherwise, a scalar value will be returned.

Raises
  • TypeError – If input or target is not a Tensor.

  • TypeError – If dtype of input is neither float16 nor float32.

  • TypeError – If dtype of target is not int32.

  • ValueError – If length of shape of input is neither 1 nor 2.

  • ValueError – If shape of input is not the same as target.

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

Supported Platforms:

Ascend GPU

Examples

>>> import mindspore
>>> import numpy as np
>>> from mindspore import Tensor, ops
>>> inputs = Tensor(np.array([[0.1, 0.2, 0.4, 0.8], [0.2, 0.3, 0.5, 0.7]]), mindspore.float32)
>>> target = Tensor(np.array([[1, 2, 0, 3], [2, 3, -1, 1]]), mindspore.int32)
>>> output = ops.multilabel_margin_loss(inputs, target)
>>> print(output)
0.325