问题描述
我认为当涉及到矩阵向量乘法时,@
运算符以及函数 np.dot
和 np.matmul
都是 3 等价的。当矩阵是 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
。