我试图获取 numpy 数组矩阵每行的最大值。我想有效地实现它,我想出了以下两个习惯用法来实现这一点。我的问题是,以下两种方式有性能差异吗?
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
#array([[1, 2, 3],
# [4, 5, 6],
# [7, 8, 9]])
np.max(x,axis = 1)
#array([3, 6, 9])
x.max(axis = 1)
#array([3, 6, 9])
最佳答案
我在笔记本上测试了它,看来你的第二种方法稍微快一些:
import numpy as np
x = np.array([[1,2,3],[4,5,6],[7,8,9]])
第一种方法:
%%timeit
np.max(x,axis = 1)
The slowest run took 11.75 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 4.71 µs per loop
第二种方法:
%%timeit
x.max(axis = 1)
The slowest run took 12.81 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 3.71 µs per loop
据推测,这是因为对于第一个模块,您将调用 numpy 模块,而对于第二个模块,它已经在对象中。
但是,我建议不要尝试优化这些小事情,首先看看您是否已经完成了其余部分(您是否使用了像 Numba 这样的编译器,您是否使用了分析器来查看代码的哪一部分正在减慢您的速度)向下等)
关于python - numpy 数组的 np.max(x ,axis = 1) 和 x.max(axis = 1) 之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41785434/