python - 当第二个元素是向量/数组时,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。
如何执行简单的矩阵向量乘法?
解决方案
(不要使用np.matrix
,它已被弃用。而是只使用 2D 数组进行线性代数。)
使用矩阵乘法运算符@
:
In [177]: from numpy import ones,eye
...: A = eye(3)
...: b = ones(3)
...: A @ b
Out[177]: array([1., 1., 1.])
推荐阅读
- sql - Laravel - 计算查询,里面有连接
- c# - 如何忽略我认为基于属性重复的额外结果?
- spring - 我如何在@BeforeAll(JUnit5)之前执行@Sql
- reactjs - 状态更新时更改呈现的 HTML React
- fish - 鱼壳中的间接变量引用
- android - 将 Firestore 与 Fragment 和 ViewModel 一起使用时,Android 应用程序崩溃
- node.js - npm install 在 grpc@1.20.0 安装脚本失败时失败
- c# - C# 使用数据行中的值计算金额
- python - 如何在模板中显示所有用户的个人资料图片
- javascript - 在 vue 中下载总是返回相同的 html 页面