默认情况下,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和函数,则结果是不同的。
%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和函数,沿着列计算它会更快。
因此,我的观点是为什么沿轴=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和函数时,沿列(轴= 0)计算速度更快。
你怎么解释这个?
谢谢
发布于 2018-01-29 01:55:32
你不能计算同样的东西。
前两个命令只计算整个数组中的一行/列。
a[0, :].sum().shape # sums just the first row only
()第二个命令,将2D数组的整个内容之和,但沿着某个轴。这样,您就不会得到一个结果(如前两个命令中的结果),而是一个一维和数组。
a.sum(axis=0).shape # computes the row-wise sum for each column
(5000,)总之,这两组命令所做的事情是不同的。
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])https://stackoverflow.com/questions/48493343
复制相似问题