为什么a.dot(b)比a @ b快,尽管Numpy建议a @ b [英] Why is a.dot(b) faster than a@b although Numpy recommends a@b
问题描述
根据此问题的答案并根据 numpy ,与a.dot(b)
相比,最好通过a @ b
或numpy.matmul(a,b)
完成二维数组的矩阵乘法.
According to the answers from this question and also according to numpy, matrix multiplication of 2-D arrays is best done via a @ b
, or numpy.matmul(a,b)
as compared to a.dot(b)
.
如果a和b均为二维数组,则为矩阵乘法,但使用 最好使用matmul或a @ b.
If both a and b are 2-D arrays, it is matrix multiplication, but using matmul or a @ b is preferred.
我进行了以下基准测试,发现相反的结果.
I did the following benchmark and found contrary results.
问题:我的基准测试有问题吗?如果不是,为什么当Numpy比a@b
或numpy.matmul(a,b)
快时,为什么不推荐a.dot(b)
?
Questions: Is there an issue with my benchmark? If not, why does Numpy not recommend a.dot(b)
when it is faster than a@b
or numpy.matmul(a,b)
?
基准使用python 3.5 numpy 1.15.0.
Benchmark used python 3.5 numpy 1.15.0.
$ pip3 list | grep numpy
numpy 1.15.0
$ python3 --version
Python 3.5.2
基准代码:
import timeit
setup = '''
import numpy as np
a = np.arange(16).reshape(4,4)
b = np.arange(16).reshape(4,4)
'''
test = '''
for i in range(1000):
a @ b
'''
test1 = '''
for i in range(1000):
np.matmul(a,b)
'''
test2 = '''
for i in range(1000):
a.dot(b)
'''
print( timeit.timeit(test, setup, number=100) )
print( timeit.timeit(test1, setup, number=100) )
print( timeit.timeit(test2, setup, number=100) )
结果:
test : 0.11132473500038031
test1 : 0.10812476599676302
test2 : 0.06115105600474635
添加结果:
>>> a = np.arange(16).reshape(4,4)
>>> b = np.arange(16).reshape(4,4)
>>> a@b
array([[ 56, 62, 68, 74],
[152, 174, 196, 218],
[248, 286, 324, 362],
[344, 398, 452, 506]])
>>> np.matmul(a,b)
array([[ 56, 62, 68, 74],
[152, 174, 196, 218],
[248, 286, 324, 362],
[344, 398, 452, 506]])
>>> a.dot(b)
array([[ 56, 62, 68, 74],
[152, 174, 196, 218],
[248, 286, 324, 362],
[344, 398, 452, 506]])
推荐答案
您的前提不正确.您应该使用更大的矩阵来衡量性能,以避免函数调用使无关紧要的计算相形见
Your premise is incorrect. You should use larger matrices to measure performance to avoid function calls dwarfing insignificant calculations.
您会发现使用Python 3.60/NumPy 1.11.3,如
Using Python 3.60 / NumPy 1.11.3 you will find, as explained here, that @
calls np.matmul
and both outperform np.dot
.
import numpy as np
n = 500
a = np.arange(n**2).reshape(n, n)
b = np.arange(n**2).reshape(n, n)
%timeit a.dot(b) # 134 ms per loop
%timeit a @ b # 71 ms per loop
%timeit np.matmul(a,b) # 70.6 ms per loop
还要注意,如文档中所述,np.dot
在功能上与@
/np.matmul
不同.特别是,它们在处理尺寸大于2的矩阵方面有所不同.
Also note, as explained in the docs, np.dot
is functionally different to @
/ np.matmul
. In particular, they differ in treatment of matrices with dimensions greater than 2.
这篇关于为什么a.dot(b)比a @ b快,尽管Numpy建议a @ b的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!