torch.nn.ModuleList
它是一个储存不同 module,并自动将每个 module 的 parameters 添加到网络之中的容器。你可以把任意 nn.Module 的子类 (比如 nn.Conv2d, nn.Linear 之类的) 加到这个 list 里面,方法和 Python 自带的 list 一样,无非是 extend,append 等操作。但不同于一般的 list,加入到 nn.ModuleList 里面的 module 是会自动注册到整个网络上的,同时 module 的 parameters 也会自动添加到整个网络中。
例子
class MyModule(nn.Module):
def __init__(self):
super(MyModule, self).__init__()
self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])
def forward(self, x):
# ModuleList can act as an iterable, or be indexed using ints
for i, l in enumerate(self.linears):
x = self.linears[i // 2](x) + l(x)
return x

nn.ModuleList是PyTorch中用于存储和管理nn.Module子类的一个容器,它允许动态构建神经网络结构。通过将模块添加到ModuleList,这些模块及其参数会自动注册到整个网络中。在前向传播过程中,ModuleList可以作为可迭代对象或通过索引进行访问。例如,创建一个包含多个线性层的网络并在前向传播中使用它们。此特性使得ModuleList成为构建复杂网络结构的实用工具。
3007

被折叠的 条评论
为什么被折叠?



