PyTorch torch.nn.Softmax function
PyTorch torch.nn Reference Manual
torch.nn.Softmax is the Softmax activation function in PyTorch.
It converts inputs into a probability distribution, with all outputs summing to 1.
Function definition
torch.nn.Softmax(dim=None)
Parameters:
dim: The dimension along which to apply Softmax
Formula
Softmax(x_i) = exp(x_i) / sum(exp(x_j))
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
softmax
=
nn.
Softmax
(
dim
=
1
)
logits
=
torch.
tensor
(
[
[
2.0
,
1.0
,
0.1
]
,
[
1.0
,
2.0
,
0.5
]
]
)
probs
=
softmax
(
logits
)
(
"Logits:"
,
logits.
tolist
(
)
)
(
"Probability:"
,
probs.
tolist
(
)
)
(
"Row sums:"
,
probs.
sum
(
dim
=
1
)
.
tolist
(
)
)
Example 2: The dim parameter
Example
import
torch
import
torch.
nn
as
nn
3D input
x
=
torch.
randn
(
2
,
3
,
4
)
Softmax along different dimensions
(
"dim=1:"
,
nn.
Softmax
(
dim
=
1
)
(
x
)
.
sum
(
dim
=
1
)
[
:
1
]
)
(
"dim=2:"
,
nn.
Softmax
(
dim
=
2
)
(
x
)
.
sum
(
dim
=
2
)
[
:
1
]
)
(
"dim=-1:"
,
nn.
Softmax
(
dim
=
1
)
(
x
)
.
sum
(
dim
=
1
)
[
:
1
]
)
Example 3: Classification output
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Linear
(
784
,
10
)
Output logits
logits
=
model
(
torch.
randn
(
4
,
784
)
)
Convert to probabilities
probs
=
nn.
Softmax
(
dim
=
1
)
(
logits
)
(
"Predicted class:"
,
probs.
argmax
(
dim
=
1
)
.
tolist
(
)
)
(
"Highest probability:"
,
probs.
max
(
dim
=
1
)
.
values
.
tolist
(
)
)
Use Cases
- Multi-class output: Probability distribution
- Attention Mechanism
- Probabilistic models
Note: Values after Softmax are all positive and sum to 1.