首页 > 解决方案 > 当第二个元素是向量/数组时,Numpy 矩阵乘法失败(“形状未对齐”)

问题描述

当我将 NxN numpy 矩阵乘以 N 个元素 numpy 数组时,我收到一条错误消息,指出形状未对齐。

from numpy import matrix,ones,eye
A = matrix(eye(3))
b = ones(3)
A*b

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

也改变向量并不能解决问题。

A*b.T

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

这是有道理的,因为 numpy 不区分列向量和行向量,因此 bT 等于 b。

如何执行简单的矩阵向量乘法?

标签: pythonnumpy

解决方案


(不要使用np.matrix,它已被弃用。而是只使用 2D 数组进行线性代数。)

使用矩阵乘法运算符@

In [177]: from numpy import ones,eye
     ...: A = eye(3)
     ...: b = ones(3)
     ...: A @ b
Out[177]: array([1., 1., 1.])

推荐阅读