对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结合ImageMagick实现多张图片合并为一个pdf文件的方法
Apr 24 Python
NumPy.npy与pandas DataFrame的实例讲解
Jul 09 Python
python 利用pandas将arff文件转csv文件的方法
Feb 12 Python
Python调用百度根据经纬度查询地址的示例代码
Jul 07 Python
Python的numpy库下的几个小函数的用法(小结)
Jul 12 Python
python递归法解决棋盘分割问题
Jul 17 Python
python threading和multiprocessing模块基本用法实例分析
Jul 25 Python
python中时间转换datetime和pd.to_datetime详析
Aug 11 Python
python datetime中strptime用法详解
Aug 29 Python
Python连接Hadoop数据中遇到的各种坑(汇总)
Apr 14 Python
Python接口测试环境搭建过程详解
Jun 29 Python
Python 打印自己设计的字体的实例讲解
Jan 04 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
Mysql的GROUP_CONCAT()函数使用方法
2008/03/28 PHP
php实现的在线人员函数库
2008/04/09 PHP
6种php上传图片重命名的方法实例
2013/11/04 PHP
Symfony2实现从数据库获取数据的方法小结
2016/03/18 PHP
ThinkPHP路由机制简介
2016/03/23 PHP
php+mysql+ajax 局部刷新点赞/取消点赞功能(每个账号只点赞一次)
2020/07/24 PHP
创建一个复制UBB软件信息的链接或按钮的js代码
2008/01/06 Javascript
JS面向对象编程 for Cookie
2010/09/19 Javascript
JS+css 图片自动缩放自适应大小
2013/08/08 Javascript
jQuery中使用data()方法读取HTML5自定义属性data-*实例
2014/04/11 Javascript
js实现飞入星星特效代码
2014/10/17 Javascript
js的toUpperCase方法用法实例
2015/01/27 Javascript
解决node.js安装包失败的几种方法
2016/09/02 Javascript
Bootstrap3 datetimepicker控件使用实例
2016/12/13 Javascript
bootstrap日历插件datetimepicker使用方法
2016/12/14 Javascript
vue 实现在函数中触发路由跳转的示例
2018/09/01 Javascript
JS document form表单元素操作完整示例
2020/01/13 Javascript
微信小程序后端无法保持session的原因及解决办法问题
2020/03/20 Javascript
一篇文章带你使用Typescript封装一个Vue组件(简单易懂)
2020/06/05 Javascript
vue-resource 拦截器interceptors使用详解
2021/01/18 Vue.js
[02:53]DOTA2英雄昆卡基础教程
2013/11/25 DOTA
Python+matplotlib实现计算两个信号的交叉谱密度实例
2018/01/08 Python
Python封装原理与实现方法详解
2018/08/28 Python
Django框架模板语言实例小结【变量,标签,过滤器,继承,html转义】
2019/05/23 Python
Pandas_cum累积计算和rolling滚动计算的用法详解
2019/07/04 Python
Python面向对象之多态原理与用法案例分析
2019/12/30 Python
python 递归调用返回None的问题及解决方法
2020/03/16 Python
eBay瑞士购物网站:eBay.ch
2018/12/24 全球购物
大学军训感言
2014/01/10 职场文书
会计职业生涯规划书
2014/01/13 职场文书
大学生旷课检讨书
2014/01/22 职场文书
怎样写好自我评价呢?
2014/02/16 职场文书
摄影专业毕业生求职信
2014/03/13 职场文书
环保倡议书
2014/04/14 职场文书
羽毛球比赛策划方案
2014/06/13 职场文书
八年级英语教学反思
2016/02/15 职场文书