import numpy as np
def conv2d ( inputs, kernels, bias, stride, padding) :
"""
正向卷积操作
inputs: 输入数据,形状为 (C, H, W)
kernels: 卷积核,形状为 (F, C, HH, WW),C是图片输入层数,F是图片输出层数
bias: 偏置,形状为 (F,)
stride: 步长
padding: 填充
"""
C, H, W = inputs. shape
F, _, HH, WW = kernels. shape
inputs_pad = np. pad( inputs, ( ( 0 , 0 ) , ( padding, padding) , ( padding, padding) ) )
H_out = 1 + ( H + 2 * padding - HH) // stride
W_out = 1 + ( W + 2 * padding - WW) // stride
outputs = np. zeros( ( F, H_out, W_out) )
for i in range ( H_out) :
for j in range ( W_out) :
inputs_slice = inputs_pad[ : , i* stride: i* stride+ HH, j* stride: j* stride+ WW]
outputs[ : , i, j] = np. sum ( inputs_slice * kernels, axis= ( 1 , 2 , 3 ) ) + bias
return outputs
inputs = np. random. rand( 3 , 5 , 5 )
kernels = np. random. rand( 4 , 3 , 3 , 3 )
bias = np. random. rand( 4 )
stride = 1
padding = 1
outputs = conv2d( inputs, kernels, bias, stride, padding)
print ( "卷积后的输出形状:" , outputs. shape)