本文主要讲述最简单的线性回归函数:
y = w x + b y=wx+b y=wx+b在pytorch的实现,主要包括神经网络实现的基本步骤和nn.Linear的源码解读。
1. nn.Linear 源码解读
先看一下Linear类的实现:
源代码网址:https://pytorch.org/docs/stable/_modules/torch/nn/modules/linear.html
Linear继承于nn.Module,内部函数主要有__init__
,reset_parameters
, forward
和extra_repr
函数
__init__(self, in_features, out_features, bias=True)
- in_features:前一层网络神经元的个数
- out_features: 该网络层神经元的个数
以上两者决定了weight的形状[out_features , in_features]
- bias: 网络层是否有偏置,默认存在,且维度为
[out_features ]
,若bias=False,则该网络层无偏置。
接下来看一下,输入该网络层的形状(N, *, in_features)
,其中N为批量处理过成中每批数据的数量,*表示,单个样本数据中间可以包含很多维度,但是单个数据的最后一个维度的形状一定是in_features
.
经过该网络输出的形状为(N, *, out_features)
,其中计算过程为:
[ N , ∗ , i n _ f e a t u r e s ] ∗ [ o u t _ f e a t u r e s , i n _ f e a t u r e s ] T = [ N , ∗ , o u t _ f e a t u r