二维卷积的动手实现
作者:互联网
#学自深度学习5.1章
在二维互相关运算中,卷积窗口从输入数组的最左上方开始,按从左往右、从上往下的顺序,依次在输入数组上滑动。当卷积窗口滑动到某一位置时,窗口中的输入子数组与核数组按元素相乘并求和,得到输出数组中相应位置的元素。图5.1中的输出数组高和宽分别为2,其中的4个元素由二维互相关运算得出:
0×0+1×1+3×2+4×3=19,
1×0+2×1+4×2+5×3=25,
3×0+4×1+6×2+7×3=37,
4×0+5×1+7×2+8×3=43.
import torch
def corr2d(x,k):
k_h,k_w = k.shape
y=torch.zeros(x.shape[0]+1-k_h, x.shape[1]+1-k_w)
#如果是full_corr2d,可以修改y的shape
for i in range(y.shape[0]):
for j in range(y.shape[1]):
y[i,j]=(x[i:i+k_h, j:j+k_w]*k).sum()
return y
X = torch.tensor([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
K = torch.tensor([[0, 1], [2, 3]])
print(corr2d(X, K))
#tensor([[19., 25.],
# [37., 43.]])
features map(valid_corr2d)
shape[0] = (X.shape[0]+stride-K.shape[0]) / stride
shape[1] = (X.shape[1]+stride-K.shape[1]) / stride
标签:tensor,stride,卷积,torch,shape,corr2d,动手,二维,数组 来源: https://blog.csdn.net/Hu_Linson/article/details/121439470