mindspore.nn.SoftmaxCrossEntropyWithLogits

查看源文件
class mindspore.nn.SoftmaxCrossEntropyWithLogits(sparse=False, reduction='none')[源代码]

计算预测值与真实值之间的交叉熵。

使用交叉熵损失函数计算出输入概率(使用softmax函数计算)和真实值之间的误差。

函数的输入是未标准化的值,表示为 x ,格式为 (N,C) ,以及相应的目标。

通常情况下,该函数的输入为各类别的分数值以及对应的目标值,输入格式是 (N,C)

对于每个实例 xii 的范围为0到N-1,则可得损失为:

(xi,c)=log(exp(xi[c])jexp(xi[j]))=xi[c]+log(jexp(xi[j]))

其中 xi 是一维的Tensor, c 为one-hot中等于1的位置。

说明

虽然目标值是互斥的,即目标值中只有一个为正,但预测的概率不为互斥。只要求输入的预测概率分布有效。

参数:
  • sparse (bool,可选) - 指定目标值是否使用稀疏格式。默认值: False

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

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

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

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

输入:
  • logits (Tensor) - shape (N,C) 的Tensor。数据类型为float16或float32。

  • labels (Tensor) - shape (N,) 的Tensor。如果 sparseTrue ,则 labels 的类型为int32或int64。否则, labels 的类型与 logits 的类型相同。

输出:

Tensor,一个shape和数据类型与logits相同的Tensor。

异常:
  • TypeError - sparse 不是bool。

  • TypeError - sparseTrue ,并且 labels 的dtype既不是int32,也不是int64。

  • TypeError - sparseFalse,并且 labels 的dtype既不是float16,也不是float32。

  • ValueError - reduction 不为 "mean""sum""none"

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore
>>> from mindspore import Tensor, nn
>>> import numpy as np
>>> # case 1: sparse=True
>>> loss = nn.SoftmaxCrossEntropyWithLogits(sparse=True)
>>> logits = Tensor(np.array([[3, 5, 6, 9, 12, 33, 42, 12, 32, 72]]), mindspore.float32)
>>> labels_np = np.array([1]).astype(np.int32)
>>> labels = Tensor(labels_np)
>>> output = loss(logits, labels)
>>> print(output)
[67.]
>>> # case 2: sparse=False
>>> loss = nn.SoftmaxCrossEntropyWithLogits(sparse=False)
>>> logits = Tensor(np.array([[3, 5, 6, 9, 12, 33, 42, 12, 32, 72]]), mindspore.float32)
>>> labels_np = np.array([[0, 0, 0, 0, 0, 0, 1, 0, 0, 0]]).astype(np.float32)
>>> labels = Tensor(labels_np)
>>> output = loss(logits, labels)
>>> print(output)
[30.]