Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.BCEWithLogitsLoss function

PyTorch torch.nn.BCEWithLogitsLoss function

PyTorch torch.nn Reference Manual 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:


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

)

print

(

"BCE Loss:"

,

loss.

item

(

)

)

Manual verification: Sigmoid + BCE

sigmoid

=

torch.

sigmoid

(

logits

)

bce

=

nn.

BCELoss

(

)

(

sigmoid

,

targets

)

print

(

"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

)

print

(

"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

)

print

(

"Multi-label loss:"

,

loss.

item

(

)

)


Use Cases

Note: The input is logits; there is no need to apply Sigmoid beforehand.


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual