这里介绍一下 torch 的 loss 函数的各种用法。
环境
- python 3.6
- torch 1.3.1
参考资料
loss 函数
L1Loss
torch.nn.L1Loss(size_average=None, reduce=None, reduction=’mean’)
计算 x 和 y 的绝对值之差。
- size_average 弃用
- reduce 弃用
reduction 模式
- none
- mean
- sum
如果 reduction 是 none ,loss 为
$$ \ell(x, y) = L = {l_1,\dots,l_N}^\top, \quad
l_n = \left| x_n - y_n \right| $$
其中 N 是 batch_size。
如果是其他的模式,则为
$$ \ell(x, y) =
\begin{cases}
{mean}(L), & \text{if reduction} = \text{‘mean’} \\
{sum}(L), & \text{if reduction} = \text{‘sum’}
\end{cases} $$
例子
1 | loss = nn.L1Loss() |
MSELoss
torch.nn.MSELoss(size_average=None, reduce=None, reduction=’mean’)
计算 x 和 y 的均方误差。
- size_average 弃用
- reduce 弃用
reduction 模式
- none
- mean
- sum
如果 reduction 是 none ,loss 为
$$
\ell(x, y) = L = {l_1,\dots,l_N}^\top, \quad
l_n = \left( x_n - y_n \right)^2, $$
其中 N 是 batch_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 | loss = nn.MSELoss() |
CrossEntropyLoss
torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction=’mean’)