Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Numpy-Numpy轴性能_Python_Arrays_Numpy - Fatal编程技术网

Python Numpy-Numpy轴性能

Python Numpy-Numpy轴性能,python,arrays,numpy,Python,Arrays,Numpy,默认情况下,numpy是行主视图。 因此,我自然接受以下结果 a = np.random.rand(5000, 5000) %timeit a[0,:].sum() 3.57 µs ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each) %timeit a[:,0].sum() 38.8 µs ± 8.19 ns per loop (mean ± std. dev. of 7 runs, 10000 loops e

默认情况下,numpy是行主视图。 因此,我自然接受以下结果

a = np.random.rand(5000, 5000)

%timeit a[0,:].sum()
3.57 µs ± 13.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit a[:,0].sum()
38.8 µs ± 8.19 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
因为它是一个行主顺序,所以计算速度自然会加快[0,:]。 但是,如果使用numpy sum函数,结果是不同的

%timeit a.sum(axis=0)
16.9 ms ± 13.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit a.sum(axis=1)
29.5 ms ± 90.3 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
如果使用numpy sum函数,则沿列计算会更快

所以我的观点是为什么沿轴=0(沿列计算)的速度比沿轴=1(沿行计算)的速度快

比如说

a = np.array([[0, 1, 2],
[3, 4, 5],
[6, 7, 8]], order='C')
在行主顺序中,[1,2,3]和[4,5,6],[7,8,9]分别分配给相邻内存

因此,沿轴=1计算的速度应快于轴=0。 但是,使用numpy sum函数时,沿列(轴=0)计算速度更快

你怎么解释呢


谢谢

你不会计算同样的东西

前两个命令仅计算整个数组中的一行/列

a[0, :].sum().shape   # sums just the first row only
()
第二个命令沿某个轴对二维数组的全部内容求和。这样,您就不会得到一个结果(如前两个命令),而是得到一个一维和数组

a.sum(axis=0).shape   # computes the row-wise sum for each column
(5000,)
总之,这两组命令的作用不同



a[0,:]
仅对第一行求和
a.sum(axis=0)
沿行对整个内容求和。但是,如果使用numpy内置函数,结果是不同的。“实际上,您总是使用”
numpy
内置函数”@COLDSPEED完全正确:您正在计算不同的东西。a.sum(axis=0)是根据列计算的结果。沿行计算的“print(a[0,:].sum()、a[1,:].sum()、a[2,:].sum())”的结果是[3 12 21],而a.sum(axis=0)的结果是[9,12,15]@신대규 是的,如果您想要相同的输出,请使用轴=1,而不是轴0。另外,一个比另一个慢的原因是缓存未命中和缺少引用的局部性。@cᴏʟᴅsᴘᴇᴇᴅ 谢谢你的回复。我很困惑。我还在Linux系统上测试了它。a=np.rand.rand(50005000)%timeit a.sum(axis=0)100个循环,每个循环3:17毫秒的最佳值%timeit a.sum(axis=1)100个循环,每个循环3:15.5毫秒的最佳值这不是很大的区别,但它是有意义的。但是在窗口系统上timeit a.sum(轴=0)17 ms±122µs/回路(7次运行的平均值±标准偏差,每个100回路)%timeit a.sum(轴=1)29.7 ms±153µs/回路(7次运行的平均值±标准偏差,每个10回路)。它似乎受到操作系统或numpy版本的影响——同样值得注意的是——如果你做了
c=np.random.randn(50005000)
f=np.asfortranarray(c)
,你会看到0轴和1轴上的和有不可忽略的倒计时差。
a
array([[1, 6, 9, 1, 6],
       [5, 6, 9, 1, 3],
       [5, 0, 3, 5, 7],
       [2, 8, 3, 8, 6],
       [3, 4, 8, 5, 0]])

a[0, :]
array([1, 6, 9, 1, 6])

a[0, :].sum()
23
a.sum(axis=0)
array([16, 24, 32, 20, 22])