PyTorch torch.nn.RNN 関数
torch.nn.RNNPyTorchの基本的なリカレントニューラルネットワークモジュールです。
これは最も単純なリカレント層ですが、勾配消失問題に直面しやすいです。
関数定義
torch.nn.RNN(input_size, hidden_size, num_layers=1, bias=True, batch_first=True, dropout=0, bidirectional=False)
使用例
例1: 基本的な使い方
例
import torch
import torch.nn as nn
rnn = nn.RNN(input_size=256, hidden_size=128, num_layers=2, batch_first=True)
x = torch.randn(4, 10, 256)
output, hidden = rnn(x)
print("入力:", x.shape)
print("出力:", output.shape)
print("隠れ状態:", hidden.shape)
import torch.nn as nn
rnn = nn.RNN(input_size=256, hidden_size=128, num_layers=2, batch_first=True)
x = torch.randn(4, 10, 256)
output, hidden = rnn(x)
print("入力:", x.shape)
print("出力:", output.shape)
print("隠れ状態:", hidden.shape)
例2: 多層RNN
例
import torch
import torch.nn as nn
# 3層RNN、dropout付き
rnn = nn.RNN(128, 256, num_layers=3, dropout=0.3, batch_first=True)
x = torch.randn(2, 50, 128)
out, h = rnn(x)
print("入力:", x.shape)
print("出力:", out.shape)
print("隠れ状態:", h.shape) # (3, 2, 256)
import torch.nn as nn
# 3層RNN、dropout付き
rnn = nn.RNN(128, 256, num_layers=3, dropout=0.3, batch_first=True)
x = torch.randn(2, 50, 128)
out, h = rnn(x)
print("入力:", x.shape)
print("出力:", out.shape)
print("隠れ状態:", h.shape) # (3, 2, 256)
例3: 非線形活性化
例
import torch
import torch.nn as nn
# デフォルトではtanhを活性化関数として使用
rnn = nn.RNN(64, 64, batch_first=True)
x = torch.randn(1, 5, 64)
out, _ = rnn(x)
print("出力形状:", out.shape)
print(RNNはデフォルトでtanhを活性化関数として使用します)
import torch.nn as nn
# デフォルトではtanhを活性化関数として使用
rnn = nn.RNN(64, 64, batch_first=True)
x = torch.randn(1, 5, 64)
out, _ = rnn(x)
print("出力形状:", out.shape)
print(RNNはデフォルトでtanhを活性化関数として使用します)
注意事項
基本的なRNNには勾配消失問題があり、長い系列ではLSTMまたはGRUの使用を推奨します。
使用場面
- 単純な系列タスク: 短い系列
- 教育用の例: RNNの原理を理解する
- クイックプロトタイピング: シンプルなベースライン
その他の拡張