模块字典 ¶
- class torch.nn.ModuleDict(modules=None)[source][source]¶
在字典中保存子模块。
ModuleDict
可以像常规 Python 字典一样索引,但其中包含的模块会被正确注册,并且对所有Module
方法可见。ModuleDict
是一个有序字典,它尊重插入顺序,并且
在
update()
中,合并的顺序为OrderedDict
,dict
(从 Python 3.6 开始)或另一个ModuleDict
(update()
的参数)。
注意,
update()
与其他无序映射类型(例如,Python 3.6 版本之前的普通dict
)合并时不会保留顺序。- 参数:
模块(可迭代,可选)- 一个映射(字典)类型为(字符串:模块)或一个键值对的可迭代序列,键和值类型分别为(字符串,模块)
示例:
class MyModule(nn.Module): def __init__(self) -> None: super().__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
- items()[来源][来源] ¶
返回 ModuleDict 键/值对的迭代器。
- 返回类型:
Iterable[tuple[str, torch.nn.modules.module.Module]]
- keys()[来源][来源] ¶
返回 ModuleDict 键的迭代器。
- 返回类型:
Iterable[str]
- update(modules)[source][source]¶
更新
ModuleDict
中的键值对映射,覆盖现有键。注意
如果
modules
是一个OrderedDict
、一个ModuleDict
或者键值对的迭代器,则保留新元素的顺序。- 参数:
模块(迭代器)- 一个从字符串到
Module
的映射(字典),或类型为(字符串,Module
)的键值对迭代器。
- values()[来源][来源] ¶
返回 ModuleDict 值的可迭代对象。
- 返回类型:
可迭代[Module]