[作业]我将通过预条件共轭梯度法求解线性系统 Ax=b,并使用 scipy.sparse.linalg 中的 spilu 函数作为预条件器。 A是稀疏对称162*162矩阵。由于 spilu 给出了 A 的倒数的近似值,假设 M 近似于 A,因此 spilu(A) 给出了 M^-1,这是预条件子。我发现我们可以直接在python Conjugate Gradient函数中给出预处理器,但是我下面的代码不起作用。
M_inverse=scipy.sparse.linalg.spilu(A)
M2=scipy.sparse.linalg.LinearOperator((162,162),M_inverse.solve)
x3=scipy.sparse.linalg.cg(A,b,M2)
TypeError Traceback (most recent call last)
<ipython-input-84-86f8f91df8d2> in <module>()
----> 1 x3=scipy.sparse.linalg.cg(A,b,M2)
/Users/ruobinghan/anaconda/lib/python3.4/site-packages/scipy/sparse/linalg/isolve/iterative.py in cg(A, b, x0, tol, maxiter, xtype, M, callback)
/Users/ruobinghan/anaconda/lib/python3.4/site-packages/scipy/sparse/linalg/isolve/iterative.py in non_reentrant(func, *a, **kw)
83 try:
84 d['__entered'] = True
---> 85 return func(*a, **kw)
86 finally:
87 d['__entered'] = False
/Users/ruobinghan/anaconda/lib/python3.4/site-packages/scipy/sparse/linalg/isolve/iterative.py in cg(A, b, x0, tol, maxiter, xtype, M, callback)
219 @non_reentrant
220 def cg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None, callback=None):
--> 221 A,M,x,b,postprocess = make_system(A,M,x0,b,xtype)
222
223 n = len(b)
/Users/ruobinghan/anaconda/lib/python3.4/site-packages/scipy/sparse/linalg/isolve/utils.py in make_system(A, M, x0, b, xtype)
108 x = zeros(N, dtype=xtype)
109 else:
--> 110 x = array(x0, dtype=xtype)
111 if not (x.shape == (N,1) or x.shape == (N,)):
112 raise ValueError('A and x have incompatible dimensions')
TypeError: float() argument must be a string or a number, not 'LinearOperator'
此外,问题提示我需要使用 LinearOperator 接口(interface),我不明白 LinearOperator 到底在做什么以及为什么我们在这里需要它。
如有任何建议,我们将不胜感激! 提前致谢!
最佳答案
我认为参数顺序错误,
x3=scipy.sparse.linalg.cg(A,b,M2)
在错误消息中:
220 def cg(A, b, x0=None, tol=1e-5, maxiter=None, xtype=None, M=None,
callback=None):
--> 221 A,M,x,b,postprocess = make_system(A,M,x0,b,xtype)
M2 代替 x0 - 解的初始猜测,但不是预处理器。 在我的主机中,按照正确的顺序,class-LinearOperator 运行良好。
正确的版本
x3=scipy.sparse.linalg.cg(A,b,M=M2)
请尽可能多地使用“关键词”参数。
关于python - python 中的预条件共轭梯度和线性算子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32865832/