参考:官方文档    源码

官方文档

nn.Sequential

  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.

  翻译:一个有序的容器,神经网络模块将按照在传入构造器的顺序依次被添加到计算图中执行,同时以神经网络模块为元素的有序字典也可以作为传入参数。

使用方法一:作为一个有顺序的容器

  作为一个有顺序的容器,将特定神经网络模块按照在传入构造器的顺序依次被添加到计算图中执行。

官方 Example:

model = nn.Sequential(
nn.Conv2d(1,20,5),
nn.ReLU(),
nn.Conv2d(20,64,5),
nn.ReLU()
)
# When `model` is run,input will first be passed to `Conv2d(1,20,5)`.
# The output of `Conv2d(1,20,5)` will be used as the input to the first `ReLU`;
# the output of the first `ReLU` will become the input for `Conv2d(20,64,5)`.
# Finally, the output of `Conv2d(20,64,5)` will be used as input to the second `ReLU`

例子:

net = nn.Sequential(
nn.Linear(num_inputs, num_hidden)
# 传入其他层
)

使用方法二:作为一个有序字典

  将以特定神经网络模块为元素的有序字典(OrderedDict)为参数传入。

官方 Example :

model = nn.Sequential(OrderedDict([
('conv1', nn.Conv2d(1,20,5)),
('relu1', nn.ReLU()),
('conv2', nn.Conv2d(20,64,5)),
('relu2', nn.ReLU())
]))

例子:

net = nn.Sequential()
net.add_module('linear1', nn.Linear(num_inputs, num_hiddens))
net.add_module('linear2', nn.Linear(num_hiddens, num_ouputs))
# net.add_module ......

源码分析

初始化函数 init

    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 个,且类型为 OrderedDict,则通过字典索引的方式利用 add_module 函数 将子模块添加到现有模块中。否则,通过 for 循环遍历参数,将所有的子模块添加到现有模块中。 这里需要注意,Sequential 模块的初始换函数没有异常处理。

forward 函数

    def forward(self, input):
for module in self:
input = module(input)
return input

  因为每一个 module 都继承于 nn.Module,都会实现 __call__ 与 forward 函数,所以 forward 函数中通过 for 循环依次调用添加到 self._module 中的子模块,最后输出经过所有神经网络层的结果。

Pytorch——torch.nn.Sequential()详解的更多相关文章

  1. torch.nn.Sequential()详解

    参考:官方文档    源码 官方文档 nn.Sequential A sequential container. Modules will be added to it in the order th ...

  2. pytorch之nn.Conv1d详解

    转自:https://blog.csdn.net/sunny_xsc1994/article/details/82969867,感谢分享 pytorch之nn.Conv1d详解

  3. PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx

    PyTorch : torch.nn.xxx 和 torch.nn.functional.xxx 在写 PyTorch 代码时,我们会发现一些功能重复的操作,比如卷积.激活.池化等操作.这些操作分别可 ...

  4. 【小白学PyTorch】11 MobileNet详解及PyTorch实现

    文章来自微信公众号[机器学习炼丹术].我是炼丹兄,欢迎加我微信好友交流学习:cyx645016617. @ 目录 1 背景 2 深度可分离卷积 2.2 一般卷积计算量 2.2 深度可分离卷积计算量 2 ...

  5. 【小白学PyTorch】12 SENet详解及PyTorch实现

    文章来自微信公众号[机器学习炼丹术].我是炼丹兄,有什么问题都可以来找我交流,近期建立了微信交流群,也在朋友圈抽奖赠书十多本了.我的微信是cyx645016617,欢迎各位朋友. 参考目录: @ 目录 ...

  6. Pytorch里的CrossEntropyLoss详解

    在使用Pytorch时经常碰见这些函数cross_entropy,CrossEntropyLoss, log_softmax, softmax.看得我头大,所以整理本文以备日后查阅. 首先要知道上面提 ...

  7. pytorch torch.nn.functional实现插值和上采样

    interpolate torch.nn.functional.interpolate(input, size=None, scale_factor=None, mode='nearest', ali ...

  8. pytorch torch.nn 实现上采样——nn.Upsample

    Vision layers 1)Upsample CLASS torch.nn.Upsample(size=None, scale_factor=None, mode='nearest', align ...

  9. Pytorch Bi-LSTM + CRF 代码详解

    久闻LSTM + CRF的效果强大,最近在看Pytorch官网文档的时候,看到了这段代码,前前后后查了很多资料,终于把代码弄懂了.我希望在后来人看这段代码的时候,直接就看我的博客就能完全弄懂这段代码. ...

随机推荐

  1. 一文读懂Base64编码

    Base64编码 字符对应表 上表就是用来表示Base64,一共64个字符,A-Z,a-z,0-9,+,-,还有=(作为补位) 无论将文件,字符串,还是什么转为Base64,一定是用上表的字符表示. ...

  2. 20210803 noip29

    考场 第一次在 hz 考试.害怕会困,但其实还好 看完题感觉不太难,估计有人 AK. T3 比较套路,没办法枚举黑点就从 LCA 处考虑,在一个点变成黑点时计算其他点和它的 LCA 的贡献,暴力跳父亲 ...

  3. Python - 面向对象编程 - 实战(5)

    前言 主要是针对静态方法.类方法.实例方法.类属性.实例属性的混合实战 需求 设计一个 Game 类 属性 定义一个类属性 top_score 记录游戏的历史最高分,这个属性很明显只跟游戏有关,跟实例 ...

  4. Docker入门之zabbix-agent篇

    在client端启动zabbix-agent服务 启动zabbix-agent有如下2种方式: agent start root@lykj-45:/srv# ls leyao zabbix zabbi ...

  5. 控制台:控制台艺术字 & 为控制台输出增加样式(console.log( ))

    控制台/代码文档LOGO 除了知乎的控制台,大部分的代码文档都有这样的字符logo. 下面这个网站可以自动生成符号艺术字: Text to ASCII Art Generator (TAAG) 控制台 ...

  6. el-upload + accept限制上传的文件格式

    /**  * kevin 2021/1/4  * @description el-upload + accept限制上传的文件格式  * @param e 校验的类型  * @returns {str ...

  7. JEECG代码审计之文件上传

    JEECG代码审计之文件上传 0x01 简述 JEECG(J2EE Code Generation)是一款基于代码生成器JEE的智能开发平台.引领新的开发模式(Online Coding->代码 ...

  8. Vue项目-初始化之 vue-cli

    1.初始化项目 a.Vue CLI 是一个基于 Vue.js 进行快速开发的完整系统,提供: 通过 @vue/cli 搭建交互式的项目脚手架. 通过 @vue/cli + @vue/cli-servi ...

  9. angularjs $http.get 和 $http.post 传递参数

    $http.get请求数据的格式 $http.get(URL,{ params: { "id":id } }) .success(function(response, status ...

  10. vue-自定义指令(directive )的使用方法

    前言 在vue项目中我们经常使用到 v-show ,v-if,v-for等内置的指令,除此之外vue还提供了非常方便的自定义指令,供我们对普通的dom元素进行底层的操作.使我们的日常开发变得更加方便快 ...