对Pytorch中nn.ModuleList 和 nn.Sequential详解


Posted in Python onAugust 18, 2019

简而言之就是,nn.Sequential类似于Keras中的贯序模型,它是Module的子类,在构建数个网络层之后会自动调用forward()方法,从而有网络模型生成。而nn.ModuleList仅仅类似于pytho中的list类型,只是将一系列层装入列表,并没有实现forward()方法,因此也不会有网络模型产生的副作用。

需要注意的是,nn.ModuleList接受的必须是subModule类型,例如:

nn.ModuleList(
      [nn.ModuleList([Conv(inp_dim + j * increase, oup_dim, 1, relu=False, bn=False) for j in range(5)]) for i in
       range(nstack)])

其中,二次嵌套的list内部也必须额外使用一个nn.ModuleList修饰实例化,否则会无法识别类型而报错!

摘录自

nn.ModuleList is just like a Python list. It was designed to store any desired number of nn.Module's. It may be useful, for instance, if you want to design a neural network whose number of layers is passed as input:

class LinearNet(nn.Module):
 def __init__(self, input_size, num_layers, layers_size, output_size):
   super(LinearNet, self).__init__()
 
   self.linears = nn.ModuleList([nn.Linear(input_size, layers_size)])
   self.linears.extend([nn.Linear(layers_size, layers_size) for i in range(1, self.num_layers-1)])
   self.linears.append(nn.Linear(layers_size, output_size)

nn.Sequential allows you to build a neural net by specifying sequentially the building blocks (nn.Module's) of that net. Here's an example:

class Flatten(nn.Module):
 def forward(self, x):
  N, C, H, W = x.size() # read in N, C, H, W
  return x.view(N, -1)
 
simple_cnn = nn.Sequential(
      nn.Conv2d(3, 32, kernel_size=7, stride=2),
      nn.ReLU(inplace=True),
      Flatten(), 
      nn.Linear(5408, 10),
     )

In nn.Sequential, the nn.Module's stored inside are connected in a cascaded way. For instance, in the example that I gave, I define a neural network that receives as input an image with 3 channels and outputs 10 neurons. That network is composed by the following blocks, in the following order: Conv2D -> ReLU -> Linear layer. Moreover, an object of type nn.Sequential has a forward() method, so if I have an input image x I can directly call y = simple_cnn(x) to obtain the scores for x. When you define an nn.Sequential you must be careful to make sure that the output size of a block matches the input size of the following block. Basically, it behaves just like a nn.Module

On the other hand, nn.ModuleList does not have a forward() method, because it does not define any neural network, that is, there is no connection between each of the nn.Module's that it stores. You may use it to store nn.Module's, just like you use Python lists to store other types of objects (integers, strings, etc). The advantage of using nn.ModuleList's instead of using conventional Python lists to store nn.Module's is that Pytorch is “aware” of the existence of the nn.Module's inside an nn.ModuleList, which is not the case for Python lists. If you want to understand exactly what I mean, just try to redefine my class LinearNet using a Python list instead of a nn.ModuleList and train it. When defining the optimizer() for that net, you'll get an error saying that your model has no parameters, because PyTorch does not see the parameters of the layers stored in a Python list. If you use a nn.ModuleList instead, you'll get no error.

以上这篇对Pytorch中nn.ModuleList 和 nn.Sequential详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python为tornado添加recaptcha验证码功能
Feb 26 Python
跟老齐学Python之从if开始语句的征程
Sep 14 Python
Python比较2个时间大小的实现方法
Apr 10 Python
python3使用pandas获取股票数据的方法
Dec 22 Python
详解python运行三种方式
May 13 Python
Django框架搭建的简易图书信息网站案例
May 25 Python
django框架model orM使用字典作为参数,保存数据的方法分析
Jun 24 Python
Django通过dwebsocket实现websocket的例子
Nov 15 Python
Python列表切片常用操作实例解析
Dec 16 Python
Python3爬虫里关于识别微博宫格验证码的知识点详解
Jul 30 Python
python字典按照value排序方法
Dec 28 Python
matplotlib交互式数据光标实现(mplcursors)
Jan 13 Python
pytorch 自定义数据集加载方法
Aug 18 #Python
PyTorch的Optimizer训练工具的实现
Aug 18 #Python
Pytorch反向求导更新网络参数的方法
Aug 17 #Python
pytorch 模型可视化的例子
Aug 17 #Python
pytorch 输出中间层特征的实例
Aug 17 #Python
基于pytorch的保存和加载模型参数的方法
Aug 17 #Python
pytorch 固定部分参数训练的方法
Aug 17 #Python
You might like
图形数字验证代码
2006/10/09 PHP
ThinkPHP连接数据库及主从数据库的设置教程
2014/08/22 PHP
Yii中CArrayDataProvider和CActiveDataProvider区别实例分析
2016/03/02 PHP
PHP接口并发测试的方法(推荐)
2016/12/15 PHP
PHP实现笛卡尔积算法的实例讲解
2019/12/22 PHP
JS获取dom 对象 ajax操作 读写cookie函数
2009/11/18 Javascript
收集的10个免费的jQuery相册
2011/02/26 Javascript
js(JavaScript)实现TAB标签切换效果的简单实例
2014/02/26 Javascript
如何设置一定时间内只能发送一次请求
2014/02/28 Javascript
下拉框select的绑定示例
2014/09/04 Javascript
Javascript实现单张图片浏览
2014/12/18 Javascript
PageSwitch插件实现100种不同图片切换效果
2015/07/28 Javascript
Bootstrap 最常用的JS插件系列总结(图片轮播、标签切换等)
2016/07/14 Javascript
JS判断输入的字符串是否是数字的方法(正则表达式)
2016/11/29 Javascript
微信小程序checkbox组件使用详解
2018/01/31 Javascript
vue2.0实现移动端的输入框实时检索更新列表功能
2018/05/08 Javascript
webpack4.x CommonJS模块化浅析
2018/11/09 Javascript
layui使用button按钮 点击出现弹层 弹层中加载表单的实例
2019/09/04 Javascript
Vue axios 将传递的json数据转为form data的例子
2019/10/29 Javascript
vue遍历生成的输入框 绑定及修改值示例
2019/10/30 Javascript
原生JS实现天气预报
2020/06/16 Javascript
[02:32]DOTA2英雄基础教程 祸乱之源
2013/12/23 DOTA
Python实现PS图像明亮度调整效果示例
2018/01/23 Python
python3.x上post发送json数据
2018/03/04 Python
基于Python爬取京东双十一商品价格曲线
2020/10/23 Python
python爬虫利用selenium实现自动翻页爬取某鱼数据的思路详解
2020/12/22 Python
巧用HTML5给按钮背景设计不同的动画简单实例
2016/08/09 HTML / CSS
迷你唐卡软皮鞋:Minnetonka Moccasin
2018/05/01 全球购物
医学生个人求职信范文
2013/09/24 职场文书
七年级音乐教学反思
2014/01/26 职场文书
幽默自我介绍演讲稿
2014/08/21 职场文书
小学六一儿童节活动总结
2015/05/05 职场文书
2015年试用期工作总结范文
2015/05/28 职场文书
关于五一放假的通知
2015/08/18 职场文书
想要创业,那么你做好准备了吗?
2019/07/01 职场文书
适合后台管理系统开发的12个前端框架(小结)
2021/06/29 Javascript