【发布时间】:2014-11-08 11:26:00
【问题描述】:
我在 Python 中使用了很多 argmin 和 argmax。
很遗憾,这个功能很慢。
我做了一些搜索,我能找到的最好的在这里:
http://lemire.me/blog/archives/2008/12/17/fast-argmax-in-python/
def fastest_argmax(array):
array = list( array )
return array.index(max(array))
不幸的是,这个解决方案仍然只有 np.max 的一半,我想我应该能够找到与 np.max 一样快的东西。
x = np.random.randn(10)
%timeit np.argmax( x )
10000 loops, best of 3: 21.8 us per loop
%timeit fastest_argmax( x )
10000 loops, best of 3: 20.8 us per loop
作为说明,我将其应用于 Pandas DataFrame Groupby
例如
%timeit grp2[ 'ODDS' ].agg( [ fastest_argmax ] )
100 loops, best of 3: 8.8 ms per loop
%timeit grp2[ 'ODDS' ].agg( [ np.argmax ] )
100 loops, best of 3: 11.6 ms per loop
数据如下所示:
grp2[ 'ODDS' ].head()
Out[60]:
EVENT_ID SELECTION_ID
104601100 4367029 682508 3.05
682509 3.15
682510 3.25
682511 3.35
5319660 682512 2.04
682513 2.08
682514 2.10
682515 2.12
682516 2.14
5510310 682520 4.10
682521 4.40
682522 4.50
682523 4.80
682524 5.30
5559264 682526 5.00
682527 5.30
682528 5.40
682529 5.50
682530 5.60
5585869 682533 1.96
682534 1.97
682535 1.98
682536 2.02
682537 2.04
6064546 682540 3.00
682541 2.74
682542 2.76
682543 2.96
682544 3.05
104601200 4916112 682548 2.64
682549 2.68
682550 2.70
682551 2.72
682552 2.74
5315859 682557 2.90
682558 2.92
682559 3.05
682560 3.10
682561 3.15
5356995 682564 2.42
682565 2.44
682566 2.48
682567 2.50
682568 2.52
5465225 682573 1.85
682574 1.89
682575 1.91
682576 1.93
682577 1.94
5773661 682588 5.00
682589 4.40
682590 4.90
682591 5.10
6013187 682592 5.00
682593 4.20
682594 4.30
682595 4.40
682596 4.60
104606300 2489827 683438 4.00
683439 3.90
683440 3.95
683441 4.30
683442 4.40
3602724 683446 2.16
683447 2.32
Name: ODDS, Length: 65, dtype: float64
【问题讨论】:
-
我建议查看 numpy 源代码,了解他们是如何做到的。这是一个链接:github.com/numpy/numpy/blob/… 尝试模仿他们的方法。
-
“效率低下”甚至没有开始描述您所谓的“fastest_argmax”。
-
在我的笔记本电脑
%timeit np.argmax( x )和x.shape == 10上只花了 1 我们,你的 numpy 版本是什么? -
ivan - 你对更高效的版本有什么建议吗?