ModuleDict¶
- class torch.nn.ModuleDict(modules=None)[來源][來源]¶
在字典中保存子模組。
ModuleDict
可以像常規 Python 字典一樣進行索引,但它包含的模組已正確註冊,並且將被所有Module
方法可見。ModuleDict
是一個有順序的字典,它會保留插入的順序,並且
在
update()
中,合併的OrderedDict
、dict
(Python 3.6 開始) 或另一個ModuleDict
的順序 (作為update()
的參數)。
請注意,使用其他無序的映射類型 (例如,Python 3.6 之前的普通
dict
) 進行update()
並不會保留合併映射的順序。- 參數
modules (iterable, optional) – 一個 (字串: 模組) 的映射 (字典),或一個 (字串, 模組) 型別的鍵值對的可迭代物件
範例
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
- update(modules)[source][source]¶
使用來自映射的鍵值對更新
ModuleDict
,覆寫現有的鍵。注意
如果
modules
是一個OrderedDict
、一個ModuleDict
或一個鍵值對的可迭代物件,則會保留其中新元素的順序。