您可以将两个轴拆分为另外两个,从而生成一个长度为 2 的 4D 数组,每个数组作为这两个拆分轴中的第二个轴,这将是生成的 @987654323 中的第二个和第四个轴@ 大批。然后,只需沿着这两个轴找到 minimum 即可获得所需的输出。
因此,实现看起来像这样 -
m,n = M.shape
out = M.reshape(m//2,2,n//2,2).min(axis=(1,3))
示例运行 -
In [41]: M
Out[41]:
array([[33, 26, 15, 53, 72, 53],
[12, 64, 28, 27, 58, 51],
[61, 42, 70, 92, 61, 95],
[35, 62, 48, 27, 53, 33]])
In [42]: m,n = M.shape
In [43]: M.reshape(m//2,2,n//2,2).min(axis=(1,3))
Out[43]:
array([[12, 15, 51],
[35, 27, 33]])
在原始数组对应的每个子矩阵中获取argmins
为了获得这些 argmins,我们需要做一些额外的工作,如下所列 -
B = 2 # Blocksize
m,n = M.shape
# Reshape into 4D array as discussed for the previous problem
M4D = M.reshape(m//B,B,n//B,B)
# Bring the second and fourth axes together and then merge.
# Then, get linear indices within each submatrix
lidx = M4D.transpose(0,2,1,3).reshape(-1,n//B,B**2).argmin(-1)
# Convert those linear indices into row, col indices corresponding
# to submatrix and finally corresponding to the original array
r,c = np.unravel_index(lidx,[B,B])
row = r + (B*np.arange(m//B)[:,None])
col = c + B*np.arange(n//B)
样本输入、输出-
In [170]: M
Out[170]:
array([[40, 91, 90, 72, 86, 44],
[63, 56, 20, 95, 60, 41],
[28, 50, 32, 89, 69, 46],
[41, 41, 33, 81, 30, 63]])
In [171]: np.column_stack((row.ravel(),col.ravel()))
Out[171]:
array([[0, 0],
[1, 2],
[1, 5],
[2, 0],
[2, 2],
[3, 4]])