如何在PyTorch中提取线性层的权重和偏置?

4
model.state_dict()model.parameters()model.named_parameters()中,包含了nn.Linear()模块的权重和偏置项(weights and biases),例如fc1.weightfc1.bias。是否有一种简单的Pythonic方法来同时获取它们?
layer = model['fc1']
print(layer.weight)
print(layer.bias)

有没有一种方法可以获取模型中所有nn.Linear()模块的列表?您想获取模型中所有线性层的weightbias,还是只想获取其中一个特定的线性层? - iacob
4个回答

5
你可以像这样恢复模型中每个线性层的命名参数:
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
从图层中提取数值。
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]])

0
从整个模型来看,没有。但是你可以获取这个特定模块的state_dict(),然后你将得到一个包含权重和偏置的单一字典。
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'])

2
有没有一种方法可以获取模型中 nn.Linear() 模块的列表呢? - Nourless
@Nourless 不确定我是否理解了,但您始终可以在模型中拥有一个 ModuleList - Berriel

0

当我尝试在pytorch中进行原型设计并在C++/Eigen中重新实现时,我遇到了同样的问题。我可以读取json文件...

这是我想出来的方法,向我的模型类添加一个方法:


  def to_obj(self):
    data = {}
    for lname,child in self.named_children():
      ldict = {}
      data[lname] = ldict
      for key,tens in child.state_dict().items():
        ldict[key] = tens.numpy().tolist()
    return data

然后我使用保存

from json import dump

with open(FULLPATH,mode='w') as out:
    dump(model.to_obj(),out)

我的情况很简单,所以你可能需要区分子类的类型...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接