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

PyTorch torch.nn.NLLLoss Function

PyTorch torch.nn.NLLLoss Function

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


torch.nn.NLLLoss is the negative log-likelihood loss in PyTorch.

It is used for multi-classification tasks and needs to be used together with LogSoftmax.

Function definition



torch.nn.NLLLoss(weight=None, ignore_index=-100, reduction='mean')


Usage examples

Example 1: Basic usage

Example

import

torch

import

torch.

nn

as

nn

Apply LogSoftmax first, then NLLLoss

log_softmax

=

nn.

LogSoftmax

(

dim

=

1

)

nll

=

nn.

NLLLoss

(

)

Model output (logits)

logits

=

torch.

randn

(

4

,

10

)

After log softmax

log_probs

=

log_softmax

(

logits

)

Ground-truth labels

targets

=

torch.

tensor

(

[

2

,

5

,

1

,

7

]

)

loss

=

nll

(

log_probs

,

targets

)

print

(

"NLL Loss:"

,

loss.

item

(

)

)

Example 2: Equivalent to CrossEntropyLoss

Example

import

torch

import

torch.

nn

as

nn

logits

=

torch.

randn

(

4

,

10

)

targets

=

torch.

tensor

(

[

2

,

5

,

1

,

7

]

)

Method 1: Use CrossEntropyLoss directly

loss1

=

nn.

CrossEntropyLoss

(

)

(

logits

,

targets

)

Method 2: LogSoftmax + NLLLoss

loss2

=

nn.

NLLLoss

(

)

(

nn.

LogSoftmax

(

dim

=

1

)

(

logits

)

,

targets

)

print

(

"CrossEntropyLoss:"

,

loss1.

item

(

)

)

print

(

"LogSoftmax + NLLLoss:"

,

loss2.

item

(

)

)

print

(

"Results are the same:"

,

abs

(

loss1 - loss2

)

<

;

1e-5

)


Use Cases

Note: CrossEntropyLoss already includes LogSoftmax, so it is usually used directly.


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