一个有序的容器,神经网络模块将按照传入构造器的顺序依次被添加到计算图中执行,同时以神经网络模块为元素的有序字典也可以作为传入参数。例如:
# Example of using Sequential
model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
# Example of using Sequential with OrderedDict
model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))
来看下其源码实现
def __init__(self, *args):
super(Sequential, self).__init__()
if len(args) == 1 and isinstance(args[0], OrderedDict):
for key, module in args[0].items():
self.add_module(key, module)
else:
for idx, module in enumerate(args):
self.add_module(str(idx), module)
先看一下初始化函数_init_,在初始化函数中,首先是if条件判断,如果传入的参数为1个,并且类型为OrderdDict,通过字典索引的方式将子模块添加到self._module中,否则,通过for循环遍历参数,将所有的子模块添加到self._module中,注意,Sequential模块的初始函数没有异常处理,所以在写的时候要注意。
接下来,再看一下forward函数的实现:
因为每一个module都继承于nn.Module,都会实现forward函数,所以forward函数中,通过forward函数中通过for循环依次调用添加到self._module中的子模块,最后输出经过所有神经网络层的结果。
def forward(self, input):
for module in self._modules.values():
input = module(input)
return input