numpy - numpy.dot 函数如何工作?

标签 numpy

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

a.dot(b)b.dot(a) 会怎样?对于矩阵乘法,a.dot(b) 应该是非法的。

最佳答案

在此设置中,b.dot(a) 等同于 b.T.dot(a);事实上,bb.T 恰好具有相同的形状,所以尽管符号使它看起来像 b 是一个行向量,但它实际上不是。但是,我们可以将其重新定义为明确地表现为行向量,在这种情况下操作会按预期失败:

In [25]: b.dot(a)
Out[25]: array([23, 34])

In [26]: b.T.dot(a)
Out[26]: array([23, 34])

In [30]: b.shape
Out[30]: (2,)

In [31]: b.T.shape
Out[31]: (2,)

In [27]: c = b.reshape((1, 2))

In [28]: c.dot(a)
Out[28]: array([[23, 34]])

In [29]: a.dot(c)
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-29-5d91888f8066> in <module>()
----> 1 a.dot(c)

ValueError: shapes (2,2) and (1,2) not aligned: 2 (dim 1) != 1 (dim 0)

关于numpy - numpy.dot 函数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43451249/

相关文章:

python - 在 Python 中生成数字序列(曲线)

python - 在 pandas 数据框中重复行

python - 用 python 平均多个 netCDF4 文件

python - 将 PyTorch 的张量形状从 (C, B, H) 修改为 (B, C*H)

python - Numpy:在具体示例中摆脱循环

python - cv.cvtColor(img, cv.COLOR_BGR2GRAY) 不起作用

python - 重复列表中的每个元素任意次

python - 如何从图像中删除方括号?

python - Numpy 索引 : Set values of an array given by conditions in different array

python - 在 matplotlib 中调整/拉伸(stretch) 2d 直方图的大小与 x-y 相关的箱数?