# 1、对input进行paddingimport numpy as npinput = nparange113reshape34pad = 1input_pad = npzerosinputshape0 + 2 pad inputshape1 + 2 padinput_padpadpad + inputshape0pad pad + inputshape1 = inputprintinput
4、增加输入通道
import numpy as np
input = np.random.randn(3, 4, 2) # 输入矩阵大小为 [C, H, W] pad = 1 stride = 2 kernel = np.random.randn(2, 2, 2) # 卷积核大小为 [C, K, K]
padding
input_pad = np.pad(input, ((0, 0), (pad, pad), (pad, pad)), mode='constant')
计算输出大小
output_h = int((input_pad.shape[1] - kernel.shape[1]) / stride) + 1 output_w = int((input_pad.shape[2] - kernel.shape[2]) / stride) + 1
初始化输出矩阵
output = np.zeros((output_h, output_w))
对每个位置进行卷积计算
for h in range(output_h): for w in range(output_w): # 截取对应位置的输入矩阵 input_slice = input_pad[:, h * stride:h * stride + kernel.shape[1], w * stride:w * stride + kernel.shape[2]] # 将输入矩阵展开成向量形式 input_vector = input_slice.reshape(-1) # 将卷积核展开成向量形式 kernel_vector = kernel.reshape(-1) # 计算卷积结果 output[h, w] = np.dot(input_vector, kernel_vector)
print("Input shape:", input.shape) print("Kernel shape:", kernel.shape) print("Output shape:", output.shape) print("Input:\n", input) print("Kernel:\n", kernel) print("Output:\n", output
原文地址: https://www.cveoy.top/t/topic/hKMe 著作权归作者所有。请勿转载和采集!