【问题标题】:PyTorch: access weights of a specific module in nn.Sequential()PyTorch:在 nn.Sequential() 中访问特定模块的权重
【发布时间】:2017-11-01 05:49:48
【问题描述】:

当我在 PyTorch 中使用预定义模块时,我通常可以相当轻松地访问它的权重。但是,如果我先将模块包装在nn.Sequential() 中,如何访问它们? r.g:

class My_Model_1(nn.Module):
    def __init__(self,D_in,D_out):
        super(My_Model_1, self).__init__()
        self.layer = nn.Linear(D_in,D_out)
    def forward(self,x):
        out = self.layer(x)
        return out

class My_Model_2(nn.Module):
    def __init__(self,D_in,D_out):
        super(My_Model_2, self).__init__()
        self.layer = nn.Sequential(nn.Linear(D_in,D_out))
    def forward(self,x):
        out = self.layer(x)
        return out

model_1 = My_Model_1(10,10)
print(model_1.layer.weight)
model_2 = My_Model_2(10,10)

我现在如何打印重量? model_2.layer.0.weight 不起作用。

【问题讨论】:

    标签: python pytorch


    【解决方案1】:

    访问权重的一种简单方法是使用模型的state_dict()

    这应该适用于您的情况:

    for k, v in model_2.state_dict().iteritems():
        print("Layer {}".format(k))
        print(v)
    

    另一个选择是获取modules() 迭代器。如果您事先知道图层的类型,这也应该有效:

    for layer in model_2.modules():
       if isinstance(layer, nn.Linear):
            print(layer.weight)
    

    【讨论】:

    • 嗨!感谢您的回复。我还在 PyTorch 论坛上发帖,找到了推荐的方法。我在下面发布了答案。
    【解决方案2】:

    来自PyTorch forum,这是推荐的方式:

    model_2.layer[0].weight
    

    【讨论】:

    • 这个方法已经不行了。使用 modules() 方法可以访问模块迭代器。
    • 这种方法对我来说仍然有效。如果您将模型包装在 DataParallel 中,它曾经会中断,我认为它仍然会中断。但这不是该线程中提出的原始问题。 (PyTorch 1.5)
    • @mbpaulus 不,它没有
    • 我不知道你们在做什么,但这在 Pytorch 1.6.0 中工作得很好。我刚刚又测试了一次。如果你愿意,我可以把笔记本发给你。
    【解决方案3】:

    您可以使用 _modules 按名称访问模块:

    class Net(nn.Module):
        def __init__(self):
            super(Net, self).__init__()
    
            self.conv1 = nn.Conv2d(3, 3, 3)
    
        def forward(self, input):
            return self.conv1(input)
    
    model = Net()
    print(model._modules['conv1'])
    

    【讨论】:

      猜你喜欢
      • 2019-10-19
      • 2021-02-12
      • 1970-01-01
      • 2021-05-11
      • 1970-01-01
      • 2022-08-10
      • 2020-10-07
      • 2021-05-14
      • 1970-01-01
      相关资源
      最近更新 更多