神经网络的正向传播中进行的矩阵的乘积运算在几何学领域被称为“仿射变换”。
“Affine层”的作用就是进行仿射变换。
理解“Affine层”的原理,需要掌握矩阵微分的知识。
矩阵微分的知识可参考:https://www.cnblogs.com/faranten/p/16028217.html
【Affine层的Python代码实现】
import numpy as np
class Affine:
def __init__(self,w,b):
self.w=w
self.b=b
self.x=None
self.dw=None
self.db=None
def forward(self,x):
self.x=x
out=np.dot(x,self.w)+self.b
return out
def backward(self,dout):
dx=np.dot(dout,self.w.T)
self.dw=np.dot(self.x.T,dout)
self.db=np.sum(dout,axis=0)
return dx
x=np.arange(6).reshape(2,3)
w=np.arange(6).reshape(3,2)
b=np.arange(4).reshape(2,2)
affine_layer=Affine(w,b)
qian_out=affine_layer.forward(x)
hou_out=affine_layer.backward(qian_out)
print(qian_out)
print("\n")
print(hou_out)
运行后,此代码的输出为:
[[10 14]
[30 43]]
[[ 14 62 110]
[ 43 189 335]]