【问题标题】:Python - compute average absolute difference of element and neighbors in NumPy arrayPython - 计算 NumPy 数组中元素和邻居的平均绝对差
【发布时间】:2021-11-14 13:20:43
【问题描述】:

我正在寻找一种方法来计算 NumPy 数组中相邻元素之间的平均绝对差。即,给定一个数组,如

[[1, 2, 3],
 [4, 5, 6],
 [7, 8, 9]]

中间正方形的值为 2.5(又名(4+3+2+1+1+2+3+4)/8)。我知道使用 SciPy 的 correlate2d 您可以计算平均差异,但据我所知,不是平均 absolute 差异(即对于上面的示例,correlate2d 将给出 0 - @987654325 @ - 不是 2.5)。

在 Python 中有没有一种快速的方法来做到这一点?我不想遍历元素,因为这将多次运行非常大的数组。

【问题讨论】:

    标签: python arrays numpy scipy


    【解决方案1】:

    为什么不手写并numba.jit结果呢?

    arr = (np.arange(10**6)+1).reshape(10**3,10**3)
    
    @nb.njit
    def get_avg_abs_diff(arr):
        n,m = arr.shape
        out = np.empty((n,m))
        for i in range(n):
            for j in range(m):
                a = max(0,i-1)
                b = i+2
                c = max(0,j-1)
                d = j+2
                neighbours = arr[a:b,c:d]
                out[i,j] = np.sum(np.abs(neighbours-arr[i,j]))/(neighbours.shape[0]*neighbours.shape[1]-1)
        return out
    
    get_avg_abs_diff(arr)
    

    对于 1000 x 1000 阵列,这大约需要 160 毫秒(低于需要 10.6 秒的非 jited 版本)。

    我得到你的数组

    array([[2.66666667, 2.2       , 2.        ],
           [2.6       , 2.5       , 2.6       ],
           [2.        , 2.2       , 2.66666667]])
    

    【讨论】:

    • 这行得通——仍然没有correlate2d那么快,但已经足够好了!谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2014-10-31
    • 1970-01-01
    • 1970-01-01
    • 2018-06-17
    • 2020-10-03
    相关资源
    最近更新 更多