【问题标题】:Easiest way to return sum of a matrix's neighbors in numpy在numpy中返回矩阵邻居总和的最简单方法
【发布时间】:2017-02-24 22:47:31
【问题描述】:

我正在尝试制作一个需要矩阵邻居(不包括自身)和 ex 的程序:

 matrix([[0, 0, 0],
        [1, 0, 1],
        [0, 1, 0]])  

会返回:

matrix([[1, 2, 1],
        [1, 3, 1],
        [2, 2, 2]])

我在这里有一个工作代码,但它又大又乱,而且我是 numpy 的新手,所以我需要一些帮助来清理和优化它。 (我觉得必须有更好的方法)

示例代码:

import numpy as np

def NiSum(m):
    new = []
    for x in range(m.shape[0]-1):
        row = []
        for y in range(m.shape[1]-1):
            Ni = 0
            for a in [1,1],[1,0],[1,-1],[0,1],[0,-1],[-1,1],[-1,0],[-1,-1]:
                Ni += m[x+a[0],y+a[1]]
            row.append(Ni)
        new.append(row)
    return np.matrix(new)


example = np.matrix('0 0 0 0 0 0 0 0; '*3+'0 0 0 1 1 1 0 0; '*3+'0 0 0 0 0 0 0 0;0 0 0 0 0 0 0 0 ')

NiSum(example)

感谢您的帮助!

【问题讨论】:

    标签: python python-3.x numpy matrix scipy


    【解决方案1】:

    您正在对 3x3 邻域中的所有值求和,但不包括元素本身。因此,我们可以使用Scipy's 2D convolution 并从中减去输入数组/矩阵以获得所需的输出,就像这样 -

    from scipy.signal import convolve2d
    
    convolve2d(a,np.ones((3,3),dtype=int),'same') - a
    

    示例运行 -

    In [11]: a
    Out[11]: 
    matrix([[0, 0, 0],
            [1, 0, 1],
            [0, 1, 0]])
    
    In [12]: convolve2d(a,np.ones((3,3),dtype=int),'same') - a
    Out[12]: 
    matrix([[1, 2, 1],
            [1, 3, 1],
            [2, 2, 2]])
    

    或者简单地形成一个核心,除零外,中心都是1,并使用相同的2D卷积-

    In [31]: kernel = np.array([[1,1,1],[1,0,1],[1,1,1]])
    
    In [32]: np.asmatrix(convolve2d(a,kernel,'same'))
    Out[32]: 
    matrix([[1, 2, 1],
            [1, 3, 1],
            [2, 2, 2]])
    

    【讨论】:

    • 感谢您的帮助,但我在尝试安装 scipy 时遇到了很多问题。
    • pip install scipy 不起作用,因为我没有 scipy mkl pip install numpy-mkl 不起作用,因为它找不到匹配的版本 pip install http://www.lfd.uci.edu/~gohlke/pythonlibs/numpy-1.11.2+mkl-cp35-cp35m-win32.whl 不起作用,因为 404 错误我'之前从来没有安装过一个数据包而不只是做pip install name所以我有点迷路了
    • @Whud 您可以在我相信的 Scipy 安装上发布一个新问题。我对那些安装步骤不太熟悉。
    • 我会这样做的。感谢所有帮助。
    【解决方案2】:

    定义一个函数,计算矩阵条目的所有邻居的总和(如果存在):

    def sumNeighbors(M,x,y):
        l = []
        for i in range(max(0,x-1),x+2): # max(0,x-1), such that no negative values in range() 
            for j in range(max(0,y-1),y+2):
                try:
                    t = M[i][j]
                    l.append(t)
                except IndexError: # if entry doesn't exist
                    pass
        return sum(l)-M[x][y] # exclude the entry itself
    

    然后您可以迭代矩阵中的每个条目并将其结果传递给新矩阵 N:

    import numpy as np
    
    M = [[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]] 
    
    M = np.asarray(M)
    N = np.zeros(M.shape)
    
    for i in range(M.shape[0]):
        for j in range(M.shape[1]):
            N[i][j] = sumNeighbors(M, i, j)
    
    print "Original matrix:\n", M
    print "Summed neighbors matrix:\n", N
    

    输出:

    Original matrix:
    [[1 2 3]
     [4 5 6]
     [7 8 9]]
    Summed neighbors matrix:
    [[ 11.  19.  13.]
     [ 23.  40.  27.]
     [ 17.  31.  19.]]
    

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 1970-01-01
      • 2019-04-09
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多