mindspore.nn.HingeEmbeddingLoss

查看源文件
class mindspore.nn.HingeEmbeddingLoss(margin=1.0, reduction='mean')[源代码]

Hinge Embedding 损失函数。根据输入 logitslabels (只包含1或-1)计算Hinge Embedding损失值。通常被用来衡量两个输入之间的相似度。

mini-batch中的第 \(n\) 个样例的损失函数为:

\[\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}\]

总损失值为:

\[\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}\]

其中 \(L = \{l_1,\dots,l_N\}^\top\)

参数:
  • margin (float, int) - Hinge Embedding Loss公式定义的阈值 \(margin\)。公式中表示为 \(\Delta\)。默认值: 1.0

  • reduction (str,可选) - 指定应用于输出结果的规约计算方式,可选 'none''mean''sum' ,默认值: 'mean'

    • "none":不应用规约方法。

    • "mean":计算输出元素的平均值。

    • "sum":计算输出元素的总和。

输入:
  • logits (Tensor) - 预测值,公式中表示为 \(x\),shape为 \((*)\)\(*\) 代表着任意数量的维度。

  • labels (Tensor) - 标签值,公式中表示为 \(y\),和 logits 具有相同shape,包含1或-1。

返回:

Tensor或Tensor scalar,根据 \(reduction\) 计算的loss。

异常:
  • TypeError - logits 不是Tensor。

  • TypeError - labels 不是Tensor。

  • TypeError - margin 不是float或int。

  • ValueError - labelslogits shape不一致且不能广播。

  • ValueError - reduction 不是 "none""mean" 或者 "sum"

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore as ms
>>> import mindspore.nn as nn
>>> import numpy as np
>>> 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 = ms.Tensor(arr1, ms.float32)
>>> labels = ms.Tensor(arr2, ms.float32)
>>> loss = nn.HingeEmbeddingLoss(reduction='mean')
>>> output = loss(logits, labels)
>>> print(output)
0.16666667