根据question的答案,也根据numpy的答案,与a.dot(b)相比,二维数组的矩阵乘法最好通过a b或numpy.matmul(a,b)完成.
If both a and b are 2-D arrays, it is matrix multiplication, but using
matmul or a @ b is preferred.
我做了以下基准测试,发现相反的结果.
问题:我的基准测试有问题吗?如果不是,当Numpy比a @ b或numpy.matmul(a,b)快时,为什么Numpy不推荐a.dot(b)?
基准使用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]])