Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/317.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 基于邻域和的三维阵列子采样_Python_Arrays_Numpy_Binning_Subsampling - Fatal编程技术网

Python 基于邻域和的三维阵列子采样

Python 基于邻域和的三维阵列子采样,python,arrays,numpy,binning,subsampling,Python,Arrays,Numpy,Binning,Subsampling,标题可能令人困惑。我有一个相当大的3D numpy阵列。我想通过组合大小为(2,2,2)的块将其大小减少2^3。然后,新3D数组中的每个元素都应包含原始数组中其各自块中的元素之和 作为一个例子,考虑一个4x4x4数组: input = [[[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]], [[1, 1, 2, 2], [1, 1, 2,

标题可能令人困惑。我有一个相当大的3D numpy阵列。我想通过组合大小为(2,2,2)的块将其大小减少2^3。然后,新3D数组中的每个元素都应包含原始数组中其各自块中的元素之和

作为一个例子,考虑一个4x4x4数组:

input = [[[1, 1, 2, 2],
          [1, 1, 2, 2],
          [3, 3, 4, 4],
          [3, 3, 4, 4]],
         [[1, 1, 2, 2],
          [1, 1, 2, 2],
          [3, 3, 4, 4],
          [3, 3, 4, 4]],
              ...    ]]]
(为了节省空间,我只代表了其中的一半)。请注意,具有相同值的所有元素构成一个(2x2x2)块。输出应为2x2x2数组,以便每个元素都是一个块的总和:

output = [[[8, 16],
          [24, 32]],
             ... ]]]

因此,8是所有1的总和,16是2的总和,依此类推。

有一个内置的模块来进行这些分块缩减--

使用其他减少UFUNC,例如
max reduction
-

In [40]: block_reduce(a, block_size=(2,2,2), func=np.max)
Out[40]: 
array([[[1, 2],
        [3, 4]]])
使用NumPy工具实现这样的功能并不困难,可以这样做-

def block_reduce_numpy(a, block_size, func):
    shp = a.shape
    new_shp = np.hstack([(i//j,j) for (i,j) in zip(shp,block_size)])
    select_axes = tuple(np.arange(a.ndim)*2+1)
    return func(a.reshape(new_shp),axis=select_axes)
def block_reduce_numpy(a, block_size, func):
    shp = a.shape
    new_shp = np.hstack([(i//j,j) for (i,j) in zip(shp,block_size)])
    select_axes = tuple(np.arange(a.ndim)*2+1)
    return func(a.reshape(new_shp),axis=select_axes)