快捷方式

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_averageTrue 時,損失會在未忽略的目標上平均。注意,ignore_index 僅適用於目標包含類別索引的情況。預設值:-100

  • reduce (bool, optional) – 已棄用(請參閱 reduction)。預設情況下,損失根據 size_average 在每個 minibatch 的觀測值上平均或求和。當 reduceFalse 時,改為返回每個 batch 元素的損失,並忽略 size_average。預設值:True

  • reduction (str, optional) – 指定應用於輸出的 reduction 型別:'none' | 'mean' | 'sum''none':不應用 reduction,'mean':輸出的總和將除以輸出中的元素數量,'sum':輸出將被求和。注意:size_averagereduce 正在被棄用,同時,指定這兩個引數中的任何一個都將覆蓋 reduction。預設值:'mean'

  • label_smoothing (float, optional) – 一個介於 [0.0, 1.0] 之間的浮點數。指定計算損失時應用的平滑量,其中 0.0 表示不進行平滑。目標變為原始真實標籤和均勻分佈的混合,如 Rethinking the Inception Architecture for Computer Vision 中所述。預設值:0.00.0

返回型別

Tensor

形狀
  • 輸入:形狀 (C)(C), (N,C)(N, C)(N,C,d1,d2,...,dK)(N, C, d_1, d_2, ..., d_K),對於 K 維損失,其中 K1K \geq 1

  • 目標:如果包含類別索引,形狀為 ()(), (N)(N)(N,d1,d2,...,dK)(N, d_1, d_2, ..., d_K),對於 K 維損失,其中 K1K \geq 1 且每個值應在 [0,C)[0, C) 之間。如果包含類別機率,則形狀與輸入相同,且每個值應在 [0,1][0, 1] 之間。

其中

C=類別數量N=批次大小\begin{aligned} C ={} & \text{number of classes} \\ N ={} & \text{batch size} \\ \end{aligned}

示例

>>> # 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()

文件

訪問 PyTorch 的全面開發者文件

檢視文件

教程

獲取面向初學者和高階開發者的深度教程

檢視教程

資源

查詢開發資源並獲得問題解答

檢視資源