我无意中发现了毕火炬模型中的add_module()方法。
医生仅状态
将子模块添加到当前模块。 可以使用给定的名称作为属性访问该模块。
我不明白“添加子模块”是什么意思。
这与使用self._other module = other_module设置指向另一个模块的指针有什么不同?
细微差别是什么?
发布于 2021-01-07 19:58:38
如前所述:https://discuss.pytorch.org/t/when-to-use-add-module-function/10534
一般来说,您不需要调用add_module。一个潜在的用例如下:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
modules = [...] # some list of modules
for module in modules:
self.add_module(...)发布于 2021-01-07 20:00:41
nn.Module有一个子模块的层次结构,您可以通过方法 (如module.named_children()或module.children() )访问这些子模块。
正如在上面的论坛文章中提到的,执行self._other module = other_module将输入check other_module,查看它是一个nn.Module,并将它添加到子列表中,因此add_module并不是真正必要的。
发布于 2021-04-23 17:41:32
正如您所说,将模块添加为属性很好。但是,如果您不知道预先拥有多少模块,并且必须以编程方式构造名称,那么在运行时做起来可能有点困难。在这种情况下,add_module()是一种非常方便的方法。我刚刚写了一篇简短的博客文章,展示了这一点:module.html
https://stackoverflow.com/questions/65619076
复制相似问题