YouTip LogoYouTip

Pytorch Torch Nn Tanh

```html PyTorch torch.nn.Tanh Function | Online Tutorial [Online Tutorial -- Learning not just technology, but dreams!]

PyTorch Tutorial

PyTorch torch.nn.Tanh Function

The torch.nn.Tanh function is a hyperbolic tangent activation function commonly used in neural networks. It maps input values to the range (-1, 1), making it useful for centering the output around zero.

Syntax

torch.nn.Tanh()

Example

import torch
import torch.nn as nn

# Create a Tanh activation function
tanh = nn.Tanh()

# Input tensor
input = torch.tensor([-2.0, -1.0, 0.0, 1.0, 2.0])

# Apply Tanh
output = tanh(input)
print(output)

Output

tensor([-0.9640, -0.7616,  0.0000,  0.7616,  0.9640])

Description

The torch.nn.Tanh function computes the hyperbolic tangent of each element in the input tensor. The formula is:

f(x) = tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))

This function is differentiable and smooth, making it suitable for gradient-based optimization in deep learning models.

Notes

  • Unlike ReLU, Tanh outputs both positive and negative values, which can help with gradient flow.
  • It suffers from vanishing gradients for large absolute input values.
  • Often used in hidden layers of neural networks, especially in RNNs and older architectures.
```
← Pytorch Torch Nn TransformerenPytorch Torch Nn Sequential β†’