arrays - 为什么 scipy.sparse.linalg.LinearOperator 与 @、np.dot 和 np.matmul 有不同的行为
问题描述
我认为当谈到矩阵向量乘法时,运算符和@
函数都是 3 等价的。当矩阵为 a 时,它们给出相同的结果:np.dot
np.matmul
np.ndarray
import numpy as np
M = np.ones((2, 2))
a = np.arange(2)
M @ a
Out[11]: array([1., 1.])
np.dot(M, a)
Out[12]: array([1., 1.])
np.matmul(M, a)
Out[13]: array([1., 1.])
但是,它们与 scipy 的 LinearOperator 接口的行为不同
from scipy.sparse.linalg import aslinearoperator
lM = aslinearoperator(M)
lM @ a
Out[15]: array([1., 1.])
np.dot(lM, a)
Out[16]:
array([<2x2 _ScaledLinearOperator with dtype=float64>,
<2x2 _ScaledLinearOperator with dtype=float64>], dtype=object)
np.matmul(lM, a)
Traceback (most recent call last):
File "/home/luc/anaconda3/envs/ckm/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3437, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-17-287f28944706>", line 1, in <module>
np.matmul(lM, a)
ValueError: matmul: Input operand 0 does not have enough dimensions (has 0, gufunc core with signature (n?,k),(k,m?)->(n?,m?) requires 1)
我不明白它们的功能有什么区别。
解决方案
lM
不是numpy
数组,也不是它的子类。np.array(lM)
生成()
形状对象 dtype 数组。这就是为什么它在matmul
. lM@a
并将lM.dot(a)
任务委托给 lM 方法。其他人错误地转换为ndarray
第一。
推荐阅读
- python - 自定义表情符号和动画表情符号不起作用 [discord.py-rewrite]
- angular - 如何使用 .NET Core 2 配置 Angular 6 以允许来自任何主机的 CORS?
- json - 如何正确使用大型 JSON 文件
- database - Teradata - 使用 kerberos 的 JDBC 连接
- python - 如何使用python获取硒中特定类的下一个元素
- reactjs - GitHub Pages 不为项目提供服务,而是呈现根用户站点
- ruby - 从数组或对象(而不是从哈希)生成路由时,如何将“only_path:true”和“anchor:”等选项传递给“url_for”
- fullcalendar - fullcalendar 不能与主要的谷歌日历一起使用
- django - 使用 Django 动态创建新的 URL/页面
- javascript - 传单隐藏和显示图层