【问题标题】:Is there a way to set attribute of attribute?有没有办法设置属性的属性?
【发布时间】:2021-02-20 10:52:57
【问题描述】:

我目前正在尝试分配一个属性,请考虑以下示例:

net = timm.create_model(model_name='regnetx_002', pretrained=False)
net.head.fc = torch.nn.Linear(1111, 2)

这似乎工作得很好,但是,某些模型具有不同的属性,如下所示

net.classifier = torch.nn.Linear(1111,2) 

因此,我尝试动态设置属性。我已经设法检索了属性的名称,例如“head”和“fc”,但您似乎无法执行以下操作:

setattr(net, "head.fc", torch.nn.Linear(1111, 2)) 

因为它将创建一个新属性“head.fc”。我认为我的知识存在误解,因为我注意到当我打印模型的最后一层时,它看起来像:

  (head): ClassifierHead(
    (global_pool): SelectAdaptivePool2d (pool_type=avg, flatten=True)
    (fc): Linear(in_features=368, out_features=1000, bias=True)
  )
)

有什么方法可以动态实现我想要的。

【问题讨论】:

标签: python deep-learning pytorch


【解决方案1】:

setattr(net, "head.fc", torch.nn.Linear(1111, 2))

将在网上创建head.fc 属性。

我猜你想创建
setattr(net.head, "fc", torch.nn.Linear(1111, 2))

或动态:

setattr(getattr(net, "head"), "fc", torch.nn.Linear(1111, 2)).

如果您想要一个更通用的嵌套动态属性,您将为此添加一些帮助函数,如here 所述。

【讨论】:

    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 2021-02-05
    • 2017-09-02
    • 2013-10-29
    • 2010-10-24
    相关资源
    最近更新 更多