torch.nn.ModuleList有什么用

免费建站   2024年05月09日 17:52  

本篇内容主要讲解“..ModuleList有什么用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“torch..ModuleList有什么用”吧!

简要介绍

classtorch.nn.ModuleList(modules=None)Holdssubmodulesinalist.它可以以列表的形式来保持多个子模块。ModuleListcanbeindexedlikearegularPythonlist,butmodulesitcontainsareproperlyregistered,andwillbevisiblebyallModulemethods.ModuleList能够像python列表一样被索引访问,而且其中的模块会被正确地登记注册,而且它保存的模块可以被所有Module方法可见,之所以不能直接用python列表来保存,是因为PyTorch需要自动跟踪计算图并计算自动梯度,如果直接使用python列表或者python字典来保存module,那么无法正确地自动计算梯度.Parameters参数modules(iterable,optional)–aniterableofmodulestoadd接受的参数是模块module的可迭代类型,用来添加到ModuleListappend(module)方法Appendsagivenmoduletotheendofthelist.Parametersmodule(nn.Module)–moduletoappend用来将一个module添加到列表末尾extend(modules)方法AppendsmodulesfromaPythoniterabletotheendofthelist.从python可迭代对象向列表添加多个moduleParameters参数modules(iterable)–iterableofmodulestoappendmodule的可迭代对象insert(index,module)方法Insertagivenmodulebeforeagivenindexinthelist.Parametersindex(int)–indextoinsert.module(nn.Module)–moduletoinsert该方法就像操作python普通列表一样,向ModuleList中指定位置插入一个module

演示代码:

classMyModule(nn.Module):def__init__(self):super(MyModule,self).__init__()self.linears=nn.ModuleList([nn.Linear(10,10)foriinrange(10)])defforward(self,x):#ModuleListcanactasaniterable,orbeindexedusingintsfori,linenumerate(self.linears):x=self.linears[i//2](x)+l(x)returnx注意:子模块必须放在顶层的属性中,而不可能放在列表或者字典中。因为如果不在顶层,而是在列表或者字典中,那么优化器就不能够准确定位这些子模块,因而也就无法优化更新这些模块的参数。如果你需要一个列表或者字典来存放你的子模块,那么就需要使用pytorch提供的方式nn.ModuleList和nn.ModuleDict方法。注意:子模块submodules必须位于顶层属性,不能存放在列表或者字典中,否则优化器不能够准确定位到这些学习参数,因而无法正确优化参数。如有必要,我们可以使用pytorch提供的nn.ModuleList和nn.ModuleDict来实现列表和字典的功能。

到此,相信大家对“torch.nn.ModuleList有什么用”有了更深的了解,不妨来实际操作一番吧!这里是网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

域名注册
购买VPS主机

您或许对下面这些文章有兴趣:                    本月吐槽辛苦排行榜

看贴要回贴有N种理由!看帖不回贴的后果你懂得的!


评论内容 (*必填):
(Ctrl + Enter提交)   

部落快速搜索栏

各类专题梳理

网站导航栏

X
返回顶部