【发布时间】:2019-02-03 08:38:57
【问题描述】:
根据question 和numpy 的答案,与a.dot(b) 相比,二维数组的矩阵乘法最好通过a @ b 或numpy.matmul(a,b) 完成。
如果 a 和 b 都是二维数组,则为矩阵乘法,但使用 首选 matmul 或 a @ b。
我做了以下基准测试并发现了相反的结果。
问题:我的基准测试有问题吗?如果不是,为什么 Numpy 比 a@b 或 numpy.matmul(a,b) 快时不推荐 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]])
【问题讨论】:
-
因为这里它已经“假定”它是一个矩阵乘法?此外,最好运行 batch 个测试(不仅仅是 100 个)。
-
@WillemVanOnsem 如果将其增加到 number=1000,或者运行脚本几次,您将观察到类似的发现。
-
例如,通过运行这些测试,矩阵乘法算法被缓存(在程序缓存中)可能,从而促进第二次调用。
-
matmul和@没有显着差异。dot和matmul甚至不做同样的事情。
标签: python arrays performance numpy matrix