首页 > 解决方案 > 为什么 scipy.sparse.linalg.LinearOperator 与 @、np.dot 和 np.matmul 有不同的行为

问题描述

我认为当谈到矩阵向量乘法时,运算符和@函数都是 3 等价的。当矩阵为 a 时,它们给出相同的结果:np.dotnp.matmulnp.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)

我不明白它们的功能有什么区别。

标签: arraysnumpyscipy

解决方案


lM不是numpy数组,也不是它的子类。np.array(lM)生成()形状对象 dtype 数组。这就是为什么它在matmul. lM@a并将lM.dot(a)任务委托给 lM 方法。其他人错误地转换为ndarray第一。


推荐阅读