对 numpy 数组进行下采样的最佳方法是什么?

prd*_*dnr 8 python arrays numpy

我有一个 3 维 numpy 数组,形状为 Nx64x64。我想通过取平均值在维度 1 和维度 2 上对其进行下采样,从而产生形状为 Nx8x8 的新数组。

我有几个工作实现,但我觉得必须有一种更简洁的方法来实现它。

我最初尝试使用 np.split:

def subsample(inparray, n):
    inp = inparray.copy()
    res = np.moveaxis(np.array(np.hsplit(inp, inp.shape[1]/n)), 1, 0)
    res = np.moveaxis(np.array(np.split(res, inp.shape[2]/n, axis=3)), 1, 0)
    res = np.mean(res, axis=(3,4))
    return res
Run Code Online (Sandbox Code Playgroud)

我也尝试使用普通索引:

def subsample2(inparray, n):
    res = np.zeros((inparray.shape[0], n, n))
    lin = np.linspace(0, inparray.shape[1], n+1).astype(int)
    bounds = np.stack((lin[:-1], lin[1:]), axis=-1)

    for i, b in enumerate(bounds):
        for j, b2 in enumerate(bounds):
            res[:, i, j] = np.mean(inparray[:, b[0]:b[1], b2[0]:b2[1]], axis=(1,2))
    return res
Run Code Online (Sandbox Code Playgroud)

我曾想过使用 itertools.groupby,但它看起来也很复杂。

有谁知道一个干净的解决方案?

L_W*_*L_W 7

block_reduce模块中的函数形式有一个简洁的解决方案scikit-image链接到文档)。

它有一个非常简单的接口,可以通过应用诸如 之类的函数来对数组进行下采样numpy.mean。通过为块提供不同大小的元组,可以通过不同轴的不同因子来完成下采样。这是一个二维数组的示例;使用均值仅对轴 1 进行下采样 5:

import numpy as np
from skimage.measure import block_reduce

arr = np.stack((np.arange(1,20), np.arange(20,39)))

# array([[ 1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
#        [20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38]])

arr_reduced = block_reduce(arr, block_size=(1,5), func=np.mean, cval=np.mean(arr))

# array([[ 3. ,  8. , 13. , 17.8],
#        [22. , 27. , 32. , 33. ]])
Run Code Online (Sandbox Code Playgroud)