0%

torch | loss 函数

这里介绍一下 torchloss 函数的各种用法。


环境


  • python 3.6
  • torch 1.3.1

参考资料



loss 函数


L1Loss

torch.nn.L1Loss(size_average=None, reduce=None, reduction=’mean’)

计算 xy 的绝对值之差。

  • size_average 弃用
  • reduce 弃用

reduction 模式

  • none
  • mean
  • sum

如果 reductionnoneloss

$$ \ell(x, y) = L = {l_1,\dots,l_N}^\top, \quad
l_n = \left| x_n - y_n \right| $$

其中 Nbatch_size

如果是其他的模式,则为

$$ \ell(x, y) =
\begin{cases}
{mean}(L), & \text{if reduction} = \text{‘mean’} \\
{sum}(L), & \text{if reduction} = \text{‘sum’}
\end{cases} $$

例子

1
2
3
4
5
loss = nn.L1Loss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()

MSELoss

torch.nn.MSELoss(size_average=None, reduce=None, reduction=’mean’)

计算 xy 的均方误差。

  • size_average 弃用
  • reduce 弃用

reduction 模式

  • none
  • mean
  • sum

如果 reductionnoneloss

$$
\ell(x, y) = L = {l_1,\dots,l_N}^\top, \quad
l_n = \left( x_n - y_n \right)^2, $$

其中 Nbatch_size

如果是其他的模式,则为

$$
\ell(x, y) =
\begin{cases}
\operatorname{mean}(L), & \text{if reduction} = \text{‘mean’;}\\
\operatorname{sum}(L), & \text{if reduction} = \text{‘sum’.}
\end{cases}
$$

例子

1
2
3
4
5
loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()

CrossEntropyLoss

torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction=’mean’)

请我喝杯咖啡吧~