python - numpy 矩阵乘法 n x m * m x p = n x p

标签 python numpy matrix linear-algebra matrix-multiplication

我正在尝试将两个 numpy 数组作为矩阵相乘。我希望如果 An x m 矩阵并且 Bm x p 矩阵,则 A* B 产生一个 n x p 矩阵。

此代码创建一个 5x3 矩阵和一个 3x1 矩阵,由 shape 属性验证。我小心翼翼地创建了两个二维数组。最后一行执行乘法,我期望一个 5x1 矩阵。

A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
print(A)
print(A.shape)
B = np.array([[2],[3],[4]])
print(B)
print(B.shape)
print(A*B)

结果

[[1 1 1]
 [2 2 2]
 [3 3 3]
 [4 4 4]
 [5 5 5]]
(5, 3)
[[2]
 [3]
 [4]]
(3, 1)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-38-653ff6c66fb7> in <module>()
      5 print(B)
      6 print(B.shape)
----> 7 print(A*B)

ValueError: operands could not be broadcast together with shapes (5,3) (3,1) 

即使异常消息也表明内部尺寸(3 和 3)匹配。为什么乘法会抛出异常?我应该如何生成 5x1 矩阵?

我使用的是 Python 3.6.2 和 Jupyter Notebook 服务器 5.2.2。

最佳答案

* 运算符提供元素乘法,这要求数组具有相同的形状,或者是 'broadcastable'

对于点积,请使用 A.dot(B),或者在许多情况下您可以使用 A @ B(在 Python 3.5 中;read how it differs from dot

>>> import numpy as np
>>> A = np.array([[1,1,1],[2,2,2],[3,3,3],[4,4,4],[5,5,5]])
>>> B = np.array([[2],[3],[4]])
>>> A @ B
array([[ 9],
       [18],
       [27],
       [36],
       [45]])

对于更多选项,特别是处理高维数组,还有 np.matmul .

关于python - numpy 矩阵乘法 n x m * m x p = n x p,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633812/

相关文章:

java - 如何在计算大量矩阵时使用内存

algorithm - 查找二维矩阵中的路径和内部字段

python - 将带有字母的电话号码翻译为python中的所有数字。我究竟做错了什么?

python - DRF - PrimaryKeyRelatedField 中的过滤查询集

python - 如何在 Python 中添加二维数组的相邻元素而不必使用嵌套循环?

python - 矩阵求逆 (3,3) python - 硬编码与 numpy.linalg.inv

python - Matlab到Python代码转换: Matrices are not aligned

python - 如何指定嵌套列表的每个子列表中特定元素的索引?

python - 迁移到 numpy api 1.7

matlab - 如何在 MATLAB 中对矩阵的每一项应用条件并获得相同大小的输入矩阵并计算 1 的数量?