是否有一个 numpy 有限的 argsort?

我有一个包含 1M 浮点数的数组,想要获得前 10 名。想知道是否有一个 argsort 只会给出前 10 名以加快速度。我想我可以执行 np.argmax() 10 次,每次都删除结果索引(可能是通过将其设为 -inf,从而不必跟踪移动索引)。只是检查是否有众所周知的内置方式。

不一定非要麻木。其次是另一个非常常见的库。

djdz123 回答:是否有一个 numpy 有限的 argsort?

你确实可以使用numpy.argpartition()

import numpy
a = numpy.random.rand(1000000)
b = numpy.argpartition(a,[0,1,2,3,4,5,6,7,8,9])[:10]

快了近 10 倍(在本例中,在我的机器上):

>>> import timeit,numpy
>>> a = numpy.random.rand(1000000)
>>> # Sorting traditionally
>>> timeit.timeit('numpy.argsort(a)[:10]',globals=globals(),number=100)
10.2261...
>>> # Getting the top 10 but not in order
>>> timeit.timeit('numpy.argpartition(a,10)[:10]',number=100)
1.2125...
>>> # Getting the top 10 in order
>>> timeit.timeit('numpy.argpartition(a,9])[:10]',number=100)
1.4764...
本文链接:https://www.f2er.com/1409.html

大家都在问