首页 > 解决方案 > 2d numpy 数组中的平方和(形成一个正方形的 4 个值)。Python

问题描述

我正在寻找在矩阵内形成正方形的二维数组中的每个 4 点组合

in4x4 = np.array(([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,3,1,2]))
print(in4x4)
array([[1, 2, 3, 4],
       [2, 3, 4, 1],
       [3, 4, 1, 2],
       [4, 3, 1, 2]])

预期输出:

print(out3x3)
array([[ 8, 12, 12],
       [12, 12,  8],
       [14,  9,  6]]

目前我正在使用numpy.diff几个步骤。感觉应该有一个更清洁的方法。我目前做的计算示例:

diff3x4 = np.diff(a4x4,axis=0)
a3x4 = a4x4[0:3,:] * 2 + d3x4
d3x3 = np.diff(a3x4)
a3x3 = a3x4[:,0:3] * 2 + d3x3

是否有一个干净的可能矢量化的方法?速度令人担忧。看了scipy.convolve但似乎不适合我的目的,但也许我只是配置内核错误。

标签: pythonnumpy

解决方案


您可以使用 kerenl 进行 2-D 卷积以获得所需的结果。

实现二维卷积并测试您提供的输入的简单代码:

import numpy as np

def conv2d(a, f):
    s = f.shape + tuple(np.subtract(a.shape, f.shape) + 1)
    strd = np.lib.stride_tricks.as_strided
    subM = strd(a, shape = s, strides = a.strides * 2)
    return np.einsum('ij,ijkl->kl', f, subM)

in4x4 = np.array(([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,3,1,2]))
k = np.ones((2,2))

print(conv2d(in4x4, k))

输出:

[[ 8. 12. 12.]
 [12. 12.  8.]
 [14.  9.  6.]]

如果您可以使用内置函数,则可以使用如下所示:

import numpy as np
from scipy import signal
in4x4 = np.array(([1,2,3,4],[2,3,4,1],[3,4,1,2],[4,3,1,2]))
k = np.ones((2,2))
signal.convolve2d(in4x4, k, 'valid')

哪个输出:

array([[ 8., 12., 12.],
       [12., 12.,  8.],
       [14.,  9.,  6.]])

signal.convolve2d(in4x4, k, '有效')


推荐阅读