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時忽略。預設值:Trueignore_index (int, optional) – 指定一個會被忽略且不計入輸入梯度的目標值。當
size_average為True時,損失會在未忽略的目標上平均。注意,ignore_index僅適用於目標包含類別索引的情況。預設值:-100reduce (bool, optional) – 已棄用(請參閱
reduction)。預設情況下,損失根據size_average在每個 minibatch 的觀測值上平均或求和。當reduce為False時,改為返回每個 batch 元素的損失,並忽略size_average。預設值:Truereduction (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()