Python pytorch model.parameter的形状与它的形状不一致';它在模型中定义

Python pytorch model.parameter的形状与它的形状不一致';它在模型中定义,python,machine-learning,pytorch,Python,Machine Learning,Pytorch,我试图从PyTorch中构建的简单网络中提取权重和偏差。我的整个网络由nn.线性层组成。当我通过调用nn.Linear(in\u dim,out\u dim)来创建一个层时,我希望从调用model.parameters()得到的该模型的参数对于权重是形状(in\u dim,out\u dim),对于偏差是形状。但是,来自model.parameters()的权重代替了形状(out\u dim,in\u dim) 我的代码的目的是能够使用矩阵乘法来执行仅使用numpy而不是任何PyTorch的前向

我试图从PyTorch中构建的简单网络中提取权重和偏差。我的整个网络由nn.线性层组成。当我通过调用
nn.Linear(in\u dim,out\u dim)
来创建一个层时,我希望从调用
model.parameters()
得到的该模型的参数对于权重是形状
(in\u dim,out\u dim)
,对于偏差是形状
。但是,来自
model.parameters()
的权重代替了形状
(out\u dim,in\u dim)

我的代码的目的是能够使用矩阵乘法来执行仅使用numpy而不是任何PyTorch的前向传递。由于形状不一致,矩阵乘法会产生错误。我怎样才能解决这个问题

这是我的确切密码:

class RNN(nn.Module):

    def __init__(self, dim_input, dim_recurrent, dim_output):

        super(RNN, self).__init__()

        self.dim_input = dim_input
        self.dim_recurrent = dim_recurrent
        self.dim_output = dim_output

        self.dense1 = nn.Linear(self.dim_input, self.dim_recurrent)
        self.dense2 = nn.Linear(self.dim_recurrent, self.dim_recurrent, bias = False)
        self.dense3 = nn.Linear(self.dim_input, self.dim_recurrent)
        self.dense4 = nn.Linear(self.dim_recurrent, self.dim_recurrent, bias = False)
        self.dense5 = nn.Linear(self.dim_recurrent, self.dim_output)

#There is a defined forward pass

model = RNN(12, 100, 6)

for i in model.parameters():
    print(i.shape())
输出为:

torch.Size([100, 12])
torch.Size([100])
torch.Size([100, 100])
torch.Size([100, 12])
torch.Size([100])
torch.Size([100, 100])
torch.Size([6, 100])
torch.Size([6])
如果我正确的话,输出应该是:

torch.Size([12, 100])
torch.Size([100])
torch.Size([100, 100])
torch.Size([12, 100])
torch.Size([100])
torch.Size([100, 100])
torch.Size([100, 6])
torch.Size([6])

我的问题是什么?

你看到的不是(外维度,内维度),而是权重矩阵的形状。当您调用
print(model)
时,您可以看到输入和输出功能是正确的:

RNN(
  (dense1): Linear(in_features=12, out_features=100, bias=True)
  (dense2): Linear(in_features=100, out_features=100, bias=False)
  (dense3): Linear(in_features=12, out_features=100, bias=True)
  (dense4): Linear(in_features=100, out_features=100, bias=False)
  (dense5): Linear(in_features=100, out_features=6, bias=True)
)
在调用
matmul
之前,您可以检查源代码以查看权重实际上是转置的


nn.Linear
定义如下:

您可以向前查看
,它看起来如下所示:

def forward(self, input):
    return F.linear(input, self.weight, self.bias)

F.linear
定义如下:

用于乘以权重的相应行为:

output = input.matmul(weight.t())
如上所述,在应用
matmul
之前,您可以看到权重转置的,因此权重的形状与您预期的不同。

因此,如果要手动执行矩阵乘法,请执行以下操作:

# dummy input of length 5
input = torch.rand(5, 12)
# apply layer dense1 (without bias, for bias just add + model.dense1.bias)
output_first_layer = input.matmul(model.dense1.weight.t())
print(output_first_layer.shape)
正如您从
dense1所期望的那样,它返回:

torch.Size([5, 100])

我希望这能解释你的观察结果:)

请分享相关代码并强调确切的问题重量被转换的原因是什么?@SamuelcarCenter实际上我不知道:)我在这里问了一个问题:@SamuelcarCenter找到了这个问题的答案,你可以在我发布的链接上查看。