torch.nn.modules.loss 的源代码
import warnings
from .distance import PairwiseDistance
from .module import Module
from .. import functional as F
from .. import _reduction as _Reduction
from torch import Tensor
from typing import Callable, Optional
__all__ = ['L1Loss', 'NLLLoss', 'NLLLoss2d', 'PoissonNLLLoss', 'GaussianNLLLoss', 'KLDivLoss',
'MSELoss', 'BCELoss', 'BCEWithLogitsLoss', 'HingeEmbeddingLoss', 'MultiLabelMarginLoss',
'SmoothL1Loss', 'HuberLoss', 'SoftMarginLoss', 'CrossEntropyLoss', 'MultiLabelSoftMarginLoss',
'CosineEmbeddingLoss', 'MarginRankingLoss', 'MultiMarginLoss', 'TripletMarginLoss',
'TripletMarginWithDistanceLoss', 'CTCLoss']
class _Loss(Module):
reduction: str
def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
super().__init__()
if size_average is not None or reduce is not None:
self.reduction: str = _Reduction.legacy_get_string(size_average, reduce)
else:
self.reduction = reduction
class _WeightedLoss(_Loss):
def __init__(self, weight: Optional[Tensor] = None, size_average=None, reduce=None, reduction: str = 'mean') -> None:
super().__init__(size_average, reduce, reduction)
self.register_buffer('weight', weight)
self.weight: Optional[Tensor]
[docs]class L1Loss(_Loss):
r"""创建一个标准,用于衡量输入 :math:`x` 和目标 :math:`y` 中每个元素之间的平均绝对误差(MAE)。
未减少的(即当 :attr:`reduction` 设置为 ``'none'`` 时)损失可以描述为:
.. math::
\ell(x, y) = L = \{l_1,\dots,l_N\}^\top, \quad
l_n = \left| x_n - y_n \right|,
其中 :math:`N` 是批次大小。如果 :attr:`reduction` 不是 ``'none'``
(默认 ``'mean'``),则:
.. math::
\ell(x, y) =
\begin{cases}
\operatorname{mean}(L), & \text{if reduction} = \text{`mean';}\\
\operatorname{sum}(L), & \text{if reduction} = \text{`sum'.}
\end{cases}
:math:`x` 和 :math:`y` 是任意形状的张量,总共有 :math:`n` 个元素。
求和操作仍然对所有元素进行操作,并除以 :math:`n`。
如果设置 ``reduction = 'sum'``,则可以避免除以 :math:`n`。
支持实值和复值输入。
参数:
size_average (bool, 可选): 已弃用(参见 :attr:`reduction`)。默认情况下,
损失在批次的每个损失元素上进行平均。请注意,对于某些损失,每个样本有多个元素。如果字段 :attr:`size_average`
设置为 ``False``,则损失改为对每个小批次进行求和。当 :attr:`reduce` 为 ``False`` 时忽略。默认值:``True``
reduce (bool, 可选): 已弃用(参见 :attr:`reduction`)。默认情况下,
损失根据 :attr:`size_average` 在每个小批次上进行平均或求和。当 :attr:`reduce` 为 ``False`` 时,返回每个批次元素的损失,并忽略 :attr:`size_average`。默认值:``True``
reduction (str, 可选): 指定应用于输出的减少方式:
``'none'`` | ``'mean'`` | ``'sum'``。``'none'``:不应用减少,
``'mean'``:输出的总和将除以输出中的元素数量,``'sum'``:输出将被求和。注意::attr:`size_average`
和 :attr:`reduce` 正在被弃用,在此期间,指定其中任何一个参数将覆盖 :attr:`reduction`。默认值:``'mean'``
形状:
- 输入: :math:`(*)`,其中 :math:`*` 表示任意数量的维度。
- 目标: :math:`(*)`,与输入形状相同。
- 输出: 标量。如果 :attr:`reduction` 为 ``'none'``,则为
:math:`(*)`,与输入形状相同。
示例::
>>> loss = nn.L1Loss()
>>> input = torch.randn(3, 5, requires_grad=True)
>>> target = torch.randn(3, 5)
>>> output = loss(input, target)
>>> output.backward()
"""
__constants__ = ['reduction']
def __init__(self, size_average=None, reduce=None, reduction: str = 'mean') -> None:
super().__init__(size_average, reduce, reduction)
def forward(self, input: Tensor, target: Tensor) -> Tensor:
return F.l1_loss(input, target, reduction=self.reduction)
[docs]class NLLLoss(_WeightedLoss):
r"""负对数似然损失。它对于训练具有 `C` 个类别的分类问题非常有用。