pytorch系列文档之API:Containers中的ModuleDict

将子模块放到一个字典里

torch.nn.ModuleDict(modules=None)

ModuleDict 可以像regular Python dictionary一样进行索引
ModuleDict 是一个有序的字典.

Note that update() with other unordered mapping types (e.g., Python’s plain dict) does not preserve the order of the merged mapping.

参数:

modules (iterable, optional) – a mapping (dictionary) of (string: module) or an iterable of key-value pairs of type (string, module)
作者注:
这个参数可以是字典、子模块、或者可迭代的键值对

示例

class MyModule(nn.Module):
    def __init__(self):
        super(MyModule, self).__init__()
        self.choices = nn.ModuleDict({
                'conv': nn.Conv2d(10, 10, 3),
                'pool': nn.MaxPool2d(3)
        })
        self.activations = nn.ModuleDict([
                ['lrelu', nn.LeakyReLU()],
                ['prelu', nn.PReLU()]
        ])

    def forward(self, x, choice, act):
        x = self.choices[choice](x)
        x = self.activations[act](x)
        return x

这个类中的方法:
1· clear()

clear()
清除ModuleDict中的所有item

2· items()

items()
返回一个可迭代的对象,里面包含一些ModuleDict键值对
Return an iterable of the ModuleDict key/value pairs.

3· keys()

keys()
返回ModuleDict中的键

4· pop(key)

pop(key)
Remove key from the ModuleDict and return its module.
参数:
key (string) – key to pop from the ModuleDict

5· update(modules)
在这里插入图片描述
6· values()

values()
Return an iterable of the ModuleDict values.
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值