cnn的原理可以查看百度的一些介绍,主要是利用划窗进行矩阵的对应相乘运算
class conv():
def __init__(self,in_channles,out_channles,kernel=3,stride=1,padding=0):
self.in_channles = in_channles
self.out_channles =out_channles
self.kernel = kernel
self.stride = stride
self.padding = padding
self.filter = np.random.random((3,3,3))
self.bias = np.zeros(out_channles)
def numpy_conv(self,inputs,filter,out_shape):
filter_size = filter.shape[0]
result = np.zeros(out_shape)
H, W = out_shape
for r in range(0, H):
for c in range(0, W):
# 池化大小的输入区域
cur_input = inputs[r*self.stride:r*self.stride + filter_size,
c*self.stride:c*self.stride + filter_size]
cur_output = cur_input * filter
conv_sum = np.sum(cur_output)
result[r, c] = conv_sum
return result
def forward(self, inputs):
N, C, H, W = inputs.shape
assert C==self.in_channles,"wwwwww %s %s"%(C,self.in_channles)
out_H = int((H - self.kernel + 2 * self.padding) / self.stride) + 1
out_W = int((W - self.kernel + 2 * self.padding) / self.stride) + 1
# print(out_H,out_W)
result = np.zeros([N,self.out_channles, out_H, out_W], np.float32)
inputs = np.pad(inputs, ((0, 0),(0, 0), (self.padding, self.padding), (self.padding, self.padding)), 'constant',
constant_values=(0, 0))
for n in range(N):
for i in range(self.out_channles):
result[n, i, :, :] = self.bias[i]
for j in range(self.in_channles):
channel_data = inputs[n,j]
# 采用上面对逻辑,单核单通道卷积,然后累计
result[n, i, :, :] += self.numpy_conv(channel_data, self.filter[i][j] ,(out_H,out_W))
return result