首页 > 解决方案 > 如何修复“torch.nn.Linear”的权重?

问题描述

  1. 我想知道为什么参数列表中有两个张量nn.linear??

  2. 我尝试设置参数,但没有成功。我该如何解决?

XX=torch.from_numpy(X)
YY=torch.from_numpy(Y)
Ytt=torch.from_numpy(Yt)
XX=XX.view(100,1)
YY=YY.view(100,1)
Ytt=Ytt.view(100,1)
class model(torch.nn.Module):
  def __init__(self):
    super(model,self).__init__()
    self.linear1 = torch.nn.Linear(1,2).double()
    self.linear2 = torch.nn.Linear(2,2).double()
    self.linear3 = torch.nn.Linear(2,1).double()
  
  def forward(self,x):
    x=F.relu(self.linear1(x))
    x=F.relu(self.linear2(x))
    x=self.linear3(x)
    return x

M=model()
L=nn.MSELoss()
print(list(M.linear1.parameters()))
list(M.linear1.parameters())[0]=torch.Tensor([[-0.1],
        [ 0.2]])

print(list(M.linear1.parameters()))

然后

[Parameter containing:
tensor([[-0.2288],
        [ 0.2211]], dtype=torch.float64, requires_grad=True), Parameter containing:
tensor([-0.9185, -0.2458], dtype=torch.float64, requires_grad=True)]
[Parameter containing:
tensor([[-0.2288],
        [ 0.2211]], dtype=torch.float64, requires_grad=True), Parameter containing:
tensor([-0.9185, -0.2458], dtype=torch.float64, requires_grad=True)]

标签: pythonpytorch

解决方案


每个都有两个参数张量nn.Linear:一个用于权重矩阵,另一个用于偏差。该层实现的功能是

y = Wx + b

您可以通过访问它来设置参数张量的值data

with torch.no_grad():
    M.linear1.weight.data[...] = torch.Tensor([[-0.1], [0.2]])

推荐阅读