PyTorch torch.nn.BCEWithLogitsLoss function
PyTorch torch.nn Reference Manual
torch.nn.BCEWithLogitsLoss is the binary cross-entropy loss function (with Sigmoid) in PyTorch.
It combines Sigmoid and BCE for greater numerical stability and is used for binary classification tasks.
Function definition
torch.nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)
Parameters:
weight: Manual weightspos_weight: Weight for the positive class, used for class imbalance
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
criterion
=
nn.
BCEWithLogitsLoss
(
)
Unnormalized logits
logits
=
torch.
tensor
(
[
2.0
,
1.0
,
0.5
,
3.0
]
)
Binary labels
targets
=
torch.
tensor
(
[
1.0
,
0.0
,
1.0
,
0.0
]
)
loss
=
criterion
(
logits
,
targets
)
(
"BCE Loss:"
,
loss.
item
(
)
)
Manual verification: Sigmoid + BCE
sigmoid
=
torch.
sigmoid
(
logits
)
bce
=
nn.
BCELoss
(
)
(
sigmoid
,
targets
)
(
"Manual BCE:"
,
bce.
item
(
)
)
Example 2: Class imbalance
Example
import
torch
import
torch.
nn
as
nn
Positive class weight: increases the importance of positive samples
pos_weight
=
torch.
tensor
(
[
5.0
]
)
criterion
=
nn.
BCEWithLogitsLoss
(
pos_weight
=
pos_weight
)
logits
=
torch.
randn
(
10
,
1
)
targets
=
torch.
zeros
(
10
,
1
)
targets
[
:
2
]
=
1.0
Few positive samples
loss
=
criterion
(
logits
,
targets
)
(
"Weighted BCE loss:"
,
loss.
item
(
)
)
Example 3: Multi-label classification
Example
import
torch
import
torch.
nn
as
nn
Multi-label binary classification
criterion
=
nn.
BCEWithLogitsLoss
(
)
batch=4, 5 categories, each can be 0 or 1
logits
=
torch.
randn
(
4
,
5
)
labels
=
torch.
randint
(
0
,
2
,
(
4
,
5
)
)
.
float
(
)
loss
=
criterion
(
logits
,
labels
)
(
"Multi-label loss:"
,
loss.
item
(
)
)
Use Cases
- Binary Classification: Single label
- Multi-label Classification: Each label is independent
- Class imbalance: Use pos_weight
Note: The input is logits; there is no need to apply Sigmoid beforehand.