Fonction torch.nn.Tanh de PyTorch
Manuel de référence torch.nn de PyTorch
torch.nn.TanhIl s'agit de la fonction d'activation tangente hyperbolique dans PyTorch.
Elle transforme les valeurs d'entrée pour les situer entre -1 et 1, la sortie est centrée sur zéro, et elle est couramment utilisée dans les réseaux de neurones récurrents.
Définition de fonction
torch.nn.Tanh()
Principe mathématique
Tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))
Exemples d'utilisation
Exemple 1 : Utilisation de base
Exemple
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("Sortie :", output.tolist())
print("Caractéristiques : plage de sortie [-1, 1], centrée sur zéro")
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("Sortie :", output.tolist())
print("Caractéristiques : plage de sortie [-1, 1], centrée sur zéro")
Exemple 2 : Utilisation dans LSTM
Exemple
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
# Le mécanisme de portes utilise Tanh et Sigmoid
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
h, c = hidden
# Calcul simplifié des portes
gates = self.sigmoid(x @ torch.randn(x.shape[1], self.hidden_size * 4))
# Tanh est utilisé pour la mémoire candidate
candidate = self.tanh(x @ torch.randn(x.shape[1], self.hidden_size))
return candidate, torch.zeros_like(h)
# Test
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("Forme d'entrée :", x.shape)
print("Forme de l'état caché :", new_h.shape)
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
# Le mécanisme de portes utilise Tanh et Sigmoid
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
h, c = hidden
# Calcul simplifié des portes
gates = self.sigmoid(x @ torch.randn(x.shape[1], self.hidden_size * 4))
# Tanh est utilisé pour la mémoire candidate
candidate = self.tanh(x @ torch.randn(x.shape[1], self.hidden_size))
return candidate, torch.zeros_like(h)
# Test
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("Forme d'entrée :", x.shape)
print("Forme de l'état caché :", new_h.shape)
Exemple 3 : Comparer avec Sigmoid
Exemple
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}")
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}")
FAQ
Q1 : Différence entre Tanh et Sigmoid ?
Les sorties de Tanh sont dans l'intervalle [-1,1] (centrées sur zéro), les sorties de Sigmoid dans [0,1].
Q2 : Pourquoi LSTM utilise-t-il Tanh ?
La propriété centrée sur zéro de Tanh rend le flux de gradient plus stable.
Cas d'utilisation
- Réseaux de neurones récurrents: Activation par défaut pour LSTM, GRU
- Modèles génératifs: Générateur de GAN
- Mécanisme de portes: Contrôle de la plage d'informations
Autres extensions