我有一个 2D Numpy ndarray,x,我需要将其拆分为大小为 s 的正方形子区域。对于每个子区域,我想获得最大的元素(我这样做了),以及它在该子区域中的位置(我无法弄清楚)。
这是一个最小的例子:
>>> x = np.random.randint(0, 10, (6,8))
>>> x
array([[9, 4, 8, 9, 5, 7, 3, 3],
[3, 1, 8, 0, 7, 7, 5, 1],
[7, 7, 3, 6, 0, 2, 1, 0],
[7, 3, 9, 8, 1, 6, 7, 7],
[1, 6, 0, 7, 5, 1, 2, 0],
[8, 7, 9, 5, 8, 3, 6, 0]])
>>> h, w = x.shape
>>> s = 2
>>> f = x.reshape(h//s, s, w//s, s)
>>> mx = np.max(f, axis=(1, 3))
>>> mx
array([[9, 9, 7, 5],
[7, 9, 6, 7],
[8, 9, 8, 6]])
例如mx左下角的8是子区域[[1,6], [8, 7]中的最大元素]在x的左下角。
我想要的是得到一个类似于mx 的数组,它保留最大元素的索引,如下所示:
[[0, 1, 1, 2],
[0, 2, 3, 2],
[2, 2, 2, 2]]
其中,例如左下角的2是[[1, 6]线性表示中。8的索引,[ 8, 7]]
我可以这样做:np.argmax(f[i, :, j, :]) 并遍历 i 和 j,但是对于大量的计算速度差异是巨大的。为了给你一个想法,我正在尝试(仅)使用 Numpy 来处理 max pooling .基本上,我是在问是否有比我正在使用的更快的替代方案。
请您参考如下方法:
这是一种方法-
# Get shape of output array
m,n = np.array(x.shape)//s
# Reshape and permute axes to bring the block as rows
x1 = x.reshape(h//s, s, w//s, s).swapaxes(1,2).reshape(-1,s**2)
# Use argmax along each row and reshape to output shape
out = x1.argmax(1).reshape(m,n)
示例输入、输出-
In [362]: x
Out[362]:
array([[9, 4, 8, 9, 5, 7, 3, 3],
[3, 1, 8, 0, 7, 7, 5, 1],
[7, 7, 3, 6, 0, 2, 1, 0],
[7, 3, 9, 8, 1, 6, 7, 7],
[1, 6, 0, 7, 5, 1, 2, 0],
[8, 7, 9, 5, 8, 3, 6, 0]])
In [363]: out
Out[363]:
array([[0, 1, 1, 2],
[0, 2, 3, 2],
[2, 2, 2, 2]])
或者,为了简化事情,我们可以使用 scikit-image这为我们做了 reshape 和排列轴的繁重工作 -
In [372]: from skimage.util import view_as_blocks as viewB
In [373]: viewB(x, (s,s)).reshape(-1,s**2).argmax(1).reshape(m,n)
Out[373]:
array([[0, 1, 1, 2],
[0, 2, 3, 2],
[2, 2, 2, 2]])
