![](/img/trans.png)
[英]Pycharm complains about using [] operator with pytorch's nn.ModuleList object
[英]Why does my PyTorch ModuleList object become a 'function' object after assigning it as a class variable?
我真的需要你的幫助來解決一些我無法解釋的煩人問題。 我是 PyTorch 的新手,想實現一個需要使用 ModuleList 的模塊。 但是,在實例化一個空的 ModuleList object 之后,我無法使用它的追加方法。 為什么?
self.modules = torch.nn.ModuleList([])
print(type(self.modules), type(torch.nn.ModuleList())) # -> <class 'method'> <class 'torch.nn.modules.container.ModuleList'>
for m in range(len(self.module_sizes)):
prev_channels = 0 if m == 0 else self.module_out_channels[-m]
vgg19_channels = self.vgg19_layer_channels[-(m+1)]
module_out_channels = self.module_out_channels[-(m+1)]
module_size = self.module_sizes[-(m+1)]
self.modules.append(
GeneratorModule(prev_channels=prev_channels, vgg19_channels=vgg19_channels, out_channels=module_out_channels, module_size=module_size, initial=(m==0))
)
錯誤消息說:
File "main.py", line 90, in __init__
self.modules.append(
AttributeError: 'function' object has no attribute 'append'
到目前為止,一切都很好。 我假設一旦我將 ModuleList 作為 class 變量分配給我的自定義 nn.Module 子類,它就會變成一個“函數”object。所以我更改了代碼,在附加后將 ModuleList 分配給 self.modules環形。 但隨后它在后面的一段代碼中拋出了另一個錯誤,它說:
for m, module in enumerate(self.modules):
pass
TypeError: 'method' object is not iterable
我知道這應該可行,因為我發現其他人在 inte.net 上也是這樣做的。
如果有更多經驗豐富的 PyTorch 程序員可以幫助我,我將非常高興。 提前致謝!
其實問題是不一樣的。 如您所見, torch.nn.ModuleList
具有append
和其他類似列表的方法,因此它應該可以工作。 不,它不會“改變”為“功能”object,這對每個人來說都是非常不直觀的。
相反,PyTorch 的torch.nn.Module
有一些你繼承的方法,其中包括modules
(它允許你迭代包含在torch.nn.Module
實例中的modules
)。
只需將您的self.modules
重命名為self.module_list
就可以了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.