乘以两个2D numpy数组的最快方法是什么?

时间:2018-11-04 13:26:36

标签: python arrays numpy multiplication

我们应该找到一种方法来将大小为(7403,33)的2D数组X与其转置相乘

我的意思是这个X * X.T

该解决方案应该比np.dot(X,X.T)快2.5倍。 我已经尽力想到了

%timeit np.dot(X,X.T)
%timeit np.matmul(X,X.T)
%timeit X@X.T
%timeit np.einsum("ij, jk -> ik",X,X.T)

而我实现的速度仅是numpy点的1.5倍

3.17 s ± 14.9 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2.03 s ± 6.82 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2.01 s ± 6.57 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2.02 s ± 6.67 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

1 个答案:

答案 0 :(得分:0)

好吧,我找到了scipy解决方案

%timeit np.dot(X,X.T)
%timeit np.matmul(X,X.T)
%timeit X@X.T
%timeit np.einsum("ij, jk -> ik",X,X.T)
%timeit linalg.blas.dgemm(alpha=1.0, a=X, b=X.T)

给出

3.07 s ± 16.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2.02 s ± 37.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
1.99 s ± 9.79 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
2 s ± 5.97 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
306 ms ± 6.85 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)