mindspore.ops.hinge_embedding_loss
- mindspore.ops.hinge_embedding_loss(inputs, targets, margin=1.0, reduction='mean')[source]
Hinge Embedding Loss. Compute the output according to the input elements. Measures the loss given an input tensor x and a labels tensor y (containing 1 or -1). This is usually used for measuring the similarity between two inputs.
The loss function for \(n\)-th sample in the mini-batch is
\[\begin{split}l_n = \begin{cases} x_n, & \text{if}\; y_n = 1,\\ \max \{0, \Delta - x_n\}, & \text{if}\; y_n = -1, \end{cases}\end{split}\]and the total loss functions is
\[\begin{split}\ell(x, y) = \begin{cases} \operatorname{mean}(L), & \text{if reduction} = \text{'mean';}\\ \operatorname{sum}(L), & \text{if reduction} = \text{'sum'.} \end{cases}\end{split}\]where \(L = \{l_1,\dots,l_N\}^\top\).
- Parameters
inputs (Tensor) – Tensor of shape \((*)\) where \(*\) means any number of dimensions.
targets (Tensor) – Same shape as the logits, contains -1 or 1.
margin (float) – Threshold defined by Hinge Embedding Loss \(margin\). Represented as \(\Delta\) in the formula. Default: 1.0.
reduction (str) – Specify the computing method to be applied to the outputs: ‘none’, ‘mean’, or ‘sum’. Default: ‘mean’.
- Returns
Tensor or Tensor scalar, the computed loss depending on reduction.
- Raises
TypeError – If inputs is not a Tensor.
TypeError – If targets is not a Tensor.
TypeError – If margin is not a float.
ValueError – If targets does not have the same shape as inputs.
ValueError – If reduction is not one of ‘none’, ‘mean’, ‘sum’.
- Supported Platforms:
Ascend
GPU
CPU
Examples
>>> import numpy as np >>> import mindspore.common.dtype as mstype >>> import mindspore.ops as ops >>> from mindspore import Tensor >>> arr1 = np.array([0.9, -1.2, 2, 0.8, 3.9, 2, 1, 0, -1]).reshape((3, 3)) >>> arr2 = np.array([1, 1, -1, 1, -1, 1, -1, 1, 1]).reshape((3, 3)) >>> logits = Tensor(arr1, mstype.float32) >>> labels = Tensor(arr2, mstype.float32) >>> loss = ops.hinge_embedding_loss(logits, labels, margin=1.0, reduction='mean') >>> print(loss) 0.16666666