【问题标题】:How can I extract the weight and bias of Linear layers in PyTorch?如何在 PyTorch 中提取线性层的权重和偏差?
【发布时间】:2021-03-13 22:20:20
【问题描述】:

model.state_dict()model.parameters()model.named_parameters() 中,nn.Linear() 模块的权重和偏差分别包含,例如fc1.weightfc1.bias。有没有一种简单的pythonic方法来获取它们?

预期的示例与此类似:

layer = model['fc1']
print(layer.weight)
print(layer.bias)

【问题讨论】:

  • "那么有没有办法获取模型中的 nn.Linear() 模块列表?"你想得到模型中所有线性层的weightbias,还是一个特定的层?

标签: python pytorch torch


【解决方案1】:

您可以像这样恢复模型中每个线性层的命名参数:

from torch import nn

for layer in model.children():
    if isinstance(layer, nn.Linear):
        print(layer.state_dict()['weight'])
        print(layer.state_dict()['bias'])

【讨论】:

    【解决方案2】:

    从完整模型来看,没有。没有。但是你可以得到那个特定的Modulestate_dict(),然后你会有一个dictweightbias

    import torch
    
    m = torch.nn.Linear(3, 5)  # arbitrary values
    l = m.state_dict()
    
    print(l['weight'])
    print(l['bias'])
    

    您的代码中的等价物是:

    layer = model.fc1.state_dict()
    print(layer['weight'])
    print(layer['bias'])
    

    【讨论】:

    • 那么有没有办法在模型中获取nn.Linear() 模块的列表?
    • @Nourless 不确定我是否理解,但您始终可以在模型中使用 ModuleList
    【解决方案3】:

    从层中提取值。

    layer = model['fc1']
    print(layer.weight.data[0])
    print(layer.bias.data[0])
    

    您可以使用要提取的神经元值来代替 0 索引。

    >> nn.Linear(2,3).weight.data
    tensor([[-0.4304,  0.4926],
            [ 0.0541,  0.2832],
            [-0.4530, -0.3752]])
    

    【讨论】:

      猜你喜欢
      • 2021-11-07
      • 2018-07-09
      • 1970-01-01
      • 2020-02-02
      • 1970-01-01
      • 2019-11-18
      • 2021-11-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多