nn.Module vs nn.functional

前者会保存权重等信息,后者只是做运算

parameters()

返回可训练参数

nn.ModuleList vs. nn.ParameterList vs. nn.Sequential

layer_list = [nn.Conv2d(5,5,3), nn.BatchNorm2d(5), nn.Linear(5,2)]

class myNet(nn.Module):
def __init__(self):
super().__init__()
self.layers = layer_list def forward(x):
for layer in self.layers:
x = layer(x) net = myNet() print(list(net.parameters())) # Parameters of modules in the layer_list don't show up.

nn.ModuleList的作用就是wrap pthon list,这样其中的参数会被注册,因此可以返回可训练参数(ParameterList)。

nn.Sequential的作用如下:

class myNet(nn.Module):
def __init__(self):
super().__init__()
self.layers = nn.Sequential(
nn.Relu(inplace=True),
nn.Linear(10, 10)
) def forward(x):
x = layer(x) x = torch.rand(10)
net = myNet()
print(net(x).shape)

可以看到Sequential的作用就是按照指定的顺序构建网络结构,得到一个完整的模块,而ModuleList则只是像list那样把元素集合起来而已。

nn.modules vs. nn.children

class myNet(nn.Module):
def __init__(self):
super().__init__()
self.convBN = nn.Sequential(nn.Conv2d(10,10,3), nn.BatchNorm2d(10))
self.linear = nn.Linear(10,2) def forward(self, x):
pass Net = myNet() print("Printing children\n------------------------------")
print(list(Net.children()))
print("\n\nPrinting Modules\n------------------------------")
print(list(Net.modules()))

输出信息如下:

Printing children
------------------------------
[Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
), Linear(in_features=10, out_features=2, bias=True)] Printing Modules
------------------------------
[myNet(
(convBN1): Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
(linear): Linear(in_features=10, out_features=2, bias=True)
), Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
), Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1)), BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True), Linear(in_features=10, out_features=2, bias=True)]

可以看到children只会返回子元素,子元素可能是单个操作,如Linear,也可能是Sequential。 而modules()返回的信息更加详细,不仅会返回children一样的信息,同时还会递归地返回,例如modules()会迭代地返回Sequential中包含的若干个子元素。

named_*

  • named_parameters: 返回一个iterator,每次它会提供包含参数名的元组。
In [27]: x = torch.nn.Linear(2,3)

In [28]: x_name_params = x.named_parameters()

In [29]: next(x_name_params)
Out[29]:
('weight', Parameter containing:
tensor([[-0.5262, 0.3480],
[-0.6416, -0.1956],
[ 0.5042, 0.6732]], requires_grad=True)) In [30]: next(x_name_params)
Out[30]:
('bias', Parameter containing:
tensor([ 0.0595, -0.0386, 0.0975], requires_grad=True))
  • named_modules

    这个其实就是把上面提到的nn.modulesiterator的形式返回,每次读取和上面一样也是用next(),示例如下:
In [46]:  class myNet(nn.Module):
...: def __init__(self):
...: super().__init__()
...: self.convBN1 = nn.Sequential(nn.Conv2d(10,10,3), nn.BatchNorm2d(10))
...: self.linear = nn.Linear(10,2)
...:
...: def forward(self, x):
...: pass
...: In [47]: net = myNet() In [48]: net_named_modules = net.named_modules() In [49]: next(net_named_modules)
Out[49]:
('', myNet(
(convBN1): Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)
(linear): Linear(in_features=10, out_features=2, bias=True)
)) In [50]: next(net_named_modules)
Out[50]:
('convBN1', Sequential(
(0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
(1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
)) In [51]: next(net_named_modules)
Out[51]: ('convBN1.0', Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))) In [52]: next(net_named_modules)
Out[52]:
('convBN1.1',
BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)) In [53]: next(net_named_modules)
Out[53]: ('linear', Linear(in_features=10, out_features=2, bias=True)) In [54]: next(net_named_modules)
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-54-05e848b071b8> in <module>
----> 1 next(net_named_modules)
StopIteration:
  • named_children

named_modules

参考

https://blog.paperspace.com/pytorch-101-advanced/

