手写conv2d卷积不考虑batchsize和channel
参考b站up主deep_thoughs
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
# 不考虑BatchSize 维度 和channel 维度
def ManualConv2d_MatrixCaculation(input , kernel , bias = 0 , stride = 1 , padding = 0 ):
if(padding > 0):
input = F.pad(input , (padding ,padding ,padding ,padding))
input_h , input_w = input.shape
kernel_h , kernel_w = kernel.shape
output_w = (math.floor((input_h - kernel_h)/stride) + 1) # conv output wide
output_h = (math.floor((input_w - kernel_w)/stride) + 1) # conv output height
output = torch.zeros(output_h , output_w) # initial output matrix
for i in range(0 , input_h - kernel_h + 1 , stride): # 对高度维进行遍历
for j in range(0 , input_w - kernel_w + 1 , stride): # 对宽度维进行遍历
region = input[i : i + kernel_w , j : j + kernel_w] # kernel 正在覆盖的区域
output[int(i/stride) , int(j/stride)] = torch.sum(region * kernel) + bias
return output
input = torch.randn(5 ,5)
kernnel = torch.randn(3 ,3)
mat_mul_conv_output = ManualConv2d_MatrixCaculation(input , kernnel , padding= 1)
print(" mat_mul_conv_output : " , mat_mul_conv_output