ModuleDict#
- class torch.nn.modules.container.ModuleDict(modules=None)[原始碼]#
以字典形式儲存子模組。
ModuleDict可以像普通 Python 字典一樣進行索引,但其中包含的模組會被正確註冊,並對所有Module方法可見。ModuleDict是一個**有序**字典,它會保留插入的順序,並且
在
update()方法中,會保留合併的OrderedDict、dict(從 Python 3.6 開始)或另一個ModuleDict(作為update()的引數)的順序。
請注意,使用其他無序對映型別(例如,Python 3.6 版本之前的普通
dict)呼叫update()不會保留合併對映的順序。- 引數
modules (iterable, optional) – 一個對映(字典),包含 (string: module) 對,或者一個包含 (string, module) 型別鍵值對的可迭代物件。
示例
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)[原始碼]#
使用來自對映的鍵值對更新
ModuleDict,並覆蓋現有鍵。注意
如果
modules是OrderedDict、ModuleDict或鍵值對的可迭代物件,則其中新元素的順序將得到保留。