快速查找二维数组中的多个最大值

The*_*ude 5 python arrays performance numpy max

情况如下:

我有一个2D numpy数组.它的形状是(1002,1004).每个元素包含0到Inf之间的值.我现在要做的是确定前1000个最大值并将相应的索引存储到名为x的列表和名为y的列表中.这是因为我想绘制最大值,而索引实际上对应于值的实时x和y位置.

到目前为止我所拥有的是:

x = numpy.zeros(500)
y = numpy.zeros(500)

for idx in range(500):
    x[idx] = numpy.unravel_index(full.argmax(), full.shape)[0]
    y[idx] = numpy.unravel_index(full.argmax(), full.shape)[1]
    full[full == full.max()] = 0.

print os.times()
Run Code Online (Sandbox Code Playgroud)

这里是我的2D numpy数组.从for循环可以看出,我现在只确定前500个最大值.然而,这已经需要大约5秒.对于前1000个最大值,用户时间实际上应该在0.5秒左右.我注意到一个非常耗时的部分是每次将之前的最大值设置为0.我怎样才能加快速度?

非常感谢!

War*_*ser 12

如果你有numpy 1.8,你可以使用这个argpartition功能或方法.这是一个计算的脚本,x并且y:

import numpy as np

# Create an array to work with.
np.random.seed(123)
full = np.random.randint(1, 99, size=(8, 8))

# Get the indices for the largest `num_largest` values.
num_largest = 8

indices = (-full).argpartition(num_largest, axis=None)[:num_largest]
# OR, if you want to avoid the temporary array created by `-full`:
# indices = full.argpartition(full.size - num_largest, axis=None)[-num_largest:]

x, y = np.unravel_index(indices, full.shape)

print("full:")
print(full)
print("x =", x)
print("y =", y)
print("Largest values:", full[x, y])
print("Compare to:    ", np.sort(full, axis=None)[-num_largest:])
Run Code Online (Sandbox Code Playgroud)

输出:

full:
[[67 93 18 84 58 87 98 97]
 [48 74 33 47 97 26 84 79]
 [37 97 81 69 50 56 68  3]
 [85 40 67 85 48 62 49  8]
 [93 53 98 86 95 28 35 98]
 [77 41  4 70 65 76 35 59]
 [11 23 78 19 16 28 31 53]
 [71 27 81  7 15 76 55 72]]
x = [0 2 4 4 0 1 4 0]
y = [6 1 7 2 7 4 4 1]
Largest values: [98 97 98 98 97 97 95 93]
Compare to:     [93 95 97 97 97 98 98 98]
Run Code Online (Sandbox Code Playgroud)

  • +1这可能是1.8中最酷的算法补充.虽然从示例中看起来很明显,并且它不是OP问题中的要求,但可能值得强调的是,`partition`函数不会对它们对数组进行分区的块进行排序. (2认同)