ModuleList#
- class torch.nn.ModuleList(modules=None)[source]#
将子模块保存在一个列表中。
ModuleList
可以像普通 Python 列表一样进行索引,但它包含的模块已正确注册,并且可以被所有Module
方法访问。- 参数
modules (iterable, optional) – 要添加的模块的可迭代对象
示例
class MyModule(nn.Module): def __init__(self) -> None: super().__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