[英]what is Pytorch's add_module()?
I stumbled upon the method add_module()
in a Pytorch model.我偶然发现了 Pytorch model 中的
add_module()
方法。
Adds a child module to the current module.
将子模块添加到当前模块。
The module can be accessed as an attribute using the given name.
可以使用给定名称作为属性访问模块。
I don't understand what "adding a child module" means.我不明白“添加子模块”是什么意思。
How is it different from just setting a pointer to the other module using self._other module = other_module
?与仅使用
self._other module = other_module
设置指向其他模块的指针有何不同?
What are the nuances?细微差别是什么?
As mentioned here: https://discuss.pytorch.org/t/when-to-use-add-module-function/10534如此处所述: https://discuss.pytorch.org/t/when-to-use-add-module-function/10534
In general, you won't need to call add_module
.通常,您不需要调用
add_module
。 One potential use case is the following:一个潜在的用例如下:
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
modules = [...] # some list of modules
for module in modules:
self.add_module(...)
nn.Module
s have a hierarchy of child modules that you can access via methods like module.named_children()
or module.children()
. nn.Module
具有子模块的层次结构,您可以通过module.named_children()
或module.children()
等方法访问这些子模块。
As mentioned in the forum post above, doing self._other module = other_module
will type check other_module
, see it's an nn.Module
, and also add it to the child list, so add_module
isn't really necessary.正如上面论坛帖子中提到的那样,执行
self._other module = other_module
将检查other_module
,看到它是一个nn.Module
,并将其添加到子列表中,因此add_module
并不是真正必要的。
Adding a module as an attribute works fine, as you say.正如您所说,将模块添加为属性可以正常工作。 But it can be a bit difficult to do at runtime if you don't know how many modules you have in advance, and you have to construct names programmatically.
但是如果你事先不知道你有多少个模块,并且你必须以编程方式构造名称,那么在运行时可能会有点困难。 In such a case,
add_module()
is a very convenient way to do this.在这种情况下,
add_module()
是一种非常方便的方法。 I've just written a short blog post showing this in action: https://blog.d-and-j.net/deep-learning/2021/04/23/pytorch-add_module.html我刚刚写了一篇简短的博客文章,展示了这一点: https://blog.d-and-j.net/deep-learning/2021/04/23/pytorch-add_module.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.