PyTorch torch.nn.Tanh Funktion
PyTorch torch.nn Referenzhandbuch
torch.nn.TanhEs ist die hyperbolische Tangens-Aktivierungsfunktion in PyTorch.
Sie bildet Eingabewerte auf einen Bereich zwischen -1 und 1 ab, die Ausgabe ist nullzentriert und wird häufig in rekurrenten neuronalen Netzen verwendet.
Funktionsdefinition
torch.nn.Tanh()
Mathematisches Prinzip
Tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))
Anwendungsbeispiele
Beispiel 1: Grundlegende Verwendung
Beispiel
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("Eingabe:", x.tolist())
print("Ausgabe:", output.tolist())
print("Merkmale: Ausgabebereich [-1, 1], nullzentriert")
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("Eingabe:", x.tolist())
print("Ausgabe:", output.tolist())
print("Merkmale: Ausgabebereich [-1, 1], nullzentriert")
Beispiel 2: Verwendung in LSTM
Beispiel
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
# Der Gating-Mechanismus verwendet Tanh und Sigmoid
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
h, c = hidden
# Vereinfachte Gating-Berechnung
gates = self.sigmoid(x @ torch.randn(x.shape[1], self.hidden_size * 4))
# Tanh wird für den Kandidatenspeicher verwendet
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("Eingabeform:", x.shape)
print("Form des verborgenen Zustands:", 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
# Der Gating-Mechanismus verwendet Tanh und Sigmoid
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
h, c = hidden
# Vereinfachte Gating-Berechnung
gates = self.sigmoid(x @ torch.randn(x.shape[1], self.hidden_size * 4))
# Tanh wird für den Kandidatenspeicher verwendet
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("Eingabeform:", x.shape)
print("Form des verborgenen Zustands:", new_h.shape)
Beispiel 3: Vergleich mit Sigmoid
Beispiel
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
Frage 1: Unterschied zwischen Tanh und Sigmoid?
Tanh-Ausgaben liegen im Bereich [-1,1] (nullzentriert), Sigmoid-Ausgaben im Bereich [0,1].
Frage 2: Warum verwendet LSTM Tanh?
Die nullzentrierte Eigenschaft von Tanh macht den Gradientenfluss stabiler.
Anwendungsfälle
- Rekurrente neuronale Netze: Standardaktivierung für LSTM, GRU
- Generative Modelle: Generator von GAN
- Gating-Mechanismus: Steuerung des Informationsbereichs
Weitere Erweiterungen