2015-09-30 61 views
2

[作業]我要通過預處理共軛梯度法解決線性系統Ax = b,並且我使用scipy.sparse.linalg中的spilu函數作爲預處理器。 A是一個稀疏對稱的162 * 162矩陣。由於spilu給出A的倒數的近似值,所以M近似於A,所以spilu(A)給出M^-1,它是預處理器。我發現我們可以直接在python Conjugate Gradient函數中給出preconditioner,但是我下面的代碼不起作用。預處理共軛梯度和LinearOperator在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' 

而且,問題提示我將需要使用LinearOperator接口,我不明白究竟是什麼LinearOperator做,爲什麼我們這裏需要它。

任何建議,將不勝感激! 在此先感謝!

+1

強烈建議您將代碼和錯誤粘貼到格式化文本中,而不是截取屏幕截圖。 –

+0

@ machineyearning,謝謝,我使用LinearOperator,現在又出現了一個新的錯誤,是不是頁面告訴我uss cg(A,b,M2)?爲什麼現在LinearOperator成爲一個問題?http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.cg.html#scipy.sparse.linalg.cg – Bob

+0

在交互式解釋器中測試你的代碼並找出它正在破裂的位置,以便您可以提供[最小,完整和可驗證示例](https://stackoverflow.com/help/mcve)。嘗試使用非常簡單的值來顯示正在破解的函數,以確保函數按照您的預期工作。如果您提出的簡單示例仍然不起作用,請使用簡單的示例代碼發佈一個新問題(您應該能夠將其縮小到10行或更少)以及您得到的確切錯誤消息,這將有一個非常短的堆棧跟蹤。 –

回答

1

我覺得參數順序錯誤

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的地方 - 該解決方案的初始猜測,但不預處理器。 在我的主機中,訂單正確,類別爲LinearOperator運行良好。

正確版本

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

請使用 「關鍵字」 論據儘可能多地。