PyTorch torch.nn.GRU 関数
torch.nn.GRUPyTorchのゲート付きリカレントユニット(GRU)モジュールです。
GRUはLSTMの簡素化版で、パラメータが少なく、計算が速く、性能はほぼ同等です。
関数定義
torch.nn.GRU(input_size, hidden_size, num_layers=1, bias=True, batch_first=True, dropout=0, bidirectional=False)
使用例
例1: 基本の使い方
サンプル
import torch
import torch.nn as nn
# GRU: 入力256次元、隠れ256次元、2層
gru = nn.GRU(input_size=256, hidden_size=256, num_layers=2, batch_first=True)
# 入力: batch=4、系列=10、特徴量=256
x = torch.randn(4, 10, 256)
output, hidden = gru(x)
print("入力形状:", x.shape)
print("出力形状:", output.shape)
print("隠れ状態形状:", hidden.shape)
import torch.nn as nn
# GRU: 入力256次元、隠れ256次元、2層
gru = nn.GRU(input_size=256, hidden_size=256, num_layers=2, batch_first=True)
# 入力: batch=4、系列=10、特徴量=256
x = torch.randn(4, 10, 256)
output, hidden = gru(x)
print("入力形状:", x.shape)
print("出力形状:", output.shape)
print("隠れ状態形状:", hidden.shape)
例2: LSTMとの比較
サンプル
import torch
import torch.nn as nn
import time
# 同じ構成のLSTMとGRU
lstm = nn.LSTM(256, 256, 1, batch_first=True)
gru = nn.GRU(256, 256, 1, batch_first=True)
x = torch.randn(32, 100, 256)
# 性能比較
for model, name in [(lstm, "LSTM"), (gru, "GRU")]:
start = time.time()
for _ in range(100):
_ = model(x)
print(f"{name} 時間: {time.time()-start:.3f}s")
import torch.nn as nn
import time
# 同じ構成のLSTMとGRU
lstm = nn.LSTM(256, 256, 1, batch_first=True)
gru = nn.GRU(256, 256, 1, batch_first=True)
x = torch.randn(32, 100, 256)
# 性能比較
for model, name in [(lstm, "LSTM"), (gru, "GRU")]:
start = time.time()
for _ in range(100):
_ = model(x)
print(f"{name} 時間: {time.time()-start:.3f}s")
例3: 分類タスク
サンプル
import torch
import torch.nn as nn
class GRUClassifier(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
super(GRUClassifier, self).__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.gru = nn.GRU(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.fc = nn.Linear(hidden_dim * 2, num_classes)
def forward(self, x):
embedded = self.embedding(x)
_, hidden = self.gru(embedded)
# 双方向の最終隠れ状態を連結
hidden = torch.cat([hidden[-2], hidden[-1]], dim=1)
return self.fc(hidden)
model = GRUClassifier(10000, 128, 128, 2)
x = torch.randint(0, 10000, (8, 50))
output = model(x)
print("入力:", x.shape, "-> 出力:", output.shape)
import torch.nn as nn
class GRUClassifier(nn.Module):
def __init__(self, vocab_size, embed_dim, hidden_dim, num_classes):
super(GRUClassifier, self).__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.gru = nn.GRU(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.fc = nn.Linear(hidden_dim * 2, num_classes)
def forward(self, x):
embedded = self.embedding(x)
_, hidden = self.gru(embedded)
# 双方向の最終隠れ状態を連結
hidden = torch.cat([hidden[-2], hidden[-1]], dim=1)
return self.fc(hidden)
model = GRUClassifier(10000, 128, 128, 2)
x = torch.randint(0, 10000, (8, 50))
output = model(x)
print("入力:", x.shape, "-> 出力:", output.shape)
LSTM vs GRU
| 項目 | LSTM | GRU |
|---|---|---|
| パラメータ数 | 多い | 少ない |
| ゲート | 3つのゲート | 2つのゲート |
| 計算 | 遅い | 速い |
使用シーン
- 系列モデリング: テキスト、音声
- 迅速なプロトタイピング: リソースが限られている場合
- 機械翻訳: encoder側
その他の拡張
PyTorch torch.nn リファレンスマニュアル