PyTorch Loss Functions
The loss function measures the gap between a model's predictions and the true values; it is the core guide for neural network training -- the optimizer updates model parameters by minimizing the loss function.
PyTorch has torch.nn more than ten common loss functions built into its module, covering major task types such as classification, regression, and ranking.
1. Loss function basics
Basic Usage
All PyTorch loss functions are nn.Module subclasses, used in a consistent way:
Example
import
torch
import
torch.
nn
as
nn
1. Instantiate the loss function
criterion
=
nn.
CrossEntropyLoss
(
)
2. Compute the loss (predictions first, true values second)
loss
=
criterion
(
predictions
,
targets
)
3. Backpropagation
loss.
backward
(
)
Shape conventions for predictions
Different loss functions have different input shape requirements, which is where beginners most often make mistakes:
| Loss function | Prediction (input) shape | Label (target) shape |
|---|---|---|
CrossEntropyLoss |
(N, C) Raw logits |
(N,) Integer class indices |
BCELoss |
(N,) Probabilities after Sigmoid |
(N,) 0/1 floating point numbers |
BCEWithLogitsLoss |
(N,) Raw logits |
(N,) 0/1 floating point numbers |
MSELoss |
(N,) Any real number |
(N,) Any real number |
NLLLoss |
(N, C) Probabilities after log_softmax |
(N,) Integer class indices |
N = batch size, C = number of classes
2. Loss functions for classification tasks
2.1 CrossEntropyLoss (cross entropy loss)
The most commonly used multi-class loss function,internally performs Softmax + log + negative signautomatically, with no need to manually apply Softmax to model outputs.
Mathematical formula:
Loss = -sum(y_c * log(p_c))
where p_c = exp(x_c) / sum_j exp(x_j) is the Softmax output.
Example
import
torch
import
torch.
nn
as
nn
criterion
=
nn.
CrossEntropyLoss
(
)
Model output: raw logits, shape (batch_size, num_classes)
No need to apply Softmax in advance!
predictions
=
torch.
tensor
(
[
[
2.0
,
0.5
,
0.3
]
,
Sample 1, most likely class 0
[
0.1
,
3.0
,
0.2
]
,
Sample 2, most likely class 1
[
0.2
,
0.1
,
4.0
]
,
Sample 3, most likely class 2
]
)
Labels: integer class indices, shape (batch_size,)
targets
=
torch.
tensor
(
[
0
,
1
,
2
]
)
loss
=
criterion
(
predictions
,
targets
)
(
f
"Loss: {loss.item():.4f}"
)
Loss: 0.1763
Supports soft labels (Label Smoothing):
Example
Label smoothing, alleviates overfitting, commonly used in image classification competitions
criterion
=
nn.
CrossEntropyLoss
(
label_smoothing
=
0.1
)
Also supports passing soft labels (probability distributions) directly
soft_targets
=
torch.
tensor
(
[
[
0.9
,
0.05
,
0.05
]
,
[
0.05
,
0.9
,
0.05
]
,
]
)
predictions
=
torch.
randn
(
2
,
3
)
loss
=
criterion
(
predictions
,
soft_targets
)
Applicable Scenarios:All multi-class tasks: multi-class (cat/dog/bird), image classification, text classification, etc.
2.2 BCELoss (binary cross entropy loss)
Specifically forBinary ClassificationorMulti-label Classificationtasks; the input must be probability values after Sigmoid processing (0~1).
Mathematical formula:
Loss = -[y * log(p) + (1-y) * log(1-p)]
Example
criterion
=
nn.
BCELoss
(
)
Model output must first pass through Sigmoid, with range (0, 1)
raw_output
=
torch.
tensor
(
[
2.0
,
1.0
,
0.5
,
3.0
]
)
predictions
=
torch.
sigmoid
(
raw_output
)
[0.88, 0.27, 0.62, 0.05]
Labels: floating point 0.0 or 1.0
targets
=
torch.
tensor
(
[
1.0
,
0.0
,
1.0
,
0.0
]
)
loss
=
criterion
(
predictions
,
targets
)
(
f
"Loss: {loss.item():.4f}"
)
Loss: 0.2824
Multi-label classification (each sample can belong to multiple classes)
predictions shape: (batch_size, num_labels)
predictions_ml
=
torch.
sigmoid
(
torch.
randn
(
4
,
5
)
)
targets_ml
=
torch.
randint
(
0
,
2
,
(
4
,
5
)
)
.
float
(
)
loss_ml
=
criterion
(
predictions_ml
,
targets_ml
)
BCELossRequires input in the (0, 1) range; passing raw logits can cause numerical instability or even NaN. The improved version below is recommended,BCEWithLogitsLoss.
2.3 BCEWithLogitsLoss
BCELoss (the improved version ofinternally performs Sigmoidautomatically, with better numerical stability and recommended first.
Example
criterion
=
nn.
BCEWithLogitsLoss
(
)
Pass raw logits directly, no manual Sigmoid needed
predictions
=
torch.
tensor
(
[
2.0
,
1.0
,
0.5
,
3.0
]
)
targets
=
torch.
tensor
(
[
1.0
,
0.0
,
1.0
,
0.0
]
)
loss
=
criterion
(
predictions
,
targets
)
(
f
"Loss: {loss.item():.4f}"
)
Equivalent to (but with better numerical stability):
loss = BCELoss(Sigmoid(predictions), targets)
With positive sample weights (handling class imbalance):
Example
pos_weight: positive sample weight; larger values focus more on positive samples
For example, if negative samples are 10 times the positive ones, set pos_weight=10
pos_weight
=
torch.
tensor
(
[
10.0
]
)
criterion
=
nn.
BCEWithLogitsLoss
(
pos_weight
=
pos_weight
)
Applicable Scenarios:Binary classification (spam detection), multi-label classification (multi-tag article tagging), object detection (foreground/background).
2.4 NLLLoss (negative log likelihood loss)
Requires manually applying log_softmaxto model outputs, offering more flexibility.CrossEntropyLoss = LogSoftmax + NLLLoss.
Example
criterion
=
nn.
NLLLoss
(
)
Must manually apply log_softmax first
raw_output
=
torch.
randn
(
4
,
3
)
(batch, num_classes)
log_probs
=
torch.
log_softmax
(
raw_output
,
dim
=
1
)
targets
=
torch.
tensor
(
[
0
,
2
,
1
,
0
]
)
loss
=
criterion
(
log_probs
,
targets
)
Use cases:When log probabilities are needed in intermediate steps (such as CTC, Beam Search); otherwise prefer
CrossEntropyLoss.
3. Loss functions for regression tasks
3.1 MSELoss (mean squared error)
The most classic regression loss, very sensitive tolarge errors(because squaring amplifies the effect of large errors).
Mathematical formula:
MSELoss = (1/N) * sum((y_i - y_hat_i)^2)
Example
criterion
=
nn.
MSELoss
(
)
predictions
=
torch.
tensor
(
[
2.5
,
0.5
,
2.0
,
8.0
]
)
targets
=
torch.
tensor
(
[
3.0
,
0.5
,
2.0
,
7.0
]
)
loss
=
criterion
(
predictions
,
targets
)
(
f
"MSE Loss: {loss.item():.4f}"
)
MSE Loss: 0.3750
Manual verification
manual
=
(
(
predictions - targets
)
**
2
)
.
mean
(
)
(
f
"Manual calculation: {manual.item():.4f}"
)
0.3750
Applicable Scenarios:Works well for continuous regression such as house price and temperature prediction when there are no obvious outliers.
3.2 L1Loss (mean absolute error)
locksMore robust to outliers, because it takes absolute values instead of squares, so large errors are not overly amplified.
Mathematical formula:
L1Loss = (1/N) * sum(|y_i - y_hat_i|)
Example
criterion
=
nn.
L1Loss
(
)
predictions
=
torch.
tensor
(
[
2.5
,
0.5
,
2.0
,
8.0
]
)
targets
=
torch.
tensor
(
[
3.0
,
0.5
,
2.0
,
7.0
]
)
loss
=
criterion
(
predictions
,
targets
)
(
f
"L1 Loss: {loss.item():.4f}"
)
L1 Loss: 0.5000
3.3 SmoothL1Loss (Huber loss)
Combines the advantages of MSE and L1: uses MSE for small errors (smooth, stable gradients) and L1 for large errors (resistant to outliers). The standard loss in object detection (Faster R-CNN).
Mathematical formula:
SmoothL1(x) = 0.5*x^2 if |x| < 1, else |x| - 0.5
Example
criterion
=
nn.
SmoothL1Loss
(
)
predictions
=
torch.
tensor
(
[
2.5
,
0.5
,
2.0
,
8.0
]
)
targets
=
torch.
tensor
(
[
3.0
,
0.5
,
2.0
,
7.0
]
)
loss
=
criterion
(
predictions
,
targets
)
(
f
"SmoothL1 Loss: {loss.item():.4f}"
)
Comparison of three regression losses:
Example
import
torch
import
torch.
nn
as
nn
predictions
=
torch.
tensor
(
[
0.0
,
1.0
,
5.0
,
10.0
]
)
Simulate errors of different sizes
targets
=
torch.
zeros
(
4
)
for
name
,
fn
in
[
(
"MSELoss"
,
nn.
MSELoss
(
reduction
=
'none'
)
)
,
(
"L1Loss"
,
nn.
L1Loss
(
reduction
=
'none'
)
)
,
(
"SmoothL1"
,
nn.
SmoothL1Loss
(
reduction
=
'none'
)
)
]
:
losses
=
fn
(
predictions
,
targets
)
(
f
"{name:12s}: {[f'{l:.2f}' for l in losses.tolist()]}"
)
Output example:
MSELoss : ['0.00', '1.00', '25.00', '100.00'] # 大误差被平方放大
L1Loss : ['0.00', '1.00', '5.00', '10.00'] # 线性增长
SmoothL1 : ['0.00', '0.50', '4.50', '9.50'] # 中间值
Applicable Scenarios:Bounding box regression in object detection, depth estimation, and other regression tasks with both small errors and outliers.
4. Advanced loss functions
4.1 HuberLoss
SmoothL1Loss The general version, allowing a custom switching threshold delta(default 1.0).
Example
delta controls the switching point between MSE and L1
criterion
=
nn.
HuberLoss
(
delta
=
1.5
)
predictions
=
torch.
randn
(
10
)
targets
=
torch.
randn
(
10
)
loss
=
criterion
(
predictions
,
targets
)
4.2 KLDivLoss (KL divergence)
Measures the difference between two probability distributions, commonly used inKnowledge distillationandvariational autoencoders (VAE).
Mathematical formula:
KL(P || Q) = sum(P(i) * log(P(i) / Q(i)))
Example
criterion
=
nn.
KLDivLoss
(
reduction
=
'batchmean'
)
input must be log probabilities, target is ordinary probabilities
log_predictions
=
torch.
log_softmax
(
torch.
randn
(
4
,
5
)
,
dim
=
1
)
targets
=
torch.
softmax
(
torch.
randn
(
4
,
5
)
,
dim
=
1
)
loss
=
criterion
(
log_predictions
,
targets
)
(
f
"KL Div Loss: {loss.item():.4f}"
)
Typical usage in knowledge distillation:
Example
temperature
=
4.0
Temperature coefficient; larger values soften more
Teacher model output
teacher_logits
=
torch.
randn
(
32
,
10
)
Student model output
student_logits
=
torch.
randn
(
32
,
10
)
soft_labels
=
torch.
softmax
(
teacher_logits / temperature
,
dim
=
1
)
soft_preds
=
torch.
log_softmax
(
student_logits / temperature
,
dim
=
1
)
distill_loss
=
nn.
KLDivLoss
(
reduction
=
'batchmean'
)
(
soft_preds
,
soft_labels
)
distill_loss *
=
temperature **
2
Restore gradient scale
4.3 MarginRankingLoss (ranking loss)
Determines the relative order of two inputs, commonly used inlearning to rankandsimilarity learning.
Example
criterion
=
nn.
MarginRankingLoss
(
margin
=
0.5
)
x1 should be closer to target than x2 (y=1 means x1 > x2)
x1
=
torch.
tensor
(
[
0.8
,
0.3
,
0.6
]
)
x2
=
torch.
tensor
(
[
0.2
,
0.7
,
0.5
]
)
y
=
torch.
tensor
(
[
1.0
,
1.0
,
1.0
]
)
1: x1>x2, -1: x1
loss
=
criterion
(
x1
,
x2
,
y
)
4.4 TripletMarginLoss (triplet loss)
Used for metric learning, requiring the distance to the anchor (anchor point) The difference between positive (same class) distance is smaller than the distance to negative (different class) distance.
Example
criterion
=
nn.
TripletMarginLoss
(
margin
=
1.0
)
Each vector has dimension embedding_dim
anchor
=
torch.
randn
(
32
,
128
)
Anchor sample
positive
=
torch.
randn
(
32
,
128
)
Positive (same-class) sample
negative
=
torch.
randn
(
32
,
128
)
Negative (different-class) sample
loss
=
criterion
(
anchor
,
positive
,
negative
)
Goal: dist(anchor, positive) + margin < dist(anchor, negative)
Applicable Scenarios:Face recognition, image retrieval, Few-Shot Learning.
4.5 CTCLoss (sequence labeling loss)
Used forInput and output lengths are not alignedin sequence tasks, such as speech recognition (acoustic sequence -> text sequence) and handwriting recognition.
Example
criterion
=
nn.
CTCLoss
(
blank
=
0
)
blank label index
log_probs: (T, N, C) T = time steps, N = batch, C = number of classes
T
,
N
,
C
=
50
,
4
,
20
log_probs
=
torch.
log_softmax
(
torch.
randn
(
T
,
N
,
C
)
,
dim
=
2
)
targets
=
torch.
randint
(
1
,
C
,
(
N *
10
,
)
)
Concatenated target sequence
input_lengths
=
torch.
full
(
(
N
,
)
,
T
,
dtype
=
torch.
long
)
target_lengths
=
torch.
full
(
(
N
,
)
,
10
,
dtype
=
torch.
long
)
loss
=
criterion
(
log_probs
,
targets
,
input_lengths
,
target_lengths
)
5. The reduction parameter in detail
All loss functions support the reduction parameter, which controls how sample losses are aggregated:
Example
predictions
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
,
4.0
]
)
targets
=
torch.
tensor
(
[
1.5
,
2.5
,
2.0
,
5.0
]
)
Per-sample errors: [0.25, 0.25, 1.00, 1.00]
mean (default): average over all samples
loss_mean
=
nn.
MSELoss
(
reduction
=
'mean'
)
(
predictions
,
targets
)
print
(
f
"mean: {loss_mean.item():.4f}"
)
0.6250
sum: sum over all samples
loss_sum
=
nn.
MSELoss
(
reduction
=
'sum'
)
(
predictions
,
targets
)
print
(
f
"sum: {loss_sum.item():.4f}"
)
2.5000
none: return individual losses for each sample (often used for weighting)
loss_none
=
nn.
MSELoss
(
reduction
=
'none'
)
(
predictions
,
targets
)
print
(
f
"none: {loss_none.tolist()}"
)
[0.25, 0.25, 1.0, 1.0]
reduction='none' applied in practice -- weighting different samples:
Example
Give higher weight to samples with large errors (focal loss idea)
per_sample_loss
=
nn.
MSELoss
(
reduction
=
'none'
)
(
predictions
,
targets
)
weights
=
torch.
tensor
(
[
1.0
,
1.0
,
2.0
,
2.0
]
)
Manually set weights
weighted_loss
=
(
per_sample_loss * weights
)
.
mean
(
)
6. Class weights and sample weights
Class weights (handling class imbalance)
When some classes have very few samples in the dataset, you can give minority classes higher weights:
Example
Suppose 3 classes: class 0 has 1000, class 1 has 100, class 2 has 50
Weights are inversely proportional to frequency
class_counts
=
torch.
tensor
(
[
1000.0
,
100.0
,
50.0
]
)
weights
=
1.0
/ class_counts
weights
=
weights / weights.
sum
(
)
len
(
weights
)
Normalization
criterion
=
nn.
CrossEntropyLoss
(
weight
=
weights
)
Ignore specific labels
In tasks such as semantic segmentation, boundary pixels often need to be ignored (label 255):
Example
ignore_index: ignore this label when computing the loss
criterion
=
nn.
CrossEntropyLoss
(
ignore_index
=
255
)
Semantic segmentation scenario
predictions
=
torch.
randn
(
2
,
21
,
256
,
256
)
(N, C, H, W)
targets
=
torch.
randint
(
0
,
22
,
(
2
,
256
,
256
)
)
targets
[
targets
==
21
]
=
255
Boundary labeled as 255
loss
=
criterion
(
predictions
,
targets
)
7. Custom loss functions
When built-in loss functions do not meet your needs, you can customize in two ways:
Method 1: functional (simple)
Example
import
torch
import
torch.
nn
.
functional
as
F
def
focal_loss
(
predictions
,
targets
,
gamma
=
2.0
,
alpha
=
0.25
)
:
"""
Focal Loss: addresses severe positive/negative sample imbalance in object detection
Reduces weight for easy-to-classify samples so the model focuses on hard samples
"""
ce_loss
=
F.
cross_entropy
(
predictions
,
targets
,
reduction
=
'none'
)
pt
=
torch.
exp
(
-ce_loss
)
Probability of correct prediction
focal_weight
=
alpha *
(
1
- pt
)
** gamma
Hard samples get higher weight
return
(
focal_weight * ce_loss
)
.
mean
(
)
Use
predictions
=
torch.
randn
(
8
,
10
)
targets
=
torch.
randint
(
0
,
10
,
(
8
,
)
)
loss
=
focal_loss
(
predictions
,
targets
)
Method 2: subclass nn.Module (recommended)
Example
import
torch
import
torch.
nn
as
nn
class
DiceLoss
(
nn.
Module
)
:
"""
Dice Loss: commonly used in image segmentation, directly optimizes the Dice coefficient
More robust than CrossEntropy for class imbalance (e.g., small object segmentation)
"""
def
init
(
self
,
smooth
=
1.0
)
:
super
(
)
.
init
(
)
self
.
smooth
=
smooth
def
forward
(
self
,
predictions
,
targets
)
:
predictions: (N, C, H, W) -> probabilities after sigmoid
targets: (N, C, H, W) -> one-hot encoded labels
predictions
=
torch.
sigmoid
(
predictions
)
Flatten to (N, -1)
pred_flat
=
predictions.
view
(
predictions.
size
(
0
)
,
1
)
target_flat
=
targets.
view
(
targets.
size
(
0
)
,
1
)
.
float
(
)
intersection
=
(
pred_flat * target_flat
)
.
sum
(
dim
=
1
)
dice
=
(
2.0
- intersection +
self
.
smooth
)
/
(
pred_flat.
sum
(
dim
=
1
)
- target_flat.
sum
(
dim
=
1
)
self
.
smooth
)
return
1
- dice.
mean
(
)
class
CombinedLoss
(
nn.
Module
)
:
"""
Combined loss: CrossEntropy + Dice, balancing pixel-level classification and region overlap
A common combination for image segmentation
"""
def
init
(
self
,
ce_weight
=
0.5
,
dice_weight
=
0.5
)
:
super
(
)
.
init
(
)
self
.
ce_weight
=
ce_weight
self
.
dice_weight
=
dice_weight
self
.
ce
=
nn.
CrossEntropyLoss
(
)
self
.
dice
=
DiceLoss
(
)
def
forward
(
self
,
predictions
,
targets
)
:
return
(
self
.
ce_weight
*
self
.
ce
(
predictions
,
targets
)
self
.
dice_weight
self
.
dice
(
predictions
,
targets
)
)
Use
criterion
=
CombinedLoss
(
ce_weight
=
0.4
,
dice_weight
=
0.6
)
8. Loss function selection guide
Select by task type
Task Type
Recommended loss function
Notes
Multi-Class Classification
CrossEntropyLoss
Most general, preferred choice
Multi-class (class imbalance)
CrossEntropyLoss(weight=...)
Weight minority classes
Multi-class (noisy labels)
CrossEntropyLoss(label_smoothing=0.1)
Prevent overfitting
Binary Classification
BCEWithLogitsLoss
More stable than BCELoss
Multi-label Classification
BCEWithLogitsLoss
Each label judged independently
Object detection (classification head)
CrossEntropyLoss / Focal Loss
Use Focal when positive/negative samples are imbalanced
Object detection (regression head)
SmoothL1Loss / GIoULoss
Standard practice
Ordinary regression
MSELoss
First choice when there are no outliers
Regression with outliers
HuberLoss / SmoothL1Loss
Robust regression
Image segmentation
CrossEntropyLoss + DiceLoss
Better when used in combination
Speech recognition
CTCLoss
Sequence alignment
Metric learning / face recognition
TripletMarginLoss
Learn distances in feature space
Knowledge distillation
KLDivLoss
Learn soft label distributions
Common misuse and cautions
Example
Wrong: manually applying Softmax before CrossEntropyLoss
output
=
torch.
softmax
(
model
(
x
)
,
dim
=
1
)
Redundant softmax
loss
=
nn.
CrossEntropyLoss
(
)
(
output
,
targets
)
it will be applied again internally
Correct: pass logits directly
output
=
model
(
x
)
Raw logits
loss
=
nn.
CrossEntropyLoss
(
)
(
output
,
targets
)
Wrong: passing raw unsigmoided values to BCELoss
loss
=
nn.
BCELoss
(
)
(
model
(
x
)
,
targets
)
May exceed [0,1], numerically unstable
Correct: use BCEWithLogitsLoss
loss
=
nn.
BCEWithLogitsLoss
(
)
(
model
(
x
)
,
targets
)
Wrong: label type mismatch (integer vs float)
targets
=
torch.
tensor
(
[
1
,
0
,
1
]
)
int type
loss
=
nn.
BCEWithLogitsLoss
(
)
(
preds
,
targets
)
Error!
Correct: BCEWithLogitsLoss requires float labels
targets
=
torch.
tensor
(
[
1.0
,
0.0
,
1.0
]
)
float type
loss
=
nn.
BCEWithLogitsLoss
(
)
(
preds
,
targets
)
Correct
Wrong: loss without .item() causes the computation graph to keep accumulating, leading to GPU out-of-memory
total_loss +
=
loss
loss is a tensor holding the computation graph
Correct: use .item() to extract the scalar
total_loss +
=
loss.
item
(
)
Complete training example
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
Model & loss function & optimizer
model
=
MyModel
(
)
.
to
(
device
)
criterion
=
nn.
CrossEntropyLoss
(
label_smoothing
=
0.1
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
1e-3
)
for
epoch
in
range
(
num_epochs
)
:
model.
train
(
)
total_loss
,
correct
=
0.0
,
0
for
inputs
,
labels
in
train_loader:
inputs
=
inputs.
to
(
device
)
labels
=
labels.
to
(
device
)
optimizer.
zero_grad
(
)
outputs
=
model
(
inputs
)
Raw logits
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
- inputs.
size
(
0
)
.item() extracts the scalar
correct +
=
(
outputs.
argmax
(
1
)
==
labels
)
.
sum
(
)
.
item
(
)
avg_loss
=
total_loss /
len
(
train_loader.
dataset
)
accuracy
=
correct /
len
(
train_loader.
dataset
)
print
(
f
"Epoch {epoch+1} | Loss: {avg_loss:.4f} | Acc: {accuracy:.4f}"
)
loss
=
criterion
(
x1
,
x2
,
y
)
4.4 TripletMarginLoss (triplet loss)
Used for metric learning, requiring the distance to the anchor (anchor point) The difference between positive (same class) distance is smaller than the distance to negative (different class) distance.
Example
criterion
=
nn.
TripletMarginLoss
(
margin
=
1.0
)
Each vector has dimension embedding_dim
anchor
=
torch.
randn
(
32
,
128
)
Anchor sample
positive
=
torch.
randn
(
32
,
128
)
Positive (same-class) sample
negative
=
torch.
randn
(
32
,
128
)
Negative (different-class) sample
loss
=
criterion
(
anchor
,
positive
,
negative
)
Goal: dist(anchor, positive) + margin < dist(anchor, negative)
Applicable Scenarios:Face recognition, image retrieval, Few-Shot Learning.
4.5 CTCLoss (sequence labeling loss)
Used forInput and output lengths are not alignedin sequence tasks, such as speech recognition (acoustic sequence -> text sequence) and handwriting recognition.
Example
criterion
=
nn.
CTCLoss
(
blank
=
0
)
blank label index
log_probs: (T, N, C) T = time steps, N = batch, C = number of classes
T
,
N
,
C
=
50
,
4
,
20
log_probs
=
torch.
log_softmax
(
torch.
randn
(
T
,
N
,
C
)
,
dim
=
2
)
targets
=
torch.
randint
(
1
,
C
,
(
N *
10
,
)
)
Concatenated target sequence
input_lengths
=
torch.
full
(
(
N
,
)
,
T
,
dtype
=
torch.
long
)
target_lengths
=
torch.
full
(
(
N
,
)
,
10
,
dtype
=
torch.
long
)
loss
=
criterion
(
log_probs
,
targets
,
input_lengths
,
target_lengths
)
5. The reduction parameter in detail
All loss functions support the reduction parameter, which controls how sample losses are aggregated:
Example
predictions
=
torch.
tensor
(
[
1.0
,
2.0
,
3.0
,
4.0
]
)
targets
=
torch.
tensor
(
[
1.5
,
2.5
,
2.0
,
5.0
]
)
Per-sample errors: [0.25, 0.25, 1.00, 1.00]
mean (default): average over all samples
loss_mean
=
nn.
MSELoss
(
reduction
=
'mean'
)
(
predictions
,
targets
)
(
f
"mean: {loss_mean.item():.4f}"
)
0.6250
sum: sum over all samples
loss_sum
=
nn.
MSELoss
(
reduction
=
'sum'
)
(
predictions
,
targets
)
(
f
"sum: {loss_sum.item():.4f}"
)
2.5000
none: return individual losses for each sample (often used for weighting)
loss_none
=
nn.
MSELoss
(
reduction
=
'none'
)
(
predictions
,
targets
)
(
f
"none: {loss_none.tolist()}"
)
[0.25, 0.25, 1.0, 1.0]
reduction='none' applied in practice -- weighting different samples:
Example
Give higher weight to samples with large errors (focal loss idea)
per_sample_loss
=
nn.
MSELoss
(
reduction
=
'none'
)
(
predictions
,
targets
)
weights
=
torch.
tensor
(
[
1.0
,
1.0
,
2.0
,
2.0
]
)
Manually set weights
weighted_loss
=
(
per_sample_loss * weights
)
.
mean
(
)
6. Class weights and sample weights
Class weights (handling class imbalance)
When some classes have very few samples in the dataset, you can give minority classes higher weights:
Example
Suppose 3 classes: class 0 has 1000, class 1 has 100, class 2 has 50
Weights are inversely proportional to frequency
class_counts
=
torch.
tensor
(
[
1000.0
,
100.0
,
50.0
]
)
weights
=
1.0
/ class_counts
weights
=
weights / weights.
sum
(
)
len
(
weights
)
Normalization
criterion
=
nn.
CrossEntropyLoss
(
weight
=
weights
)
Ignore specific labels
In tasks such as semantic segmentation, boundary pixels often need to be ignored (label 255):
Example
ignore_index: ignore this label when computing the loss
criterion
=
nn.
CrossEntropyLoss
(
ignore_index
=
255
)
Semantic segmentation scenario
predictions
=
torch.
randn
(
2
,
21
,
256
,
256
)
(N, C, H, W)
targets
=
torch.
randint
(
0
,
22
,
(
2
,
256
,
256
)
)
targets
[
targets
==
21
]
=
255
Boundary labeled as 255
loss
=
criterion
(
predictions
,
targets
)
7. Custom loss functions
When built-in loss functions do not meet your needs, you can customize in two ways:
Method 1: functional (simple)
Example
import
torch
import
torch.
nn
.
functional
as
F
def
focal_loss
(
predictions
,
targets
,
gamma
=
2.0
,
alpha
=
0.25
)
:
"""
Focal Loss: addresses severe positive/negative sample imbalance in object detection
Reduces weight for easy-to-classify samples so the model focuses on hard samples
"""
ce_loss
=
F.
cross_entropy
(
predictions
,
targets
,
reduction
=
'none'
)
pt
=
torch.
exp
(
-ce_loss
)
Probability of correct prediction
focal_weight
=
alpha *
(
1
- pt
)
** gamma
Hard samples get higher weight
return
(
focal_weight * ce_loss
)
.
mean
(
)
Use
predictions
=
torch.
randn
(
8
,
10
)
targets
=
torch.
randint
(
0
,
10
,
(
8
,
)
)
loss
=
focal_loss
(
predictions
,
targets
)
Method 2: subclass nn.Module (recommended)
Example
import
torch
import
torch.
nn
as
nn
class
DiceLoss
(
nn.
Module
)
:
"""
Dice Loss: commonly used in image segmentation, directly optimizes the Dice coefficient
More robust than CrossEntropy for class imbalance (e.g., small object segmentation)
"""
def
init
(
self
,
smooth
=
1.0
)
:
super
(
)
.
init
(
)
self
.
smooth
=
smooth
def
forward
(
self
,
predictions
,
targets
)
:
predictions: (N, C, H, W) -> probabilities after sigmoid
targets: (N, C, H, W) -> one-hot encoded labels
predictions
=
torch.
sigmoid
(
predictions
)
Flatten to (N, -1)
pred_flat
=
predictions.
view
(
predictions.
size
(
0
)
,
1
)
target_flat
=
targets.
view
(
targets.
size
(
0
)
,
1
)
.
float
(
)
intersection
=
(
pred_flat * target_flat
)
.
sum
(
dim
=
1
)
dice
=
(
2.0
- intersection +
self
.
smooth
)
/
(
pred_flat.
sum
(
dim
=
1
)
- target_flat.
sum
(
dim
=
1
)
self
.
smooth
)
return
1
- dice.
mean
(
)
class
CombinedLoss
(
nn.
Module
)
:
"""
Combined loss: CrossEntropy + Dice, balancing pixel-level classification and region overlap
A common combination for image segmentation
"""
def
init
(
self
,
ce_weight
=
0.5
,
dice_weight
=
0.5
)
:
super
(
)
.
init
(
)
self
.
ce_weight
=
ce_weight
self
.
dice_weight
=
dice_weight
self
.
ce
=
nn.
CrossEntropyLoss
(
)
self
.
dice
=
DiceLoss
(
)
def
forward
(
self
,
predictions
,
targets
)
:
return
(
self
.
ce_weight
*
self
.
ce
(
predictions
,
targets
)
self
.
dice_weight
self
.
dice
(
predictions
,
targets
)
)
Use
criterion
=
CombinedLoss
(
ce_weight
=
0.4
,
dice_weight
=
0.6
)
8. Loss function selection guide
Select by task type
| Task Type | Recommended loss function | Notes |
|---|---|---|
| Multi-Class Classification | CrossEntropyLoss |
Most general, preferred choice |
| Multi-class (class imbalance) | CrossEntropyLoss(weight=...) |
Weight minority classes |
| Multi-class (noisy labels) | CrossEntropyLoss(label_smoothing=0.1) |
Prevent overfitting |
| Binary Classification | BCEWithLogitsLoss |
More stable than BCELoss |
| Multi-label Classification | BCEWithLogitsLoss |
Each label judged independently |
| Object detection (classification head) | CrossEntropyLoss / Focal Loss |
Use Focal when positive/negative samples are imbalanced |
| Object detection (regression head) | SmoothL1Loss / GIoULoss |
Standard practice |
| Ordinary regression | MSELoss |
First choice when there are no outliers |
| Regression with outliers | HuberLoss / SmoothL1Loss |
Robust regression |
| Image segmentation | CrossEntropyLoss + DiceLoss |
Better when used in combination |
| Speech recognition | CTCLoss |
Sequence alignment |
| Metric learning / face recognition | TripletMarginLoss |
Learn distances in feature space |
| Knowledge distillation | KLDivLoss |
Learn soft label distributions |
Common misuse and cautions
Example
Wrong: manually applying Softmax before CrossEntropyLoss
output
=
torch.
softmax
(
model
(
x
)
,
dim
=
1
)
Redundant softmax
loss
=
nn.
CrossEntropyLoss
(
)
(
output
,
targets
)
it will be applied again internally
Correct: pass logits directly
output
=
model
(
x
)
Raw logits
loss
=
nn.
CrossEntropyLoss
(
)
(
output
,
targets
)
Wrong: passing raw unsigmoided values to BCELoss
loss
=
nn.
BCELoss
(
)
(
model
(
x
)
,
targets
)
May exceed [0,1], numerically unstable
Correct: use BCEWithLogitsLoss
loss
=
nn.
BCEWithLogitsLoss
(
)
(
model
(
x
)
,
targets
)
Wrong: label type mismatch (integer vs float)
targets
=
torch.
tensor
(
[
1
,
0
,
1
]
)
int type
loss
=
nn.
BCEWithLogitsLoss
(
)
(
preds
,
targets
)
Error!
Correct: BCEWithLogitsLoss requires float labels
targets
=
torch.
tensor
(
[
1.0
,
0.0
,
1.0
]
)
float type
loss
=
nn.
BCEWithLogitsLoss
(
)
(
preds
,
targets
)
Correct
Wrong: loss without .item() causes the computation graph to keep accumulating, leading to GPU out-of-memory
total_loss +
=
loss
loss is a tensor holding the computation graph
Correct: use .item() to extract the scalar
total_loss +
=
loss.
item
(
)
Complete training example
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
Model & loss function & optimizer
model
=
MyModel
(
)
.
to
(
device
)
criterion
=
nn.
CrossEntropyLoss
(
label_smoothing
=
0.1
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
1e-3
)
for
epoch
in
range
(
num_epochs
)
:
model.
train
(
)
total_loss
,
correct
=
0.0
,
0
for
inputs
,
labels
in
train_loader:
inputs
=
inputs.
to
(
device
)
labels
=
labels.
to
(
device
)
optimizer.
zero_grad
(
)
outputs
=
model
(
inputs
)
Raw logits
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
- inputs.
size
(
0
)
.item() extracts the scalar
correct +
=
(
outputs.
argmax
(
1
)
==
labels
)
.
sum
(
)
.
item
(
)
avg_loss
=
total_loss /
len
(
train_loader.
dataset
)
accuracy
=
correct /
len
(
train_loader.
dataset
)
(
f
"Epoch {epoch+1} | Loss: {avg_loss:.4f} | Acc: {accuracy:.4f}"
)