PyTorch torch.nn.Sigmoid function
PyTorch torch.nn Reference Manual
torch.nn.Sigmoid is the S-shaped activation function in PyTorch.
It maps input values to the range 0 to 1, commonly used for binary classification or as a gate control signal.
Function definition
torch.nn.Sigmoid()
Mathematical principle
Sigmoid(x) = 1 / (1 + e^(-x))
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
sigmoid
=
nn.
Sigmoid
(
)
x
=
torch.
tensor
(
[
2.0
,
1.0
,
0.0
,
1.0
,
2.0
]
)
output
=
sigmoid
(
x
)
(
"Input:"
,
x.
tolist
(
)
)
(
"Output:"
,
output.
tolist
(
)
)
Example 2: Binary classification output
Example
import
torch
import
torch.
nn
as
nn
model
=
nn.
Linear
(
10
,
1
)
sigmoid
=
nn.
Sigmoid
(
)
logits
=
model
(
torch.
randn
(
4
,
10
)
)
probabilities
=
sigmoid
(
logits
)
(
"Logits:"
,
logits.
squeeze
(
)
.
tolist
(
)
)
(
"Probability:"
,
probabilities.
squeeze
(
)
.
tolist
(
)
)
(
"Prediction:"
,
(
probabilities >
;
0.5
)
.
squeeze
(
)
.
tolist
(
)
)
Example 3: nn.functional version
Example
import
torch
import
torch.
nn
.
functional
as
F
x
=
torch.
randn
(
4
,
10
)
output
=
torch.
sigmoid
(
x
)
output2
=
F.
sigmoid
(
x
)
(
"Shape:"
,
output.
shape
)
(
"Both methods give the same result:"
,
torch.
allclose
(
output
,
output2
)
)
Use Cases
- Binary Classification: Output probabilities
- Gating mechanism: Control information flow
- Probability output: Scenarios requiring a 0-1 range
Note: When training deep networks, ReLU works better; Sigmoid tends to cause vanishing gradients.