2011-10-27 84 views

回答

63

初始化稀疏矩陣時,您可以傳遞一個numpy數組或矩陣作爲參數。例如,對於CSR矩陣,您可以執行以下操作。

>>> import numpy as np 
>>> from scipy import sparse 
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]]) 
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]]) 

>>> A 
array([[1, 2, 0], 
     [0, 0, 3], 
     [1, 0, 4]]) 

>>> sA = sparse.csr_matrix(A) # Here's the initialization of the sparse matrix. 
>>> sB = sparse.csr_matrix(B) 

>>> sA 
<3x3 sparse matrix of type '<type 'numpy.int32'>' 
     with 5 stored elements in Compressed Sparse Row format> 

>>> print sA 
    (0, 0)  1 
    (0, 1)  2 
    (1, 2)  3 
    (2, 0)  1 
    (2, 2)  4 
16

scipy中有幾個稀疏矩陣類。

bsr_matrix(ARG1 [,形狀,D型細胞,複製,塊大小])塊稀疏行矩陣
coo_matrix(ARG1 [,形狀,D型細胞,複製])的稀疏矩陣中的座標的格式。
csc_matrix(ARG1 [,形狀,D型細胞,複製])壓縮稀疏列矩陣
csr_matrix(ARG1 [,形狀,D型細胞,複製])壓縮稀疏行矩陣
dia_matrix(ARG1 [,形狀,D型細胞,複製])具有DIAgonal存儲的稀疏矩陣
dok_matrix(arg1 [,shape,dtype,copy])Dictionary基於密鑰的稀疏矩陣。
lil_matrix(ARG1 [,形狀,D型細胞,複製])基於行鏈表稀疏矩陣

它們中的任何可以執行轉換。

import numpy as np 
from scipy import sparse 
a=np.array([[1,0,1],[0,0,1]]) 
b=sparse.csr_matrix(a) 
print(b) 

(0, 0) 1 
(0, 2) 1 
(1, 2) 1 

參見http://docs.scipy.org/doc/scipy/reference/sparse.html#usage-information

3

至於反函數,函數是inv(A),但我不會推薦使用它,因爲對於巨大的矩陣來說,它在計算上非常昂貴和不穩定。相反,你應該使用逆的近似值,或者如果你想解決Ax = b,你並不需要A -1