nn.Sequential 是一个有序的容器;
它的输入是一个 神经网络模块 的有序序列,或者是由 模块名和神经网络模块 组成的有序字典;
代表模型的输入(样本)要有序地经过这些模块,然后得到一个输出;
源码解析
源码地址 https://pytorch.org/docs/stable/_modules/torch/nn/modules/container.html#Sequential
class Sequential(Module): r"""A sequential container. Modules will be added to it in the order they are passed in the constructor. Alternatively, an ordered dict of modules can also be passed in. To make it easier to understand, here is a small example:: # 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)def forward(self, input): for module in self: input = module(input) return input
1. 在注释中写了两种输入模式,一种是有序序列,一种是有序字典
2. 在构造函数 init 中,首先判断,如果序列长度为 1,且是有序字典类型,就通过读取字典的方式把 该 神经网络模块 加入模型;否则遍历模块,逐个加入模型
3. 在 forward 中实现前向计算,把 input 依次经过所有神经网络模块,最终输出前向计算结果
具体用法
创建该序列的对象,然后把样本喂给该对象
in_dim=1 n_hidden_1=1 n_hidden_2=1 out_dim=1 class Net(nn.Module): def __init__(self, in_dim, n_hidden_1, n_hidden_2, out_dim): super().__init__() self.layer = nn.Sequential( nn.Linear(in_dim, n_hidden_1), nn.ReLU(True), nn.Linear(n_hidden_1, n_hidden_2), nn.ReLU(True), nn.Linear(n_hidden_2, out_dim) ) def forward(self, x): x = self.layer(x) return x
就是这么简单
参考资料:
https://blog.csdn.net/dss_dssssd/article/details/82980222 pytorch系列7 -----nn.Sequential讲解