pytorch中Linear类中weight的形状问题源码探讨

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dss_dssssd/article/details/83537765
import torch
from torch import nn

m = nn.Linear(20, 30)
input = torch.randn(128, 20)
output = m(input)

print(output.size())
print(m.weight.shape)

来看一下输出:
out:

torch.Size([128, 30])
torch.Size([30, 20])

发现weight的形状是[30,20]而非[20, 30]?

所以具体看一下源码的实现方式:

  1. 在Linear类中的__init__函数中,weight形状为[out_features, in_features]
    在这里插入图片描述
  2. forward函数中调用F.linear函数,实现单层线性神经网络层的计算
    在这里插入图片描述
  3. 在F.linear函数中,使用的是weight.t(),也就是将weight转置,再传入matmul计算。
    在这里插入图片描述

通过以上三步,pytorch就完成weight形状的维护。简单的说就是,在定义时使用的是[out_features, in_features],而在单层线性神经网络计算时使用的是weight的转置矩阵。

猜你喜欢

转载自blog.csdn.net/dss_dssssd/article/details/83537765