【发布时间】:2016-03-24 23:24:08
【问题描述】:
[作业] 我将通过预条件共轭梯度法求解线性系统 Ax=b,并使用 scipy.sparse.linalg 中的 spilu 函数作为预条件子。 A 是一个稀疏对称的 162*162 矩阵。由于 spilu 给出了 A 的逆的近似值,假设 M 近似于 A,因此 spilu(A) 给出了 M^-1,它是预条件子。我发现我们可以在python Conjugate Gradient函数中直接给preconditioner,但是我下面的代码不行。
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 接口,我不明白 LinearOperator 到底在做什么以及为什么我们需要它。
任何建议将不胜感激! 提前致谢!
【问题讨论】:
-
强烈建议将代码和错误粘贴到格式化文本中,而不是截图。
-
@machineyearning,谢谢,我用的是LinearOperator,现在出现了新的错误,页面不是告诉我uss cg(A,b,M2)吗?为什么现在 LinearOperator 成了问题?docs.scipy.org/doc/scipy/reference/generated/…
-
在交互式解释器中测试您的代码并找出它的确切位置,以便您提供Minimal, Complete, and Verifiable example。尝试使用非常简单的值的看似有问题的函数,这样您就可以确保这些函数按您期望的那样工作。如果您提出的简单示例似乎仍然不起作用,请使用您的简单示例代码发布一个新问题(您应该能够将其缩小到 10 行或更少)以及您收到的确切错误消息,这将有一个非常短的堆栈跟踪。
标签: python scipy linear-algebra preconditions