PyTorch - 模型参数权重的意外形状

问题描述 投票:0回答:1

我在Pytorch中创建了一个完全连接的网络,输入层的形状为 (1,784) 和形状的第一隐藏层 (1,256). 要短。nn.Linear(in_features=784, out_features=256, bias=True)

方法一: model.fc1.weight.data.shape 给我 torch.Size([128, 256])

方法二: list(model.parameters())[0].shape 给我 torch.Size([256, 784])

事实上,在784大小的输入层和256大小的隐藏层之间,我期待的是一个形状为 (784,256). 所以,在第一种情况下,我看到了下一个隐藏层(128)的形状,这对于输入层和第一个隐藏层之间的权重来说是没有意义的,在第二种情况下,看起来Pytorch采取了权重矩阵的变换。

我不太明白Pytorch是如何塑造不同的权重矩阵的,训练后如何获取各个权重。我应该使用方法1还是2?当我显示相应的权重矩阵时,显示看起来完全相似,而形状却不同。

deep-learning neural-network pytorch tensor
1个回答
1
投票

在Pytorch中,模型参数的权重为 转位 敷设前 matmul 对输入矩阵进行操作。这就是为什么权重矩阵的维度是翻转的,而且与你所期望的不同;也就是说,与其说是 [784, 256]你观察到,它是 [256, 784].

你可以看到Pytorch的源码文档。nn.Linear,其中我们有。

...

self.weight = Parameter(torch.Tensor(out_features, in_features))

...

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

当我们看到执行 F.linear,我们看到相应的行,将输入矩阵与之相乘。换位 的权重矩阵。

output = input.matmul(weight.t())
© www.soinside.com 2019 - 2024. All rights reserved.