pytorch nn.Linear的理解

单个sample的Linear数学表达式

pytorch nn.Linear的理解
上图是前向传播的一个简单示例图。首先说明下该图中各个数学符号的含义:
XX:单个sample的向量表达;
xix_i:输入sample向量的第ii维;
W(l)W^{(l)}Layerl1Layer_{l-1}LayerlLayer_{l}的前向传播权重矩阵;
wij(l)w_{ij}^{(l)}:权重矩阵W(l)W^{(l)}的元素,j{j}表示Layerl1Layer_{l-1}中第jj个元素,ii表示LayerlLayer_{l}中第ii个元素,wijw_{ij}表示jjii的连接权重;
Z(l)Z^{(l)}LayerlLayer_l接受到的刺激信号向量;
zi(l)z_i^{(l)}LayerlLayer_l接受到的刺激信号向量中的第ii个值;
A(l)A^{(l)}LayerlLayer_l的**值向量;
ai(l)a_i^{(l)}LayerlLayer_l对应zi(l)z_i^{(l)}的**值;
这里主要写一下Layer 1到Layer 2的前向传播数学表达式:
z1(2)=w11(2)x1+w12(2)x2+w13(2)x3z2(2)=w21(2)x1+w22(2)x2+w23(2)x3z3(2)=w31(2)x1+w32(2)x2+w33(2)x3 z_1^{(2)}=w_{11}^{(2)}x_1+w_{12}^{(2)}x_2+w_{13}^{(2)}x_3 \\ z_2^{(2)}=w_{21}^{(2)}x_1+w_{22}^{(2)}x_2+w_{23}^{(2)}x_3 \\ z_3^{(2)}=w_{31}^{(2)}x_1+w_{32}^{(2)}x_2+w_{33}^{(2)}x_3
在深度学习中,这样的表达式过于繁琐,通常使用矩阵来进行简洁的表达。上述表达式的矩阵表达为:
[z1(2)z2(2)z3(2)]=[w11(2)w12(2)w13(2)w21(2)w22(2)w23(2)w31(2)w32(2)w33(2)][x1x2x3]+[b1(2)b2(2)b3(3)](1) \left[ \begin{matrix} z_1^{(2)} \\ z_2^{(2)} \\ z_3^{(2)} \end{matrix} \right]=\left[ \begin{matrix} w_{11}^{(2)} & w_{12}^{(2)} & w_{13}^{(2)} \\ w_{21}^{(2)} & w_{22}^{(2)} & w_{23}^{(2)} \\ w_{31}^{(2)} & w_{32}^{(2)} & w_{33}^{(2)} \end{matrix} \right]\left[ \begin{matrix} x_1 \\ x_2 \\ x_3 \end{matrix} \right]+\left[ \begin{matrix} b_1^{(2)} \\ b_2^{(2)} \\ b_3^{(3)} \end{matrix} \right] \tag{1}
Z(l)=W(l)X+B(l)(2)Z^{(l)}=W^{(l)}X+B^{(l)}\tag{2}
公式(2)中的Z(l)Z^{(l)}XX都是列向量

pytorch nn.Linear

torch.nn.Linear(in_features, out_features, bias=True)
官方文档的注释:
Applies a linear transformation to the incoming data:y=xAT+by=xA^T+b
对比公式(2),可以发现AA其实就是WW,但是两者的表达还是有些不同的。
个人理解:公式(2)是针对单个sample的数学推导,其中单个sample是以列向量的形式表达的,但是在神经网络的训练中一般是使用batch train,这个时候就要使用sample matrix了。xx表示sample matrix,矩阵的每一行表示一个sample,即xx的size为batchsizein_featuresbatchsize*in\_featuresin_featuresin\_features表示上一层的输出维度。yy的size为batch_sizeout_featuresbatch\_size*out\_featuresout_featuresout\_features表示该层的输出维度,即该层的隐藏神经元个数。单个sample时,我们用列向量来表示sample,但是在sample matrix时,我们有行向量表示一个sample,所以矩阵AA需要转置。
batch_sizein_featuresin_featuresout_features=batch_sizeout_featuresbatch\_size*in\_features*in\_features*out\_features=batch\_size*out\_features
矩阵AA的维度是out_featuresin_featuresout\_features*in\_features,这和WW的形式是相同的。
之所以要转置,估计是因为batch train的原因。
pytorch nn.Linear的理解
关于shape的理解:
对于二维sample matrix,*表示batch_size,三维sample matrix,N可以理解为channel;不管有多少维,理解的时候从最后一维开始理解,最后一维表示一个样本的维度,前一维表示多少个样本,最后两维表示构成一个sample matrix;再往前一维表示有多少个这样的sample matrix;更多的维度按照这样的方式去理解就比较容易了。
#preference:
1、https://zhuanlan.zhihu.com/p/71892752
2、https://pytorch.org/docs/stable/nn.html#linear-layers