PyTorch torch.nn.LogSoftmax function
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
)
(
"Logits:"
,
logits.
tolist
(
)
)
(
"Log Softmax:"
,
log_probs.
tolist
(
)
)
(
"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
)
(
"NLL Loss:"
,
loss.
item
(
)
)
is equivalent to
loss2
=
nn.
CrossEntropyLoss
(
)
(
logits
,
targets
)
(
"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
)
(
"Softmax:"
,
sm
)
except
:
(
"Softmax overflow"
)
LogSoftmax is numerically stable
lsm
=
nn.
LogSoftmax
(
dim
=
1
)
(
logits
)
(
"LogSoftmax:"
,
lsm
)
Use Cases
- Classification tasks: used with NLLLoss
- Numerical stability: large logit values
Tip: LogSoftmax + NLLLoss is equivalent to CrossEntropyLoss.