numpy数组的np.max(x,axis = 1)和x.max(axis = 1)之间的差异

时间:2017-01-21 22:57:24

标签: python numpy matrix max

我试图获得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])

1 个答案:

答案 0 :(得分:1)

我在笔记本上测试了它,看起来你的第二种方法稍快一点:

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这样的编译器,你是否使用了一个分析器来查看代码的哪一部分正在减慢你的速度下来,等等。)