PyTorch torch.nn.ModuleList 関数
torch.nn.ModuleListPyTorchでモジュールリストを格納するためのコンテナです。
Pythonのリストに似ていますが、すべてのサブモジュールを自動的に登録します。
関数定義
torch.nn.ModuleList(modules=None)
使用例
例1: 基本的な使い方
サンプル
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.layers = nn.ModuleList([
nn.Linear(10, 20),
nn.Linear(20, 20),
nn.Linear(20, 5)
])
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
model = Net()
x = torch.randn(4, 10)
output = model(x)
print("入力:", x.shape)
print("出力:", output.shape)
print("パラメータ数:", sum(p.numel() for p in model.parameters()))
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.layers = nn.ModuleList([
nn.Linear(10, 20),
nn.Linear(20, 20),
nn.Linear(20, 5)
])
def forward(self, x):
for layer in self.layers:
x = layer(x)
return x
model = Net()
x = torch.randn(4, 10)
output = model(x)
print("入力:", x.shape)
print("出力:", output.shape)
print("パラメータ数:", sum(p.numel() for p in model.parameters()))
例2: 動的レイヤー構築
サンプル
import torch
import torch.nn as nn
class DynamicNet(nn.Module):
def __init__(self, num_layers, dim):
super(DynamicNet, self).__init__()
self.layers = nn.ModuleList()
for i in range(num_layers):
in_dim = dim if i == 0 else dim
self.layers.append(nn.Linear(in_dim, dim))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = layer(x)
if i < len(self.layers) - 1:
x = torch.relu(x)
return x
model = DynamicNet(num_layers=5, dim=64)
print("層数:", len(model.layers))
print("総パラメータ数:", sum(p.numel() for p in model.parameters()))
import torch.nn as nn
class DynamicNet(nn.Module):
def __init__(self, num_layers, dim):
super(DynamicNet, self).__init__()
self.layers = nn.ModuleList()
for i in range(num_layers):
in_dim = dim if i == 0 else dim
self.layers.append(nn.Linear(in_dim, dim))
def forward(self, x):
for i, layer in enumerate(self.layers):
x = layer(x)
if i < len(self.layers) - 1:
x = torch.relu(x)
return x
model = DynamicNet(num_layers=5, dim=64)
print("層数:", len(model.layers))
print("総パラメータ数:", sum(p.numel() for p in model.parameters()))
例3: Sequentialとの比較
サンプル
import torch
import torch.nn as nn
# ModuleList - 柔軟
mlist = nn.ModuleList([nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5)])
# Sequential - 順序固定
seq = nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5))
print("ModuleList インデックスアクセス:", mlist[0])
print("Sequential インデックスアクセス:", seq[0])
print("ModuleList は反復可能ですが、forward はありません。")
print("Sequential は直接呼び出し可能")
import torch.nn as nn
# ModuleList - 柔軟
mlist = nn.ModuleList([nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5)])
# Sequential - 順序固定
seq = nn.Sequential(nn.Linear(10, 20), nn.ReLU(), nn.Linear(20, 5))
print("ModuleList インデックスアクセス:", mlist[0])
print("Sequential インデックスアクセス:", seq[0])
print("ModuleList は反復可能ですが、forward はありません。")
print("Sequential は直接呼び出し可能")
使用シーン
- 多層ネットワーク: 動的構築
- ループ構造: 共有レイヤー
- 複雑なモデル: カスタム制御フローが必要
注意:Pythonリストではなくnn.ModuleListを使用する必要があります。
その他の拡張