PyTorch torch.nn.CrossEntropyLoss function
PyTorch torch.nn Reference Manual
torch.nn.CrossEntropyLoss is the loss function used for multi-class classification in PyTorch.
It combines nn.LogSoftmax and nn.NLLLoss, and is commonly used for tasks such as image classification and text classification.
Function definition
torch.nn.CrossEntropyLoss(weight=None, ignore_index=-100, reduction='mean', label_smoothing=0.0)
Parameter Description:
weight(Tensor): Assigns different weights to each class, used in cases of class imbalance.ignore_index(int): Ignores the loss computation for the specified index. Defaults to -100.reduction(str): Loss reduction method. Options include'mean','sum','none'. Defaults to'mean'.label_smoothing(float): Label smoothing parameter, with a value between 0 and 1. Defaults to 0.
Mathematical principle
The formula for cross-entropy loss:
Loss = -log(exp(y_true) / sum(exp(y_i)))
That is, the higher the predicted probability of the correct class, the smaller the loss.
Usage examples
Example 1: Basic usage
Create and use cross-entropy loss:
Example
import
torch
import
torch.
nn
as
nn
Create the loss function
criterion
=
nn.
CrossEntropyLoss
(
)
Logits output by the model (unnormalized)
Shape: (batch_size, num_classes)
outputs
=
torch.
randn
(
4
,
10
)
Ground-truth labels
labels
=
torch.
tensor
(
[
2
,
5
,
1
,
7
]
)
Compute the loss
loss
=
criterion
(
outputs
,
labels
)
(
"Model output (logits):"
,
outputs
[
0
]
.
tolist
(
)
)
(
"Ground-truth labels:"
,
labels
[
0
]
.
item
(
)
)
(
"Cross-entropy loss:"
,
loss.
item
(
)
)
Example 2: Class weights
Handle class imbalance:
Example
import
torch
import
torch.
nn
as
nn
Class weights: give higher weight to minority classes
Assume 10 classes, with class 3 and class 7 being more important
weight
=
torch.
ones
(
10
)
weight
[
3
]
=
2.0
weight
[
7
]
=
2.0
criterion_weighted
=
nn.
CrossEntropyLoss
(
weight
=
weight
)
outputs
=
torch.
randn
(
4
,
10
)
labels
=
torch.
tensor
(
[
2
,
3
,
7
,
5
]
)
loss
=
criterion_weighted
(
outputs
,
labels
)
(
"Weighted cross-entropy loss:"
,
loss.
item
(
)
)
Example 3: Label smoothing
Use label smoothing to prevent overfitting:
Example
import
torch
import
torch.
nn
as
nn
Label smoothing: 0.1 means distributing 10% of the probability uniformly among other classes
criterion_smooth
=
nn.
CrossEntropyLoss
(
label_smoothing
=
0.1
)
outputs
=
torch.
randn
(
4
,
10
)
labels
=
torch.
tensor
(
[
2
,
5
,
1
,
7
]
)
loss
=
criterion_smooth
(
outputs
,
labels
)
(
"Loss with label smoothing:"
,
loss.
item
(
)
)
Comparison: without label smoothing
criterion
=
nn.
CrossEntropyLoss
(
)
loss_no_smooth
=
criterion
(
outputs
,
labels
)
(
"Loss without label smoothing:"
,
loss_no_smooth.
item
(
)
)
Example 4: Complete classification training pipeline
A complete model training example:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
A simple classification model
class
Classifier
(
nn.
Module
)
:
def
init
(
self
,
input_dim
=
784
,
num_classes
=
10
)
:
super
(
Classifier
,
self
)
.
init
(
)
self
.
fc
=
nn.
Sequential
(
nn.
Linear
(
input_dim
,
256
)
,
nn.
ReLU
(
)
,
nn.
Dropout
(
0.5
)
,
nn.
Linear
(
256
,
num_classes
)
)
def
forward
(
self
,
x
)
:
return
self
.
fc
(
x
)
Initialize the model and loss
model
=
Classifier
(
)
criterion
=
nn.
CrossEntropyLoss
(
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
0.001
)
Simulate training data
batch_size
=
32
x
=
torch.
randn
(
batch_size
,
784
)
Input
y
=
torch.
randint
(
0
,
10
,
(
batch_size
,
)
)
tag
Forward propagation
model.
train
(
)
outputs
=
model
(
x
)
loss
=
criterion
(
outputs
,
y
)
Backpropagation
optimizer.
zero_grad
(
)
loss.
backward
(
)
optimizer.
step
(
)
(
"Batch loss:"
,
loss.
item
(
)
)
Predict
model.
eval
(
)
with
torch.
no_grad
(
)
:
outputs
=
model
(
x
)
predictions
=
outputs.
argmax
(
dim
=
1
)
accuracy
=
(
predictions
==
y
)
.
float
(
)
.
mean
(
)
(
"Prediction accuracy:"
,
accuracy.
item
(
)
)
Example 5: Use of ignore_index
Ignore specific labels:
Example
import
torch
import
torch.
nn
as
nn
Ignore samples with label=-100
criterion
=
nn.
CrossEntropyLoss
(
ignore_index
=
100
)
outputs
=
torch.
randn
(
5
,
10
)
Some samples have label -100, indicating they should be ignored
labels
=
torch.
tensor
(
[
2
,
100
,
5
,
100
,
7
]
)
loss
=
criterion
(
outputs
,
labels
)
(
"Loss after ignoring special labels:"
,
loss.
item
(
)
)
Example 6: Different reduction methods
Control the loss reduction method:
Example
import
torch
import
torch.
nn
as
nn
outputs
=
torch.
randn
(
4
,
10
)
labels
=
torch.
tensor
(
[
2
,
5
,
1
,
7
]
)
mean: returns the average loss
loss_mean
=
nn.
CrossEntropyLoss
(
reduction
=
'mean'
)
(
outputs
,
labels
)
(
"mean:"
,
loss_mean.
item
(
)
)
sum: returns the total sum
loss_sum
=
nn.
CrossEntropyLoss
(
reduction
=
'sum'
)
(
outputs
,
labels
)
(
"sum:"
,
loss_sum.
item
(
)
)
none: returns the loss for each sample
loss_none
=
nn.
CrossEntropyLoss
(
reduction
=
'none'
)
(
outputs
,
labels
)
(
"none:"
,
loss_none.
tolist
(
)
)
Common questions
Q1: What is the difference between CrossEntropyLoss and NLLLoss?
CrossEntropyLoss = LogSoftmax + NLLLoss. It already includes softmax internally, so there is no need to add it manually.
Q2: Why not use softmax for the model output?
CrossEntropyLoss computes softmax internally; using logits directly improves numerical stability.
Q3: What scenarios is label smoothing suitable for?
Label smoothing is suitable when there are many classes; it can improve the model's generalization ability.
Use Cases
nn.CrossEntropyLoss Main application scenarios include:
- Image classification: Such as CIFAR-10, ImageNet
- Text classification: Sentiment analysis, topic classification
- Multi-class classification tasks: Any classification task with more than 2 classes
Note: Labels should be class indices (0 to num_classes-1), not one-hot encodings.