torch.nn.ModuleList笔记

参考链接: class torch.nn.ModuleList(modules=None)

简要介绍

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 ints
        for 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来实现列表和字典的功能。

在这里插入图片描述在这里插入图片描述

  • 11
    点赞
  • 39
    收藏
    觉得还不错? 一键收藏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值