(m,)向量与(m,n)矩阵相乘时的点行为

2024-06-17 12:21:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我已经用Python和numpy工作了几个星期。直到今天我才意识到这一点

a = np.array([1,2,3])
b = np.array([[1,2], [3,4], [5,6]])

这两个计算给出了相同的结果

a @ b
b.T @ a

尽管第一个在代数中没有意义(关于维度)

所以我的问题是,.dot的算法在第一次计算中是如何工作的?或者NoMPy如何考虑1-D和N-D数组?


Tags: numpy算法np数组arraydot意义代数
2条回答
a = np.array([1,2,3])
b = np.array([[1,2], [3,4], [5,6]])

对于1d和2d数组,dotmatmul做同样的事情,尽管文档的措辞有点不同

来自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)和(3,)->;共享大小3维上的和积

In [264]: np.dot(a,b)
Out[264]: array([22, 28])

第二种情况适用,a(3,)和a(3,2)——>;最后一个(3,)和第二个(3,2)和最后一个(3,2)的和积,同样是共享的3

“A的最后一个,B的第二个到最后一个”是基本的矩阵乘法规则。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,)与(3,2)=>;(1,3)与(3,2)=>;(1,2)=>;(2,)

(2,3)与(3,)=>;(2,3)与(3,1)=>;(2,1)=>;(2,)

  1. 你可能不是在问np.dot,它有不同的广播规则

  2. 因为您的两个示例都涉及@操作符,即np.matmul的语法糖,所以我将用np.matmul来回答您的问题

答案很简单,只要引用the documentation of ^{}

The behavior depends on the arguments in the following way.

  • If both arguments are 2-D they are multiplied like conventional matrices.
  • If either argument is N-D, N > 2, it is treated as a stack of matrices residing in the last two indexes and broadcast accordingly.
  • 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.

(重点是我的)

相关问题 更多 >