mindspore.nn.L1Loss

查看源文件
class mindspore.nn.L1Loss(reduction='mean')[源代码]

L1Loss用于计算预测值和目标值之间的平均绝对误差。

假设 xy 为一维Tensor,长度 N ,则计算 xy 的loss,而不进行降维操作(即reduction参数设置为"none")。

公式如下:

(x,y)=L={l1,,lN},with ln=|xnyn|,

其中, N 为batch size。如果 reduction 不是"none",则:

(x,y)={mean(L),if reduction='mean';sum(L),if reduction='sum'.
参数:
  • reduction (str,可选) - 指定应用于输出结果的规约计算方式,可选 'none''mean''sum' ,默认值: 'mean'

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

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

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

输入:
  • logits (Tensor) - 预测值。可以是任意维度的Tensor。

  • labels (Tensor) - 目标值。通常情况下与 logits 的shape相同。但是如果 logitslabels 的shape不同,需要保证它们之间可以互相广播。

输出:

Tensor,类型为float。

异常:
  • ValueError - reduction 不为"mean"、"sum"或"none"。

  • ValueError - logitslabels 有不同的shape,且不能互相广播。

支持平台:

Ascend GPU CPU

样例:

>>> import mindspore
>>> from mindspore import Tensor, nn
>>> import numpy as np
>>> # Case 1: logits.shape = labels.shape = (3,)
>>> loss = nn.L1Loss()
>>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
>>> labels = Tensor(np.array([1, 2, 2]), mindspore.float32)
>>> output = loss(logits, labels)
>>> print(output)
0.33333334
>>> # Case 2: logits.shape = (3,), labels.shape = (2, 3)
>>> loss = nn.L1Loss(reduction='none')
>>> logits = Tensor(np.array([1, 2, 3]), mindspore.float32)
>>> labels = Tensor(np.array([[1, 1, 1], [1, 2, 2]]), mindspore.float32)
>>> output = loss(logits, labels)
>>> print(output)
[[0. 1. 2.]
 [0. 0. 1.]]