python a and b_python-尽管Numpy建议a.b,为什么a.dot(b)比a @ b更...
根據(jù)question的答案,也根據(jù)numpy的答案,與a.dot(b)相比,二維數(shù)組的矩陣乘法最好通過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.
我做了以下基準(zhǔn)測試,發(fā)現(xiàn)相反的結(jié)果.
問題:我的基準(zhǔn)測試有問題嗎?如果不是,當(dāng)Numpy比a @ b或numpy.matmul(a,b)快時,為什么Numpy不推薦a.dot(b)?
基準(zhǔn)使用python 3.5 numpy 1.15.0.
$pip3 list | grep numpy
numpy 1.15.0
$python3 --version
Python 3.5.2
基準(zhǔn)代碼:
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) )
結(jié)果:
test : 0.11132473500038031
test1 : 0.10812476599676302
test2 : 0.06115105600474635
附加結(jié)果:
>>> 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]])
總結(jié)
以上是生活随笔為你收集整理的python a and b_python-尽管Numpy建议a.b,为什么a.dot(b)比a @ b更...的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++两个数组对比去掉重复的元素_30
- 下一篇: python 如何定义字典_python