PyTorch torch.nn.TransformerEncoderLayer 関数
nn.TransformerEncoderLayerTransformer エンコーダーの単層構造です。
自己注意(セルフアテンション)とフィードフォワードネットワークを含み、完全なエンコーダーを構成する基本ユニットです。
関数定義
torch.nn.TransformerEncoderLayer(d_model, nhead, dim_feedforward=2048, dropout=0.1, activation='gelu', batch_first=True)
パラメータ
d_model: モデル次元nhead: アテンションヘッド数dim_feedforward: FFN 隠れ層の次元
使用例
例 1: 基本的な使い方
実例
import torch
import torch.nn as nn
# エンコーダー層
layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True)
# 入力
x = torch.randn(32, 100, 512)
output = layer(x)
print("入力:", x.shape, "-> 出力:", output.shape)
import torch.nn as nn
# エンコーダー層
layer = nn.TransformerEncoderLayer(d_model=512, nhead=8, batch_first=True)
# 入力
x = torch.randn(32, 100, 512)
output = layer(x)
print("入力:", x.shape, "-> 出力:", output.shape)
例 2: カスタム活性化関数
実例
import torch
import torch.nn as nn
# ReLU 活性化を使用
layer_relu = nn.TransformerEncoderLayer(d_model=256, nhead=4, activation='relu', batch_first=True)
x = torch.randn(8, 50, 256)
out = layer_relu(x)
print("ReLU 活性化出力:", out.shape)
import torch.nn as nn
# ReLU 活性化を使用
layer_relu = nn.TransformerEncoderLayer(d_model=256, nhead=4, activation='relu', batch_first=True)
x = torch.randn(8, 50, 256)
out = layer_relu(x)
print("ReLU 活性化出力:", out.shape)
例 3: 多層スタック
実例
import torch
import torch.nn as nn
# 複数の層をスタック
layer = nn.TransformerEncoderLayer(256, 4, batch_first=True)
encoder = nn.Sequential(
layer,
nn.TransformerEncoderLayer(256, 4, batch_first=True),
nn.TransformerEncoderLayer(256, 4, batch_first=True)
)
x = torch.randn(4, 30, 256)
out = encoder(x)
print("3層エンコーダー出力:", out.shape)
import torch.nn as nn
# 複数の層をスタック
layer = nn.TransformerEncoderLayer(256, 4, batch_first=True)
encoder = nn.Sequential(
layer,
nn.TransformerEncoderLayer(256, 4, batch_first=True),
nn.TransformerEncoderLayer(256, 4, batch_first=True)
)
x = torch.randn(4, 30, 256)
out = encoder(x)
print("3層エンコーダー出力:", out.shape)
使用シーン
- エンコーダーの構築
- BERT などのモデル
- テキスト理解
その他の拡張
PyTorch torch.nn リファレンスマニュアル