PyTorch torch.nn.Tanh 関数
torch.nn.TanhPyTorchの双曲線正接活性化関数です。
入力値を-1から1の間にマッピングし、出力がゼロ中心化されます。再帰型ニューラルネットワークでよく使用されます。
関数定義
torch.nn.Tanh()
数学的原理
Tanh(x) = (e^x - e^(-x)) / (e^x + e^(-x))
使用例
例1: 基本的な使い方
例
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("入力:", x.tolist())
print("出力:", output.tolist())
print("特徴: 出力範囲 [-1, 1]、ゼロ中心化")
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("入力:", x.tolist())
print("出力:", output.tolist())
print("特徴: 出力範囲 [-1, 1]、ゼロ中心化")
例2: LSTMでの使用
例
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
# ゲート機構はTanhとSigmoidを使用
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
h, c = hidden
# 簡略化したゲート計算
gates = self.sigmoid(x @ torch.randn(x.shape[1], self.hidden_size * 4))
# Tanhは候補記憶に使用
candidate = self.tanh(x @ torch.randn(x.shape[1], self.hidden_size))
return candidate, torch.zeros_like(h)
# テスト
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("入力形状:", x.shape)
print("隠れ状態の形状:", 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
# ゲート機構はTanhとSigmoidを使用
self.tanh = nn.Tanh()
self.sigmoid = nn.Sigmoid()
def forward(self, x, hidden):
h, c = hidden
# 簡略化したゲート計算
gates = self.sigmoid(x @ torch.randn(x.shape[1], self.hidden_size * 4))
# Tanhは候補記憶に使用
candidate = self.tanh(x @ torch.randn(x.shape[1], self.hidden_size))
return candidate, torch.zeros_like(h)
# テスト
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("入力形状:", x.shape)
print("隠れ状態の形状:", new_h.shape)
例3: Sigmoidとの比較
例
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}")
よくある質問
Q1: TanhとSigmoidの違いは?
Tanhの出力範囲は[-1,1](ゼロ中心化)、Sigmoidの出力範囲は[0,1]です。
Q2: なぜLSTMでTanhを使うのか?
Tanhのゼロ中心化特性により、勾配の流れがより安定します。
使用シナリオ
- 再帰型ニューラルネットワーク: LSTM、GRUのデフォルト活性化
- 生成モデル: GANの生成器
- ゲート機構: 情報の範囲を制御
その他の拡張
PyTorch torch.nn リファレンスマニュアル