对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中工作日类库Busines Holiday的介绍与使用
Jul 06 Python
python清理子进程机制剖析
Nov 23 Python
scrapy spider的几种爬取方式实例代码
Jan 25 Python
python顺序的读取文件夹下名称有序的文件方法
Jul 11 Python
Django利用cookie保存用户登录信息的简单实现方法
May 27 Python
django基于restframework的CBV封装详解
Aug 08 Python
Python 转换RGB颜色值的示例代码
Oct 13 Python
在notepad++中实现直接运行python代码
Dec 18 Python
python tkinter之 复选、文本、下拉的实现
Mar 04 Python
Python网络爬虫信息提取mooc代码实例
Mar 06 Python
Python如何给你的程序做性能测试
Jul 29 Python
一文搞懂如何实现Go 超时控制
Mar 30 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
星际争霸 Starcraft 编年史
2020/03/14 星际争霸
广播爱好者需要了解的天线知识
2021/03/01 无线电
php 上一篇,下一篇文章实现代码与原理说明
2010/05/09 PHP
7个超级实用的PHP代码片段
2011/07/11 PHP
php web环境和命令行环境下查找php.ini的位置
2019/07/17 PHP
3分钟写出来的Jquery版checkbox全选反选功能
2013/10/23 Javascript
js 中将多个逗号替换为一个逗号的代码
2014/06/07 Javascript
JS控制弹出新页面窗口位置和大小的方法
2015/03/02 Javascript
jQuery实现左右切换焦点图
2015/04/03 Javascript
JQuery悬停控制图片轮播——代码简单
2015/08/05 Javascript
jQuery实现信息提示框(带有圆角框与动画)效果
2015/08/07 Javascript
javascript每日必学之封装
2016/02/23 Javascript
ECMAScript6快速入手攻略
2016/07/18 Javascript
jQuery插件ContextMenu自定义图标
2017/03/15 Javascript
详解微信小程序Page中data数据操作和函数调用
2017/09/27 Javascript
vue.js计算属性computed用法实例分析
2018/07/06 Javascript
vue+element加入签名效果(移动端可用)
2019/06/17 Javascript
在JavaScript中实现链式调用的实现
2019/12/24 Javascript
Python开发编码规范
2006/09/08 Python
Python三种遍历文件目录的方法实例代码
2018/01/19 Python
python3安装speech语音模块的方法
2018/12/24 Python
Pycharm创建项目时如何自动添加头部信息
2019/11/14 Python
opencv 图像轮廓的实现示例
2020/07/08 Python
美国隐形眼镜网:Major Lens
2018/02/09 全球购物
实习生个人的自我评价
2013/12/08 职场文书
文明礼仪伴我行演讲稿
2014/05/12 职场文书
团干部培训方案
2014/06/03 职场文书
教师求职信
2014/06/17 职场文书
迎国庆演讲稿
2014/09/05 职场文书
乡村教师党员四风问题对照检查材料思想汇报
2014/10/08 职场文书
海上钢琴师的观后感
2015/06/11 职场文书
2015秋季幼儿园开学通知
2015/07/16 职场文书
2016预备党员培训心得体会
2016/01/08 职场文书
小学新课改心得体会
2016/01/22 职场文书
Pytorch 中net.train 和 net.eval的使用说明
2021/05/22 Python
Spring Boot 的创建和运行示例代码详解
2022/07/23 Java/Android