nn.Module vs nn.functional

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

parameters()

返回可训练参数

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

  1. layer_list = [nn.Conv2d(5,5,3), nn.BatchNorm2d(5), nn.Linear(5,2)]
  2. class myNet(nn.Module):
  3. def __init__(self):
  4. super().__init__()
  5. self.layers = layer_list
  6. def forward(x):
  7. for layer in self.layers:
  8. x = layer(x)
  9. net = myNet()
  10. print(list(net.parameters())) # Parameters of modules in the layer_list don't show up.

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

nn.Sequential的作用如下:

  1. class myNet(nn.Module):
  2. def __init__(self):
  3. super().__init__()
  4. self.layers = nn.Sequential(
  5. nn.Relu(inplace=True),
  6. nn.Linear(10, 10)
  7. )
  8. def forward(x):
  9. x = layer(x)
  10. x = torch.rand(10)
  11. net = myNet()
  12. print(net(x).shape)

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

nn.modules vs. nn.children

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

输出信息如下:

  1. Printing children
  2. ------------------------------
  3. [Sequential(
  4. (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
  5. (1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  6. ), Linear(in_features=10, out_features=2, bias=True)]
  7. Printing Modules
  8. ------------------------------
  9. [myNet(
  10. (convBN1): Sequential(
  11. (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
  12. (1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  13. )
  14. (linear): Linear(in_features=10, out_features=2, bias=True)
  15. ), Sequential(
  16. (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
  17. (1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  18. ), 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,每次它会提供包含参数名的元组。
  1. In [27]: x = torch.nn.Linear(2,3)
  2. In [28]: x_name_params = x.named_parameters()
  3. In [29]: next(x_name_params)
  4. Out[29]:
  5. ('weight', Parameter containing:
  6. tensor([[-0.5262, 0.3480],
  7. [-0.6416, -0.1956],
  8. [ 0.5042, 0.6732]], requires_grad=True))
  9. In [30]: next(x_name_params)
  10. Out[30]:
  11. ('bias', Parameter containing:
  12. tensor([ 0.0595, -0.0386, 0.0975], requires_grad=True))
  • named_modules

    这个其实就是把上面提到的nn.modulesiterator的形式返回,每次读取和上面一样也是用next(),示例如下:
  1. In [46]: class myNet(nn.Module):
  2. ...: def __init__(self):
  3. ...: super().__init__()
  4. ...: self.convBN1 = nn.Sequential(nn.Conv2d(10,10,3), nn.BatchNorm2d(10))
  5. ...: self.linear = nn.Linear(10,2)
  6. ...:
  7. ...: def forward(self, x):
  8. ...: pass
  9. ...:
  10. In [47]: net = myNet()
  11. In [48]: net_named_modules = net.named_modules()
  12. In [49]: next(net_named_modules)
  13. Out[49]:
  14. ('', myNet(
  15. (convBN1): Sequential(
  16. (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
  17. (1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  18. )
  19. (linear): Linear(in_features=10, out_features=2, bias=True)
  20. ))
  21. In [50]: next(net_named_modules)
  22. Out[50]:
  23. ('convBN1', Sequential(
  24. (0): Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1))
  25. (1): BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True)
  26. ))
  27. In [51]: next(net_named_modules)
  28. Out[51]: ('convBN1.0', Conv2d(10, 10, kernel_size=(3, 3), stride=(1, 1)))
  29. In [52]: next(net_named_modules)
  30. Out[52]:
  31. ('convBN1.1',
  32. BatchNorm2d(10, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True))
  33. In [53]: next(net_named_modules)
  34. Out[53]: ('linear', Linear(in_features=10, out_features=2, bias=True))
  35. In [54]: next(net_named_modules)
  36. ---------------------------------------------------------------------------
  37. StopIteration Traceback (most recent call last)
  38. <ipython-input-54-05e848b071b8> in <module>
  39. ----> 1 next(net_named_modules)
  40. 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. [LeetCode] 670. Maximum Swap 最大置换

    Given a non-negative integer, you could swap two digits at most once to get the maximum valued numbe ...

  2. CSP-S 2019 简要题解

    从这里开始 又考炸了,sad.....明年应该在准备高考了,考完把坑填了好了. 一半题都被卡常,qswl.[我汤姆要报警.jpg] dfs 怎么这么慢呀,sad..... i7 牛逼! 写的比较混乱, ...

  3. NOI 2010 海拔(最小割转最短路)

    题意 https://www.lydsy.com/JudgeOnline/problem.php?id=2007 思路 首先可以发现一个结论,每个位置的海拔只有能是 \(0\) 和 \(1\) ,然后 ...

  4. vue 学习注意事项

    一:插值方式: 1:数据绑定,最常见的形式就是使用 “Mustache” 语法(双大括号)的文本插值 <span>Message: {{ msg }}</span>  通过使用 ...

  5. Unity Shader 屏幕后效果——高斯模糊

    高斯模糊是图像模糊处理中非常经典和常见的一种算法,也是Bloom屏幕效果的基础. 实现高斯模糊同样用到了卷积的概念,关于卷积的概念和原理详见我的另一篇博客: https://www.cnblogs.c ...

  6. TF-IDF & CNN

    TF-IDF----------------------------------------------------------------认为一个单词出现的文本频率越小,它区别不同类别的能力就越大, ...

  7. windows上redis的安装和配置

    windows上redis的安装和配置 进入到Redis的根目录D:\Programming\Redis\Redis6379\Redis-x64-3.2.100底下操作: 配置文件启动 redis-s ...

  8. Android Studio Analyze APK 一直显示 Parsing Manifest探因及解决

    一.背景 大家都知道,Android Studio开发工具自带了Analyze Apk,可以很方便的分析Apk文件.具体位于菜单build >> Analyze APK...路径下,点击后 ...

  9. 【java】javac命令在win10不可用,提示javac不是内部或外部命令,也不是可运行的程序【解决方法】

    JDK安装成功,并且配置了环境变量,java命令正常可以使用,但是javac命令提示 不是内部或外部命令,也不是可运行的程序 解决方法: 产生这个问题的原因,是因为环境变量的配置中,Path中配置使用 ...

  10. 深入V8引擎-写在前面

    这一篇不打算讲技术,聊点别的吧,写这个的原因主要是看到了我博客园的签名,开始这个最终源码系列前想说点什么. 转行前端(达成) 入行1年vue源码(达成).webpack源码(半达成) 入行2年争取读通 ...