Pytorch: parameters(),children(),modules(),named_*区别的更多相关文章

  1. jquery 中后代遍历之children、find区别

    jquery 中children.find区别 首先看一段HTML代码,如下: <table id="tb"> <tr> <td>0</t ...

  2. web.config中httpModules和Modules的区别

    最近用到了mvc的 Modules管道时,发现web.config中有两个modules 1.system.web节点下的httpModules 2.system.webServer节点下的modul ...

  3. Odoo中Application与modules的区别

    转载请注明原文地址:https://www.cnblogs.com/cnodoo/p/9278681.html 一:Application(应用) application一般是针对大功能的模块,如提供 ...

  4. jquery选择器中的find和空格,children和>的区别、及父节点兄弟节点,还有判断是否存在的写法

     一.find和空格,children和>及其它的区别   空格:$('parent childchild')表示获取parent下的所有的childchild节点(所有的子孙). 等效成  = ...

  5. jQuery初学:find()方法及children方法的区别分析

    首先看看英文解释吧: children方法: find方法: 通过以上的解释,可以总结如下: 1:children及find方法都用是用来获得element的子elements的,两者都不会返回 te ...

  6. find()与children()方法的区别

    来源:http://www.jb51.net/article/26195.htm 总经一下前段时间用于的jQuery方法:find及children.需要的朋友可以参考下. 首先看看英文解释吧: ch ...

  7. children()与find()区别

    1.children() 返回被选元素的所有直接子元素,该方法只会向下一级对 DOM 树进行遍历: 2.find() 返回被选元素的后代元素,一路向下直到最后一个后代.

  8. vue-loader v15、vue-loader v14及之前版本,配置css modules的区别

    vue-loader v15 配置css modules: 是在 css-loader 里配置 官方文档:https://vue-loader.vuejs.org/zh/migrating.html# ...

  9. jQuery:find()方法与children()方法的区别

    1:children及find方法都用是用来获得element的子elements的,两者都不会返回 text node,就像大多数的jQuery方法一样. 2:children方法获得的仅仅是元素一 ...

随机推荐

  1. 爬虫,爬取景点信息采用pandas整理数据

    一.首先需要导入我们的库函数 导语:通过看网上直播学习得到,如有雷同纯属巧合. import requests#请求网页链接import pandas as pd#建立数据模型from bs4 imp ...

  2. 微信小程序开发注意事项

    1.小程序方法是异步的,开发过程要注意此点,避免在需要同步执行过程中的错误,尤其是在app.js处理登入的时候要特别注意. 2.小程序api.组件依赖微信的版本,注意版本的兼容,可以通过版本判断当前的 ...

  3. oracle--10GRAC集群搭建问题OUI-25031

    一,问题描述 安装RAC的过程中在结束 的阶段出现的错误 02,解决方式 这个可能在root.sh 执行的时候报错 由于版本问题: 修改vim /etc/redhat-release 把6.9改为4. ...

  4. Spring中抽象类中使用EmbeddedValueResolverAware和@PostConstruct获取配置文件中的参数值

    我的需求: 我有一个 abstract class 中包含了很多子类中需要用到的公共方法和变量,我想在抽象类中 使用@Value获取*.properties中的值.但是@Value必须要在Spring ...

  5. SpringBoot+EventBus使用教程(二)

    简介 继续上篇,本篇文章介绍如何集成spring-boot-starter-guava-eventbus使用EventBus,最新的版本好像已经不叫spring-boot-starter-guava- ...

  6. 用友U8根据客户简称/供应商简称的拼音首字母生成助记码

    用友U8+中,客户档案和供应商档案可以设置自动生成助记码,但软件只能自动根据客户全称/供应商全称生成助记码,而无法选择按简称生成助记码,这显然十分不方便,可以通过如下方式解决: 修改步骤 1.往数据库 ...

  7. Shell脚本——显示系统上的登录用户数

    写一个脚本showlogged.sh,其用法格式为: showlogged.sh -v -c -h|--help 其中,-h选项只能单独使用,用于显示帮助信息:-c选项时,显示当前系统上登录的所有用户 ...

  8. springmvc和mybatis面试题(含答案)

    Spring MVC Framework有这样一些特点: 1.它是基于组件技术的.全部的应用对象,无论控制器和视图,还是业务对象之类的都是java组件.并且和Spring提供的其他基础结构紧密集成. ...

  9. 【More Effective C++ 条款3】最好不要以多态方式处理数组

    1.在数组与多态混用的情况下,数组元素的访问会出现不可预期的结果(因为数组元素的访问会使用到下标运算) 将一个子类对象数组传递给一个父类对象数组声明的函数,编译器会允许这个行为,但是由于子类对象和父类 ...

  10. 基于word2vec的文档向量模型的应用

    基于word2vec的文档向量模型的应用 word2vec的原理以及训练过程具体细节就不介绍了,推荐两篇文档:<word2vec parameter learning explained> ...