窗口最大的numpy [英] Windowed maximum in numpy
本文介绍了窗口最大的numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组,我想通过扫描一个2x2不重叠的窗口并获得最大的数组来产生一个较小的数组.这是一个示例:
I have an array and I would like to produce a smaller array by scanning a 2x2 non-overlappingly windows and getting the maximum. Here is an example:
import numpy as np
np.random.seed(123)
np.set_printoptions(linewidth=1000,precision=3)
arr = np.random.uniform(-1,1,(4,4))
res = np.zeros((2,2))
for i in xrange(res.shape[0]):
for j in xrange(res.shape[1]):
ii = i*2
jj = j*2
res[i][j] = max(arr[ii][jj],arr[ii+1][jj],arr[ii][jj+1],arr[ii+1][jj+1])
print arr
print res
所以像这样的矩阵:
[[ 0.393 -0.428 -0.546 0.103]
[ 0.439 -0.154 0.962 0.37 ]
[-0.038 -0.216 -0.314 0.458]
[-0.123 -0.881 -0.204 0.476]]
应该变成这个:
[[ 0.439 0.962]
[-0.038 0.476]]
我如何才能更有效地做到这一点?
How can I do this more efficiently?
推荐答案
您可以执行以下操作:
print arr.reshape(2,2,2,2).swapaxes(1,2).reshape(2,2,4).max(axis=-1)
[[ 0.439 0.962]
[-0.038 0.476]]
以以下内容开始解释:
arr=np.array([[0.393,-0.428,-0.546,0.103],
[0.439,-0.154,0.962,0.37,],
[-0.038,-0.216,-0.314,0.458],
[-0.123,-0.881,-0.204,0.476]])
我们首先要将轴分组为相关部分.
We first want to group the axes into relevant sections.
tmp = arr.reshape(2,2,2,2).swapaxes(1,2)
print tmp
[[[[ 0.393 -0.428]
[ 0.439 -0.154]]
[[-0.546 0.103]
[ 0.962 0.37 ]]]
[[[-0.038 -0.216]
[-0.123 -0.881]]
[[-0.314 0.458]
[-0.204 0.476]]]]
再次重塑以获得我们想要的数据组:
Reshape once more to obtain the groups of data we want:
tmp = tmp.reshape(2,2,4)
print tmp
[[[ 0.393 -0.428 0.439 -0.154]
[-0.546 0.103 0.962 0.37 ]]
[[-0.038 -0.216 -0.123 -0.881]
[-0.314 0.458 -0.204 0.476]]]
最后沿最后一个轴取最大值.
Finally take the max along the last axis.
对于平方矩阵,可以将其推广为:
This can be generalized, for square matrices, to:
k = arr.shape[0]/2
arr.reshape(k,2,k,2).swapaxes(1,2).reshape(k,k,4).max(axis=-1)
根据杰米(Jamie)和道格拉(Dougal)的评论,我们可以进一步概括一下:
Following the comments of Jamie and Dougal we can generalize this further:
n = 2 #Height of window
m = 2 #Width of window
k = arr.shape[0] / n #Must divide evenly
l = arr.shape[1] / m #Must divide evenly
arr.reshape(k,n,l,m).max(axis=(-1,-3)) #Numpy >= 1.7.1
arr.reshape(k,n,l,m).max(axis=-3).max(axis=-1) #Numpy < 1.7.1
这篇关于窗口最大的numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文