torch.nn.functional.cross_entropy¶
- torch.nn.functional.cross_entropy(input, target, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='mean', label_smoothing=0.0)[source][source]¶
计算输入 logit 和目标之间的交叉熵损失。
详见
CrossEntropyLoss
。- 参数
input (Tensor) – 预测的未归一化 logit;支持的形状请参阅下面的“形状”部分。
target (Tensor) – 真实类别索引或类别概率;支持的形状请参阅下面的“形状”部分。
weight (Tensor, optional) – 为每个类别手动指定的缩放权重。如果提供,必须是大小为 C 的 Tensor。
size_average (bool, optional) – 已弃用(请参阅
reduction
)。默认情况下,损失会在 batch 中的每个损失元素上平均。注意,对于某些损失,每个样本有多个元素。如果字段size_average
设置为False
,损失则会在每个 minibatch 中求和。当 reduce 为False
时忽略。默认值:True
ignore_index (int, optional) – 指定一个会被忽略且不计入输入梯度的目标值。当
size_average
为True
时,损失会在未忽略的目标上平均。注意,ignore_index
仅适用于目标包含类别索引的情况。默认值:-100reduce (bool, optional) – 已弃用(请参阅
reduction
)。默认情况下,损失根据size_average
在每个 minibatch 的观测值上平均或求和。当reduce
为False
时,改为返回每个 batch 元素的损失,并忽略size_average
。默认值:True
reduction (str, optional) – 指定应用于输出的 reduction 类型:
'none'
|'mean'
|'sum'
。'none'
:不应用 reduction,'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 维损失,其中 且每个值应在 之间。如果包含类别概率,则形状与输入相同,且每个值应在 之间。
其中
示例
>>> # Example of target with class indices >>> input = torch.randn(3, 5, requires_grad=True) >>> target = torch.randint(5, (3,), dtype=torch.int64) >>> loss = F.cross_entropy(input, target) >>> loss.backward() >>> >>> # Example of target with class probabilities >>> input = torch.randn(3, 5, requires_grad=True) >>> target = torch.randn(3, 5).softmax(dim=1) >>> loss = F.cross_entropy(input, target) >>> loss.backward()