代码之家  ›  专栏  ›  技术社区  ›  Samuel T

优化在numpy数组中的非零值周围创建缓冲区的函数的性能

  •  1
  • Samuel T  · 技术社区  · 2 年前

    我有一个函数,它采用一个二维数组,如果原始数组中的值(水平、垂直或对角)紧挨着一个非零值,则返回一个形状相同的数组,该数组的值为1,否则为0。

    例如,如果您有以下输入数组:

    array([[10,  0,  0,  0,  0],
           [ 0,  0,  2,  0,  0],
           [ 0,  0,  0,  0,  0]])
    

    输出将是

    array([[1, 1, 1, 1, 0],
           [1, 1, 1, 1, 0],
           [0, 1, 1, 1, 0]])
    

    我目前的做法是创建数组的一个副本,在每个方向上移动,然后在所有副本中获取每个索引的最大值。

    这对于一个小数组来说很好,但我需要在非常大的数组上运行,这需要很长时间。我正在寻求帮助,以显著减少大型阵列的执行时间。我觉得用numpy有一种有效的方法可以做到这一点,但我想不通。这是我想出的代码:

    def shift_array(arr, direction):
        direction_map = {'left':'-x','right':'+x','up':'+y','down':'-y'}
        if direction not in direction_map.keys():
            raise ValueError(f'{direction} is not in {list(direction_map.keys())}')
        direction_val = direction_map[direction]
        direction_xy = direction_val[1]
        direction_sign = direction_val[0]
        
        if direction_xy == 'x':
            if direction_sign == '-':
                return [[val for val in arr[i][1:]]+[0] for i in range(arr.shape[0])]
            elif direction_sign == '+':
                return [[0]+[val for val in arr[i][:-1]] for i in range(arr.shape[0])]
        elif direction_xy == 'y':
            if direction_sign == '+':
                return [list(val) for val in arr[1:]]+[[0 for _ in arr[0]]]
            elif direction_sign == '-':
                return [[0 for _ in arr[0]]]+[list(val) for val in arr[:-1]]
        
    
    def apply_shifts(input_array):
        arr = input_array.copy()
        arr = np.where(arr>0, 1, 0)
        arrays = [arr]
        directions = ['left','right','up','down', ['left','down'], ['right','down'],['left','up'],['right','up']]
        for direction in directions:
            if isinstance(direction, str):
                arrays.append(shift_array(arr, direction))
            else:
                tmp_arr = shift_array(arr, direction[0])
                arrays.append(shift_array(tmp_arr, direction[1]))
                
        shape = (len(arrays), len(arrays[0]), len(arrays[0][0]))
        max_array = np.array([np.max([arrays[i][j][k] for i in range(shape[0])]) for j in range(shape[1]) for k in range(shape[2])])
        
        return max_array.reshape(arr.shape)
    
    # example array
    import numpy as np
    arr1=np.array([[10,0,0,0,0],[0,0,2,0,0],[0,0,0,0,0]])
    res=apply_shifts(arr1)
    

    我很感激任何帮助,如果我遗漏了什么,我很乐意提供更多细节。

    1 回复  |  直到 2 年前
        1
  •  1
  •   Andrej Kesely    2 年前

    你想做的IIUC convolution 带有“all-ones”内核:

    from scipy.ndimage import convolve
    
    arr = np.array([[10, 0, 0, 0, 0], [0, 0, 2, 0, 0], [0, 0, 0, 0, 0]])
    kernel = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
    
    out = convolve(arr, kernel).astype(bool).astype(int)
    print(out)
    

    打印:

    [[1 1 1 1 0]
     [1 1 1 1 0]
     [0 1 1 1 0]]