对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中合并两个文本文件并按照姓名首字母排序的例子
Apr 25 Python
Python yield 使用浅析
May 28 Python
python如何拆分含有多种分隔符的字符串
Mar 20 Python
详解Python中的分组函数groupby和itertools)
Jul 11 Python
Python正则表达式实现简易计算器功能示例
May 07 Python
python opencv捕获摄像头并显示内容的实现
Jul 11 Python
python网络爬虫 Scrapy中selenium用法详解
Sep 28 Python
Python如何计算语句执行时间
Nov 22 Python
TensorFlow设置日志级别的几种方式小结
Feb 04 Python
pycharm 设置项目的根目录教程
Feb 12 Python
基于Python pyecharts实现多种图例代码解析
Aug 10 Python
Pygame Draw绘图函数的具体使用
Nov 17 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
国内咖啡文化
2021/03/03 咖啡文化
一周让你学会PHP 不错的学习资料
2009/02/06 PHP
php FLEA中二叉树数组的遍历输出
2012/09/26 PHP
PHP人民币金额数字转中文大写的函数代码
2013/02/27 PHP
PHP 并发场景的几种解决方案
2019/06/14 PHP
根据地区不同显示时间的javascript代码
2007/08/13 Javascript
兼容多浏览器的字幕特效Marquee的通用js类
2008/07/20 Javascript
javascript 尚未实现错误解决办法
2008/11/27 Javascript
基于jQuery选择器的整理集合
2013/04/26 Javascript
jquery实现左右滑动菜单效果代码
2015/08/27 Javascript
谷歌showModalDialog()方法不兼容出现对话窗口的解决办法
2016/02/15 Javascript
使用openSpeDiv方法实现Ecshop登录弹窗框效果
2017/03/13 Javascript
ES6中Iterator与for..of..遍历用法分析
2017/03/31 Javascript
vue.js 左侧二级菜单显示与隐藏切换的实例代码
2017/05/23 Javascript
深入讲解xhr(XMLHttpRequest)/jsonp请求之abort
2017/07/26 Javascript
Bootstrap table使用方法记录
2017/08/23 Javascript
基于VUE移动音乐WEBAPP跨域请求失败的解决方法
2018/01/16 Javascript
js和jQuery以及easyui实现对下拉框的指定赋值方法
2018/01/23 jQuery
解决Nodejs全局安装模块后找不到命令的问题
2018/05/15 NodeJs
ES6 系列之 WeakMap的使用示例
2018/08/06 Javascript
解决select2在bootstrap modal中不能正常使用的问题
2018/08/09 Javascript
深入探索VueJS Scoped CSS 实现原理
2019/09/23 Javascript
vue 解决在微信内置浏览器中调用支付宝支付的情况
2020/11/09 Javascript
原生js实现无缝轮播图效果
2021/01/28 Javascript
[02:15]你好,这就是DOTA!
2015/08/05 DOTA
[47:26]完美世界DOTA2联赛 LBZS vs Forest 第二场 11.07
2020/11/09 DOTA
使用python将图片按标签分入不同文件夹的方法
2018/12/08 Python
python的schedule定时任务模块二次封装方法
2019/02/19 Python
python Gunicorn服务器使用方法详解
2019/07/22 Python
pytorch中nn.Conv1d的用法详解
2019/12/31 Python
python爬虫开发之Beautiful Soup模块从安装到详细使用方法与实例
2020/03/09 Python
python 统计list中各个元素出现的次数的几种方法
2021/02/20 Python
乐高积木玩具美国官网:LEGO Shop US
2016/09/16 全球购物
Wiggle澳大利亚:自行车、跑步、游泳商店
2020/11/07 全球购物
第一批党的群众路线教育实践活动工作总结
2014/03/03 职场文书
党员三严三实对照检查材料
2014/10/13 职场文书