mindspore.ops.multi_label_margin_loss

mindspore.ops.multi_label_margin_loss(inputs, 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
  • inputs (Tensor) – Predict data. 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, with the same shape as inputs, 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’: the sum of the output will be divided by the number of elements in the output.

    • ’sum’: the output 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 inputs or target is not a Tensor.

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

  • TypeError – If dtype of target is not int32.

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

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

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

Supported Platforms:

Ascend GPU

Examples

>>> 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.multi_label_margin_loss(inputs, target)
>>> print(output)
(Tensor(shape=[], dtype=Float32, value= 0.325), Tensor(shape=[2, 4], dtype=Int32, value=
[[1, 1, 1, 1], [0, 0, 1, 1]]))