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讲解
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)