它里面的模块是按照顺序进行排列的,所以需要保证前一个模块的输出大小和下一个模块的输入大小一致。
2、nn.ModuleList它是一个容器,可以储存不同的module,并将每个module添加到网络之中。类比认识的话,他就像是Python中常用到的list一样,就是一些放入和移除的操作。【特别注意:nn.ModuleList可以将module的所有Parameters放入网络之中】
class net_modlist(nn.Module):
def __init__(self):
super(net_modlist, self).__init__()
self.modList = nn.ModuleList([
nn.Conv2d(1, 20, 5),
nn.ReLU(),
nn.Conv2d(20, 64, 5),
nn.ReLU()
])
def forward(self, x):
for m in self.modList:
x = m(x)
return x
net_modList = net_modlLst()
print(net_modList)
二、两者区别
1、nn.Sequential不需要写forward()函数,而nn.ModuleList的内部没有实现forward()函数,故需要使用forward()函数对其进行调用。
【大体情况下:我们常使用nn.Sequential组成卷积块(block),然后像积木拼接一样把不同的block组建成一个网络】
2、nn.Sequential里面的模块按照顺序进行排列的,所以必须确保前一个模块的输出大小和下一个模块的输入大小是一致的。而nn.ModuleList 并没有定义一个网络,它只是将不同的模块储存在一起,这些模块之间并没有什么先后顺序可言。
3、网络中可能存在一些重复或相似的网络层,我们不会选择一行一行的去构建,而是使用for循环网络进行动态构建。那么,此时使用nn.ModuleList就更为方便了。
class net4(nn.Module):
def __init__(self):
super(net4, self).__init__()
layers = [nn.Linear(10, 10) for i in range(5)]
self.linears = nn.ModuleList(layers)
def forward(self, x):
for layer in self.linears:
x = layer(x)
return x
net = net4()
print(net)
参考链接:
(1)链接1
(2)链接2



