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

PyTorch torch.nn.Sigmoid function

PyTorch torch.nn.Sigmoid function

PyTorch torch.nn Reference Manual 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

)

print

(

"Input:"

,

x.

tolist

(

)

)

print

(

"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

)

print

(

"Logits:"

,

logits.

squeeze

(

)

.

tolist

(

)

)

print

(

"Probability:"

,

probabilities.

squeeze

(

)

.

tolist

(

)

)

print

(

"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

)

print

(

"Shape:"

,

output.

shape

)

print

(

"Both methods give the same result:"

,

torch.

allclose

(

output

,

output2

)

)


Use Cases

Note: When training deep networks, ReLU works better; Sigmoid tends to cause vanishing gradients.


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