首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >pytorch模块中已初始化的类成员

问pytorch模块中已初始化的类成员
EN

Stack Overflow用户
提问于 2020-11-08 22:38:37
回答 1查看 93关注 0票数 3

在pytorch中声明模型时,声明和初始化模型类成员变量会神秘地阻止它被填充到构造函数中。这是预期的吗?如果有,原因何在?

使用带有component成员变量的示例模型测试下面的代码。组件的初始化值(例如None、数字或张量)不会改变行为。

代码语言:javascript
复制
import torch

class Lin1(torch.nn.Module):
    def __init__(self):
        super(Lin1, self).__init__()
        self.component = torch.nn.Linear(100,200)

class Lin2(torch.nn.Module):
    component = None
    def __init__(self):
        super(Lin2, self).__init__()
        self.component = torch.nn.Linear(100,200)

# instantiate and check member component
for cl in [Lin1, Lin2]:
    model = cl()
    print("\nModel:", cl)
    print("Component:", model.component)
    print("It's None?: ", model.component is None)
代码语言:javascript
复制
Model: <class '__main__.Lin1'>
Component: Linear(in_features=100, out_features=200, bias=True)
It's None?:  False

Model: <class '__main__.Lin2'>
Component: None
It's None?:  True
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-09 06:31:47

这是因为nn.Module覆盖了__getattr__,并且只有在component不在Lin2.__dict__中(也不在Lin2().__dict__中)的情况下,它才会像您预期的那样工作。因为component是一个类属性,所以它在Lin2.__dict__中,并且将像它应该返回的那样被返回。

当您编写self.x = nn.Linear(...)或任何其他nn.Module (甚至是nn.Buffer或nn.Parameter)时,x实际上是在名为_modules (或_buffers等)的字典中注册的。这样,当您请求self.component时,如果component已经在类或实例的__dict__中,Python将不会调用自定义nn.Module的__getattr__()。

您可以从nn.Module here查看__getattr__的源代码。here也做了类似的讨论。在PyTorch中也有一个关于从__getattr__更改为__getattribute__的discussion,但到目前为止,这是一个wontfix issue。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64739330

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档