import numpy as npdef 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.shapeF, _, HH, WW = kernels.shapeinputs_pad = np.pad(inputs, ((0, 0), (padding, padding), (padding, padding)))H_out = 1 + (H + 2 * padding - HH) // strideW_out = 1 + (W + 2 * padding - WW) // strideoutputs = 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)) + biasreturn outputsinputs = np.random.rand(3, 5, 5)kernels = np.random.rand(4, 3, 3, 3)bias = np.random.rand(4)stride = 1padding = 1outputs = conv2d(inputs, kernels, bias, stride, padding)print("卷积后的输出形状:", outputs.shape)