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

标签 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])

最佳答案

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

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/

相关文章:

python - 使用 Python 从 CouchDB-Futon 编写的 View 中获取数据

python - Django 测试返回登录重定向 302,即使用户已登录

python - 我可以将自己的 Python 类与 numpy 或其他一些矩阵库一起使用吗?

python - 在非英语 Ubuntu 上编译 Cython .pyx 文件(unicode 错误)

r - 如何针对一列为数据矩阵的每一列绘制多条线?

python - 如何从这个单词矩阵创建句子排列?

python - 以动态 pythonic 方式查找偏序集中的最小元素

python - 内省(introspection)类属性以查看它是否被修饰,而不访问属性值

python - 如何有效地将点云数据的大型 numpy 数组转换为下采样的二维数组?

r - 如何将矩阵转换为 R 中的不同矩阵?