我已经使用Python和numpy几个星期了。直到今天我才意识到,有了
a = np.array([1,2,3])
b = np.array([[1,2], [3,4], [5,6]])
这两次计算得到相同的结果
a @ b
b.T @ a
尽管第一个在代数中没有意义(关于维度)。
所以我的问题是,在第一次计算中。dot的算法是如何工作的?或者numpy如何考虑1-D和N-D数组?
-
你可能没有问
np.dot
,它有不同的广播规则。 -
因为你的两个例子都涉及到
@
运算符,这是np.matmul
的语法糖,我将用np.matmul
来回答你的问题。
答案很简单,引用np.matmul
行为以下列方式取决于参数。
- 如果两个参数都是二维的,它们就像传统的矩阵一样相乘。
- 如果参数为N- d, N>2,它被视为驻留在最后两个索引中的矩阵堆栈,并相应地广播。
- I如果第一个参数是1- d,则通过在其维度前加上1将其提升为矩阵。在矩阵乘法之后,前面的1被移除。
- 如果第二个参数是1- d,则通过在其维度上添加1将其提升为矩阵。在矩阵乘法之后,附加的1被移除。
(重点是我的)。
a = np.array([1,2,3])
b = np.array([[1,2], [3,4], [5,6]])
对于1d和2d数组,dot
和matmul
做同样的事情,尽管文档措辞有点不同。
来自dot
的两例:
- If `a` is an N-D array and `b` is a 1-D array, it is a sum product over
the last axis of `a` and `b`.
- If `a` is an N-D array and `b` is an M-D array (where ``M>=2``), it is a
sum product over the last axis of `a` and the second-to-last axis of `b`::
你的a
是(3,),b
是(3,2):
In [263]: np.dot(b.T,a)
Out[263]: array([22, 28])
首先适用于(2,3)with (3,) ->在共享尺寸为3的维度上求和。
In [264]: np.dot(a,b)
Out[264]: array([22, 28])
第二个应用,a(3,)与a (3,2) ->最后一个(3,)和倒数第二个(3,2)的和积,同样是共享的3。
" A的最后一个,第二个到最后一个"是基本的矩阵乘法法则。In只需要在B
是1d时进行调整,并且没有倒数第二。
matmul
规则以添加维度和随后删除维度的方式表述。
- If the first argument is 1-D, it is promoted to a matrix by
prepending a 1 to its dimensions. After matrix multiplication
the prepended 1 is removed.
- If the second argument is 1-D, it is promoted to a matrix by
appending a 1 to its dimensions. After matrix multiplication
the appended 1 is removed.
(3,) with (3,2) =>(1,3) with (3,2) =>(1、2)=比;(2)
(2,3) with (3,) =>(2,3) with (3,1) =>(2, 1) =比;(2)