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

PyTorch torch.nn.LogSoftmax function

PyTorch torch.nn.LogSoftmax function

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


torch.nn.LogSoftmax is the Log Softmax activation function in PyTorch.

It is the logarithmic form of Softmax, more numerically stable, and is often used together with NLLLoss.

Function definition



torch.nn.LogSoftmax(dim=None)

Formula



LogSoftmax(x_i) = log(exp(x_i) / sum(exp(x_j)))


Usage examples

Example 1: Basic usage

Example

import

torch

import

torch.

nn

as

nn

log_softmax

=

nn.

LogSoftmax

(

dim

=

1

)

logits

=

torch.

tensor

(

[

[

2.0

,

1.0

,

0.1

]

]

)

log_probs

=

log_softmax

(

logits

)

print

(

"Logits:"

,

logits.

tolist

(

)

)

print

(

"Log Softmax:"

,

log_probs.

tolist

(

)

)

print

(

"After exp:"

,

log_probs.

exp

(

)

.

tolist

(

)

)

Example 2: Using it with NLLLoss

Example

import

torch

import

torch.

nn

as

nn

Classification tasks

logits

=

torch.

randn

(

4

,

10

)

targets

=

torch.

tensor

(

[

2

,

5

,

1

,

7

]

)

LogSoftmax + NLLLoss = CrossEntropyLoss

loss

=

nn.

NLLLoss

(

)

(

nn.

LogSoftmax

(

dim

=

1

)

(

logits

)

,

targets

)

print

(

"NLL Loss:"

,

loss.

item

(

)

)

is equivalent to

loss2

=

nn.

CrossEntropyLoss

(

)

(

logits

,

targets

)

print

(

"CrossEntropyLoss:"

,

loss2.

item

(

)

)

Example 3: Numerical stability

Example

import

torch

import

torch.

nn

as

nn

Large logit values

logits

=

torch.

tensor

(

[

[

1000

,

1001

,

1002

]

]

)

Softmax may overflow

try

:

    sm

=

nn.

Softmax

(

dim

=

1

)

(

logits

)

   

print

(

"Softmax:"

,

sm

)

except

:

   

print

(

"Softmax overflow"

)

LogSoftmax is numerically stable

lsm

=

nn.

LogSoftmax

(

dim

=

1

)

(

logits

)

print

(

"LogSoftmax:"

,

lsm

)


Use Cases

Tip: LogSoftmax + NLLLoss is equivalent to CrossEntropyLoss.


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