之间有什么区别
import numpy as np
np.dot(a,b)
和
import numpy as np
np.inner(a,b)
我尝试的所有示例都返回了相同的结果。 Wikipedia两者都有同一篇文章吗?在 the description innear()
它说,它的行为在更高的维度上是不同的,但是我无法产生任何不同的输出。我应该使用哪一个?
最佳答案
For 2-D arrays it is equivalent to matrix multiplication, and for 1-D arrays to inner product of vectors (without complex conjugation). For N dimensions it is a sum product over the last axis of a and the second-to-last of b:
Ordinary inner product of vectors for 1-D arrays (without complex conjugation), in higher dimensions a sum product over the last axes.
(重点是我的。)
作为一个例子,请考虑使用2D数组的示例:
>>> a=np.array([[1,2],[3,4]])
>>> b=np.array([[11,12],[13,14]])
>>> np.dot(a,b)
array([[37, 40],
[85, 92]])
>>> np.inner(a,b)
array([[35, 41],
[81, 95]])
因此,您应该使用的是为您的应用程序提供正确行为的一种。
性能测试
(请注意,我仅测试1D情况,因为这是 .dot
和 .inner
给出相同结果的唯一情况。)
>>> import timeit
>>> setup = 'import numpy as np; a=np.random.random(1000); b = np.random.random(1000)'
>>> [timeit.timeit('np.dot(a,b)',setup,number=1000000) for _ in range(3)]
[2.6920320987701416, 2.676928997039795, 2.633111000061035]
>>> [timeit.timeit('np.inner(a,b)',setup,number=1000000) for _ in range(3)]
[2.588860034942627, 2.5845699310302734, 2.6556360721588135]
所以也许 .inner
更快,但是我的机器目前已经加载了,因此时间不一致,它们一定是非常准确的。
关于python - numpy dot()和内()之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11033573/