CrossEntropyLoss#
- class torch.nn.modules.loss.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', label_smoothing=0.0)[源代码]#
此准则计算输入 logits 和 target 之间的交叉熵损失。
当训练一个包含 C 个类别的分类问题时,该损失函数非常有用。如果提供了可选参数
weight,它应该是一个 1D Tensor,用于为每个类别分配权重。这在训练集不平衡时特别有用。预期 input 包含每个类别的未归一化对数几率(logits)(通常不需要为正值或总和为 1)。对于未批处理的输入,input 必须是一个大小为 的张量;对于批处理输入,则为 或 ,其中 表示 K 维情况。后者对于更高维度的输入很有用,例如计算 2D 图像的逐像素交叉熵损失。
此准则期望的 target 应包含以下内容之一:
范围在 内的类别索引,其中 是类别的数量;如果指定了 ignore_index,则该损失函数也接受此类别索引(该索引不一定在类别范围内)。在此情况下,未约简(即
reduction设置为'none')的损失可以描述为:其中 是输入, 是目标, 是权重, 是类别数量, 跨越小批量维度以及 (对于 K 维情况)。如果
reduction不是'none'(默认值为'mean'),则:注意,这种情况等同于对输入应用
LogSoftmax,然后再应用NLLLoss。每个类别的概率;当需要超出每个小批量项单一类别的标签时(例如混合标签、标签平滑等),此功能非常有用。在此情况下,未约简(即
reduction设置为'none')的损失可以描述为:其中 是输入, 是目标, 是权重, 是类别数量, 跨越小批量维度以及 (对于 K 维情况)。如果
reduction不是'none'(默认值为'mean'),则:
注意
当 target 包含类别索引时,此准则的性能通常更好,因为这允许进行优化计算。仅当每个小批量(minibatch)项目只有一个类标签的限制过于苛刻时,才考虑以类别概率的形式提供 target。
- 参数:
weight (Tensor, 可选) – 给每个类别手动分配的权重。如果提供,必须是大小为 C 的 Tensor。
size_average (bool, optional) – 已弃用 (参见
reduction)。默认情况下,损失值在批次中的每个损失元素上取平均值。请注意,对于某些损失,每个样本有多个元素。如果字段size_average设置为False,则损失值在每个小批次中而是求和。当reduce为False时忽略。默认值:Trueignore_index (int, 可选) – 指定一个被忽略的目标值,该值不参与输入梯度的计算。当
size_average为True时,损失函数会在非忽略的目标上取平均值。注意,ignore_index仅在 target 包含类别索引时适用。reduce (bool, optional) – 已弃用 (参见
reduction)。默认情况下,损失值在每个小批次中根据size_average对观测值进行平均或求和。当reduce为False时,返回每个批次元素的损失值,并忽略size_average。默认值:Truereduction (str, 可选) – 指定应用于输出的缩减方式:
'none'|'mean'|'sum'。'none':不应用缩减,'mean':取输出的加权平均值,'sum':对输出进行求和。注意:size_average和reduce正在弃用过程中,在此期间,指定这两个参数中的任意一个都会覆盖reduction。默认值:'mean'label_smoothing (float, optional) – 一个在 [0.0, 1.0] 范围内的浮点数。指定计算损失时的平滑量,0.0 表示无平滑。目标变为原始真实标签和均匀分布的混合,如 Rethinking the Inception Architecture for Computer Vision 中所述。默认值:。
- 形状
输入:形状为 、 或 ,其中 表示 K 维损失的情况。
目标:如果包含类别索引,形状为 、 或 ,其中 表示 K 维损失的情况,且每个值应在 之间。使用类别索引时,目标数据类型必须为长整型(long)。如果包含类别概率,则目标的形状必须与输入相同,且每个值应在 之间。这意味着使用类别概率时,目标数据类型必须为浮点型(float)。注意,PyTorch 不会严格强制执行类别概率的约束,用户有责任确保
target包含有效的概率分布(更多详细信息请参阅下方的示例部分)。输出:如果 reduction 为 ‘none’,则输出形状为 、 或 ,取决于输入的形状;否则为标量。
其中
示例
>>> # Example of target with class indices >>> loss = nn.CrossEntropyLoss() >>> input = torch.randn(3, 5, requires_grad=True) >>> target = torch.empty(3, dtype=torch.long).random_(5) >>> output = loss(input, target) >>> output.backward() >>> >>> # Example of target with class probabilities >>> input = torch.randn(3, 5, requires_grad=True) >>> target = torch.randn(3, 5).softmax(dim=1) >>> output = loss(input, target) >>> output.backward()
注意
当
target包含类别概率时,它应该由软标签(soft labels)组成——即每个target条目都应表示给定数据样本在可能类别上的概率分布,单个概率介于[0,1]之间,且整个分布的总和为 1。这就是为什么在上述类别概率示例中对target应用了softmax()函数的原因。PyTorch 不会验证
target中提供的值是否在[0,1]范围内,也不验证每个数据样本的分布总和是否为1。程序不会引发任何警告,用户有责任确保target包含有效的概率分布。提供任意值可能会导致训练期间产生误导性的损失值和不稳定的梯度。示例
>>> # Example of target with incorrectly specified class probabilities >>> loss = nn.CrossEntropyLoss() >>> torch.manual_seed(283) >>> input = torch.randn(3, 5, requires_grad=True) >>> target = torch.randn(3, 5) >>> # Provided target class probabilities are not in range [0,1] >>> target tensor([[ 0.7105, 0.4446, 2.0297, 0.2671, -0.6075], [-1.0496, -0.2753, -0.3586, 0.9270, 1.0027], [ 0.7551, 0.1003, 1.3468, -0.3581, -0.9569]]) >>> # Provided target class probabilities do not sum to 1 >>> target.sum(axis=1) tensor([2.8444, 0.2462, 0.8873]) >>> # No error message and possible misleading loss value >>> loss(input, target).item() 4.6379876136779785 >>> >>> # Example of target with correctly specified class probabilities >>> # Use .softmax() to ensure true probability distribution >>> target_new = target.softmax(dim=1) >>> # New target class probabilities all in range [0,1] >>> target_new tensor([[0.1559, 0.1195, 0.5830, 0.1000, 0.0417], [0.0496, 0.1075, 0.0990, 0.3579, 0.3860], [0.2607, 0.1355, 0.4711, 0.0856, 0.0471]]) >>> # New target class probabilities sum to 1 >>> target_new.sum(axis=1) tensor([1.0000, 1.0000, 1.0000]) >>> loss(input, target_new).item() 2.55349063873291