python中的预条件共轭梯度与线性化器

2024-05-19 12:03:47 发布

您现在位置:Python中文网/ 问答频道 /正文

[作业]我要用预处理的共轭梯度法求解线性方程组Ax=b,我使用scipy.sparse.linalg先决条件。A是稀疏对称162×162矩阵。因为spilu给出了A的逆的近似值,比如M近似A,所以spilu(A)给出了M^-1,这是预处理条件。我发现我们可以在python共轭梯度函数中直接给出预处理条件,但是我下面的代码不起作用。在

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' 

另外,这个问题提示我需要使用linearerator接口,我不明白linearerator到底在做什么,为什么我们需要它。在

任何建议都将不胜感激! 提前谢谢!在


Tags: innonelibpackagessiteanacondascipycg
1条回答
网友
1楼 · 发布于 2024-05-19 12:03:47

我觉得参数顺序不对

x3=scipy.sparse.linalg.cg(A,b,M2)

在错误消息中:

^{pr2}$

M2代替了x0——解的初始猜测,但不是预处理条件。 在我的主机中,使用正确的顺序,class-linearerator运行良好。在

正确的版本

x3=scipy.sparse.linalg.cg(A,b,M=M2)

请尽可能多地使用“关键词”参数。

相关问题 更多 >

    热门问题