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]#
计算输入 logits 和 target 之间的交叉熵损失。
有关详细信息,请参阅
CrossEntropyLoss
。- 参数
input (Tensor) – 预测的未归一化 logits;有关支持的形状,请参阅下面的“形状”部分。
target (Tensor) – 真实的类别索引或类别概率;有关支持的形状,请参阅下面的“形状”部分。
weight (Tensor, optional) – 手动为每个类别设置重缩放权重。如果提供,必须是一个大小为 C 的 Tensor。
size_average (bool, optional) – 已弃用(请参阅
reduction
)。ignore_index (int, optional) – 指定一个被忽略的目标值,不对输入梯度做出贡献。当
size_average
为True
时,损失将根据非忽略的目标进行平均。请注意,ignore_index
仅在 target 包含类别索引时适用。默认值:-100reduce (bool, optional) – 已弃用(请参阅
reduction
)。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 中所述。默认值:。
- 返回类型
- 形状
输入:形状为 、 或 的 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()