CrossEntropyLoss#
- class torch.nn.CrossEntropyLoss(weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', label_smoothing=0.0)[source]#
此标准计算输入逻辑和目标之间的交叉熵损失。
当训练一个具有 C 个类的分类问题时,此标准很有用。如果提供了可选参数
weight
,它应该是一个 1D Tensor,为每个类分配权重。当您的训练集不平衡时,这尤其有用。input 期望包含每个类的未归一化 logits(一般不需要是正数或总和为 1)。input 必须是大小为 的张量(对于未批量的输入),或 或 的张量,其中 ,最后一个在处理高维输入时很有用,例如计算 2D 图像的每像素交叉熵损失。
此标准期望的 target 应该包含:
类索引,范围在 之间,其中 是类的数量;如果指定了 ignore_index,此损失也接受该类索引(该索引不一定在类的范围内)。在这种情况下,未归约的(即
reduction
设置为'none'
)损失可以描述为:1{yn=ignore_index}其中 是输入, 是目标, 是权重, 是类的数量, 跨越了小批量维度,以及 for the K-dimensional case. If
reduction
is not'none'
(default'mean'
), then注意,这种情况等同于先对输入应用
LogSoftmax
,然后应用NLLLoss
。每个类别的概率;当每个小批量项需要超出单个类别的标签时很有用,例如用于混合标签、标签平滑等。对于这种情况,未约减(即
reduction
设置为'none'
)的损失可以描述为其中 是输入, 是目标, 是权重, 是类的数量, 跨越了小批量维度,以及 for the K-dimensional case. If
reduction
is not'none'
(default'mean'
), then
注意
请注意,当 target 包含类别索引时,此准则的性能通常更好,因为这允许优化计算。建议仅当单个类别标签对小批量项过于受限时,才提供 target 作为类别概率。
- 参数
weight (Tensor, optional) – 为每个类别手动设置的缩放权重。如果提供,则必须是大小为 C 的 Tensor。
size_average (bool, optional) – 已弃用(参见
reduction
)。默认情况下,损失在小批量中的每个损失元素上进行平均。请注意,对于某些损失,每个样本有多个元素。如果字段size_average
设置为False
,则损失将对每个小批量求和。当reduce
为False
时被忽略。默认值:True
ignore_index (int, optional) – 指定一个目标值,该值将被忽略,并且不计入输入梯度。当
size_average
为True
时,损失将根据非忽略的目标进行平均。请注意,ignore_index
仅在目标包含类别索引时适用。reduce (bool, optional) – 已弃用(参见
reduction
)。默认情况下,损失会根据size_average
在小批量中的观测值之间进行平均或求和。当reduce
为False
时,则返回每个批次元素的损失,并忽略size_average
。默认值:True
reduction (str, optional) – 指定应用于输出的约减:
'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 中所述。默认值:。
- 形状
输入:形状为 、 或 with in the case of K-dimensional loss.
Target:如果包含类别索引,则形状为 、 或 with in the case of K-dimensional loss, where each value should be between . The target data type is required to be long when using class indices. If containing class probabilities, the target must be the same shape as the input, and each value should be between . This means the target data type is required to be float when using class probabilities.
Output:如果 reduction 是 'none',则形状为 、 或 with in the case of K-dimensional loss, depending on the shape of the input. Otherwise, scalar.
其中
示例
>>> # 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()