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

PyTorch torch.nn.Tanh function

PyTorch torch.nn.Tanh function

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


torch.nn.Tanh is the hyperbolic tangent activation function in PyTorch.

It maps input values to the range -1 to 1, producing zero-centered output, and is commonly used in recurrent neural networks.

Function definition



torch.nn.Tanh()

Mathematical principle



Tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))


Usage examples

Example 1: Basic usage

Example

import

torch

import

torch.

nn

as

nn

tanh

=

nn.

Tanh

(

)

x

=

torch.

tensor

(

[

2.0

,

1.0

,

0.0

,

1.0

,

2.0

]

)

output

=

tanh

(

x

)

print

(

"Input:"

,

x.

tolist

(

)

)

print

(

"Output:"

,

output.

tolist

(

)

)

print

(

"Feature: output range [-1, 1], zero-centered"

)

Example 2: Use in LSTM

Example

import

torch

import

torch.

nn

as

nn

class

SimpleLSTMCell

(

nn.

Module

)

:

   

def

init

(

self

,

input_size

,

hidden_size

)

:

       

super

(

SimpleLSTMCell

,

self

)

.

init

(

)

       

self

.

hidden_size

=

hidden_size

       

Gating mechanisms use Tanh and Sigmoid

       

self

.

tanh

=

nn.

Tanh

(

)

       

self

.

sigmoid

=

nn.

Sigmoid

(

)

   

def

forward

(

self

,

x

,

hidden

)

:

        h

,

c

=

hidden

       

Simplified gating computation

        gates

=

self

.

sigmoid

(

x

@

torch.

randn

(

x.

shape

[

1

]

,

self

.

hidden_size

4

)

)

       

Tanh is used for the candidate memory

        candidate

=

self

.

tanh

(

x

@

torch.

randn

(

x.

shape

[

1

]

,

self

.

hidden_size

)

)

       

return

candidate

,

torch.

zeros_like

(

h

)

Testing

cell

=

SimpleLSTMCell

(

10

,

20

)

x

=

torch.

randn

(

1

,

10

)

h

=

torch.

randn

(

1

,

20

)

c

=

torch.

randn

(

1

,

20

)

new_h

,

new_c

=

cell

(

x

,

(

h

,

c

)

)

print

(

"Input shape:"

,

x.

shape

)

print

(

"Hidden state shape:"

,

new_h.

shape

)

Example 3: Comparison with Sigmoid

Example

import

torch

import

torch.

nn

as

nn

import

numpy

as

np

x

=

np.

linspace

(

3

,

3

,

11

)

x_tensor

=

torch.

tensor

(

x

,

dtype

=

torch.

float32

)

sigmoid

=

nn.

Sigmoid

(

)

tanh

=

nn.

Tanh

(

)

print

(

"x       Sigmoid    Tanh"

)

print

(

"-"

35

)

for

i

in

range

(

0

,

11

,

2

)

:

    xi

=

x_tensor

[

i:i+

2

]

   

print

(

f

"{xi[0].item():5.1f} {sigmoid(xi)[0].item():9.4f} {tanh(xi)[0].item():9.4f}"

)


Common questions

Q1: What is the difference between Tanh and Sigmoid?

Tanh outputs in the range [-1,1] (zero-centered), while Sigmoid outputs [0,1].

Q2: Why does LSTM use Tanh?

Tanh's zero-centered property makes gradient flow more stable.


Use Cases


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