Python 如何将二维矩阵划分为面片,并将每个面片与其中心元素相乘?

Python 如何将二维矩阵划分为面片,并将每个面片与其中心元素相乘?,python,numpy,convolution,Python,Numpy,Convolution,我需要将一个2D矩阵分解成一组具有一定步幅的2D面片,然后将每个面片与其中心元素相乘,并将每个面片的元素相加 它感觉就像是一个卷积,矩阵的每个元素都使用一个单独的内核 下面是一个直观的说明。 结果矩阵的元素计算如下: 结果应该如下所示: 我想出了一个解决方案: window_shape = (2, 2) stride = 1 # Matrix m = np.arange(1, 17).reshape((4, 4)) # Pad it once per axis to make su

我需要将一个2D矩阵分解成一组具有一定步幅的2D面片,然后将每个面片与其中心元素相乘,并将每个面片的元素相加

它感觉就像是一个卷积,矩阵的每个元素都使用一个单独的内核

下面是一个直观的说明。 结果矩阵的元素计算如下:

结果应该如下所示:

我想出了一个解决方案:

window_shape = (2, 2)
stride = 1

# Matrix
m = np.arange(1, 17).reshape((4, 4))

# Pad it once per axis to make sure the number of views
# equals the number of elements
m_padded = np.pad(m, (0, 1))

# This function divides the array into `windows`, from:
# https://stackoverflow.com/questions/45960192/using-numpy-as-strided-function-to-create-patches-tiles-rolling-or-sliding-w#45960193
w = window_nd(m_padded, window_shape, stride)
ww, wh, *_ = w.shape
w = w.reshape((ww * wh, 4))  # Two first dimensions multiplied is the number of rows

# Tile each center element for element-wise multiplication
m_tiled = np.tile(m.ravel(), (4, 1)).transpose()

result = (w * m_tiled).sum(axis = 1).reshape(m.shape)
在我看来,这不是很有效,因为在中间步骤中分配了一些数组

实现这一目标的更好或更有效的方法是什么?

试试看

输出:

array([[ 14.,  36.,  66.,  48.],
       [150., 204., 266., 160.],
       [414., 500., 594., 336.],
       [351., 406., 465., 256.]])
array([[ 14.,  36.,  66.,  48.],
       [150., 204., 266., 160.],
       [414., 500., 594., 336.],
       [351., 406., 465., 256.]])