mindspore.ops.cross_entropy

查看源文件
mindspore.ops.cross_entropy(input, target, weight=None, ignore_index=- 100, reduction='mean', label_smoothing=0.0)[源代码]

获取预测值和目标值之间的交叉熵损失。

cross_entropy方法支持两种不同的目标值(target):

  • 类别索引 (int),取值范围为 [0,C) ,其中 C 为类别数,当reduction为 'none' 时,交叉熵损失公式如下:

    (x,y)=L={l1,,lN},ln=wynlogexp(xn,yn)c=1Cexp(xn,c)1{ynignore_index}

    其中, x 表示预测值, y 表示目标值, w 表示权重,N表示batch size, c 限定范围为 [0,C1] ,表示类索引,其中 C 表示类的数量。

    若reduction不为 'none' (默认为 'mean' ),则

    (x,y)={n=1N1n=1Nwyn1{ynignore_index}ln,if reduction='mean',n=1Nln,if reduction='sum'.
  • 类别概率 (float),用于目标值为多个类别标签的情况。当reduction为 'none' 时,交叉熵损失公式如下:

    (x,y)=L={l1,,lN},ln=c=1Cwclogexp(xn,c)i=1Cexp(xn,i)yn,c

    其中, x 表示预测值, y 表示目标值, w 表示权重,N表示batch size, c 限定范围为 [0,C1] ,表示类索引,其中 C 表示类的数量。

    若reduction不为 'none' (默认为 'mean' ),则

    (x,y)={n=1NlnN,if reduction='mean',n=1Nln,if reduction='sum'.
参数:
  • input (Tensor) - 输入预测值,shape为 (N)(N,C)(N,C,H,W) (针对二维数据),或 (N,C,d1,d2,...,dK) (针对高维数据)。 input 需为对数概率。数据类型支持float16或float32。

  • target (Tensor) - 输入目标值。若目标值为类别索引,则shape为 ()(N)(N,d1,d2,...,dK) ,数据类型仅支持int32。 若目标值为类别概率,则shape为 (C,)(N,C)(N,C,d1,d2,...,dK) ,数据类型仅支持float32或float16。

  • weight (Tensor) - 指定各类别的权重。若值不为 None ,则shape为 (C,)。 数据类型仅支持float32或float16。默认 None

  • ignore_index (int) - 指定target中需要忽略的值(一般为填充值),使其不对梯度产生影响。默认 -100

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

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

    • 'mean':计算输出元素的加权平均值。

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

  • label_smoothing (float) - 标签平滑值,用于计算Loss时防止模型过拟合的正则化手段。取值范围为[0.0, 1.0]。默认 0.0

返回:

Tensor,数据类型与 input 相同。

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore as ms
>>> import numpy as np
>>> # Case 1: Indices labels
>>> inputs = ms.Tensor(np.random.randn(3, 5), ms.float32)
>>> target = ms.Tensor(np.array([1, 0, 4]), ms.int32)
>>> output = ms.ops.cross_entropy(inputs, target)
>>> # Case 2: Probability labels
>>> inputs = ms.Tensor(np.random.randn(3, 5), ms.float32)
>>> target = ms.Tensor(np.random.randn(3, 5), ms.float32)
>>> output = ms.ops.cross_entropy(inputs, target)