2013-11-21 79 views
4

我搜索了網絡找到一個Scipy稀疏矩陣的指南,我失敗了。我會很高興,如果有人會分享任何來源,但現在要問:元組的稀疏數組

我有一個元組數組。我想將元組數組更改爲一個稀疏矩陣,其中元組出現在主對角線和對角線旁邊,如以下示例所示。做這件事的花哨(有效)方式是什麼?

import numpy as np 
A=np.asarray([[1,2],[3,4],[5,6],[7,8]]) 
B=np.zeros((A.shape[0],A.shape[0]+1)) 
for i in range(A.shape[0]): 
    B[i,i]=A[i,0] 
    B[i,i+1]=A[i,1] 
print B 

輸出中:

[[ 1. 2. 0. 0. 0.] 
[ 0. 3. 4. 0. 0.] 
[ 0. 0. 5. 6. 0.] 
[ 0. 0. 0. 7. 8.]] 
+0

也許這是我猜的最愚蠢的方式。 – Cupitor

+0

scipy稀疏軟件包的主要信息來源是其參考頁面:http://docs.scipy.org/doc/scipy/reference/sparse.html。但是,這不是一個精緻的用戶或初學者指南。請記住,這個軟件包仍在開發中。 Matlab的稀疏矩陣可能有更好的文檔。 – hpaulj

回答

4

你可以建立那些真正˚F ast作爲CSR矩陣:

>>> A = np.asarray([[1,2],[3,4],[5,6],[7,8]]) 
>>> rows = len(A) 
>>> cols = rows + 1 
>>> data = A.flatten() # we want a copy 
>>> indptr = np.arange(0, len(data)+1, 2) # 2 non-zero entries per row 
>>> indices = np.repeat(np.arange(cols), [1] + [2] * (cols-2) + [1]) 
>>> import scipy.sparse as sps 
>>> a_sps = sps.csr_matrix((data, indices, indptr), shape=(rows, cols)) 
>>> a_sps.A 
array([[1, 2, 0, 0, 0], 
     [0, 3, 4, 0, 0], 
     [0, 0, 5, 6, 0], 
     [0, 0, 0, 7, 8]]) 
+0

非常感謝。如果你知道的話,你能不能給我這個稀疏矩陣的來源。 – Cupitor

+2

[關於稀疏矩陣的維基百科頁面](http://en.wikipedia.org/wiki/Sparse_matrix)對於這三個數組('data','indices'和'indptr')來說是一個很好的起點。通過了解它們,通常可以非常快速地完成(至少當前)超出sipy.sparse API的範圍。 – Jaime

4

嘗試diags from scipy

import numpy as np 
import scipy.sparse 

A = np.asarray([[1,2],[3,4],[5,6],[7,8]]) 
B = scipy.sparse.diags([A[:,0], A[:,1]], [0, 1], [4, 5]) 

當我print B.todense(),它給了我

[[ 1. 2. 0. 0. 0.] 
[ 0. 3. 4. 0. 0.] 
[ 0. 0. 5. 6. 0.] 
[ 0. 0. 0. 7. 8.]] 
+0

更簡潔:'sparse.diags(A.T,[0,1],(4,5))。A' – hpaulj