numpy dot() 和 inner() 的区别 [英] difference between numpy dot() and inner()
问题描述
有什么区别
将 numpy 导入为 npnp.dot(a,b)
和
将 numpy 导入为 npnp.inner(a,b)
我尝试的所有示例都返回了相同的结果.维基百科 两者都有相同的文章?!在描述中inner()
它说,它的行为在更高维度上是不同的,但我无法产生任何不同的输出.我应该使用哪一种?
对于二维数组,它相当于矩阵乘法,对于一维数组,它相当于向量的内积(没有复共轭).对于 N 维,它是 a 的最后一个轴和 b 的倒数第二个的和积:
numpy.inner
::><块引用>
一维数组的向量的普通内积(没有复杂的共轭),在更高维度上是最后一个轴上的和积.
(强调我的.)
以二维数组为例:
<预><代码>>>>a=np.array([[1,2],[3,4]])>>>b=np.array([[11,12],[13,14]])>>>np.dot(a,b)数组([[37, 40],[85, 92]])>>>np.inner(a,b)数组([[35, 41],[81, 95]])因此,您应该使用能够为您的应用程序提供正确行为的那个.
<小时>性能测试
(请注意,我仅测试一维情况,因为这是 .dot
和 .inner
给出相同结果的唯一情况.)
所以也许 .inner
更快,但我的机器目前负载相当大,所以时间不一致,也不一定非常准确.
What is the difference between
import numpy as np
np.dot(a,b)
and
import numpy as np
np.inner(a,b)
all examples I tried returned the same result. Wikipedia has the same article for both?! In the description of inner()
it says, that its behavior is different in higher dimensions, but I couldn't produce any different output. Which one should I use?
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.
(Emphasis mine.)
As an example, consider this example with 2D arrays:
>>> 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]])
Thus, the one you should use is the one that gives the correct behaviour for your application.
Performance testing
(Note that I am testing only the 1D case, since that is the only situation where .dot
and .inner
give the same result.)
>>> 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]
So maybe .inner
is faster, but my machine is fairly loaded at the moment, so the timings are not consistent nor are they necessarily very accurate.
这篇关于numpy dot() 和 inner() 的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!