2013-11-21 83 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