torch.nn.ModuleList有什么用

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

简要介绍

class torch.nn.ModuleList(modules=None)
	Holds submodules in a list.
	它可以以列表的形式来保持多个子模块。
	ModuleList can be indexed like a regular Python list, 
	but modules it contains are properly registered, 
	and will be visible by all Module methods.
	ModuleList 能够像python列表一样被索引访问,
	而且其中的模块会被正确地登记注册,
	而且它保存的模块可以被所有Module方法可见,
	之所以不能直接用python列表来保存,
	是因为PyTorch需要自动跟踪计算图并计算自动梯度,
	如果直接使用python列表或者python字典来保存module,
	那么无法正确地自动计算梯度.
	
	Parameters 参数
		modules (iterable, optional) – an iterable of modules to add
		接受的参数是模块module的可迭代类型,用来添加到ModuleList

	append(module) 方法
		Appends a given module to the end of the list.
		Parameters
			module (nn.Module) – module to append
		用来将一个module添加到列表末尾

	extend(modules) 方法
		Appends modules from a Python iterable to the end of the list.
		从python可迭代对象向列表添加多个module
		Parameters 参数
			modules (iterable) – iterable of modules to append 
			module的可迭代对象
			
		insert(index, module) 方法
			Insert a given module before a given index in the list.
			Parameters
				index (int) – index to insert.
				module (nn.Module) – module to insert
			该方法就像操作python普通列表一样,向ModuleList中指定位置插入一个module

演示代码:

class MyModule(nn.Module):def __init__(self):super(MyModule, self).__init__()self.linears = nn.ModuleList([nn.Linear(10, 10) for i in range(10)])def forward(self, x):# ModuleList can act as an iterable, or be indexed using intsfor i, l in enumerate(self.linears):x = self.linears[i // 2](x) + l(x)return x
注意:
子模块必须放在顶层的属性中,而不可能放在列表或者字典中。
因为如果不在顶层,而是在列表或者字典中,
那么优化器就不能够准确定位这些子模块,
因而也就无法优化更新这些模块的参数。
如果你需要一个列表或者字典来存放你的子模块,
那么就需要使用pytorch提供的方式nn.ModuleList和nn.ModuleDict方法。


注意:
子模块submodules必须位于顶层属性,不能存放在列表或者字典中,
否则优化器不能够准确定位到这些学习参数,因而无法正确优化参数。
如有必要,我们可以使用pytorch提供的 nn.ModuleList
和nn.ModuleDict来实现列表和字典的功能。

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

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:niceseo99@gmail.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

评论

有免费节点资源,我们会通知你!加入纸飞机订阅群

×
天气预报查看日历分享网页手机扫码留言评论电报频道链接