2015-09-26 87 views
0

我有格式的数据(x_index,y_index,value),我试图用scipy(scipy.sparse.csr.csr_matrix)创建一个CSR矩阵。从x_index,y_index创建CSR矩阵,值为

例如,转换:

0 0 10 
0 1 5 
1 0 3 
1 1 4 

以下几点:

10 5 
3 4 

我在这里阅读文档:http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csr_matrix.html

但是我还是不太清楚其中的例子适用于我的用例。

+2

这里的想法:首先建立一个'coo'矩阵,然后通过'tocsr'转换。 – cel

回答

3

如果您可以将输入数据分离为一系列行索引,一系列列索引和相应的值索引序列,则可以使用csr_matrix文档字符串中显示的第四个选项来创建矩阵。

例如,假设您已将数据存储在单个数组中,其中前两列是索引,第三列保存值。例如。

In [213]: data 
Out[213]: 
array([[ 0, 0, 10], 
     [ 0, 1, 5], 
     [ 1, 0, 3], 
     [ 1, 1, 4]]) 

然后你就可以创建一个CSR矩阵如下:

In [214]: a = csr_matrix((data[:, 2], (data[:, 0], data[:, 1]))) 

In [215]: a 
Out[215]: 
<2x2 sparse matrix of type '<type 'numpy.int64'>' 
    with 4 stored elements in Compressed Sparse Row format> 

In [216]: a.A 
Out[216]: 
array([[10, 5], 
     [ 3, 4]]) 

根据您的资料,您可能需要显式地指定的形状。例如,我在这里使用相同的数据,但在一个3x3矩阵:

In [217]: b = csr_matrix((data[:, 2], (data[:, 0], data[:, 1])), shape=(3, 3)) 

In [218]: b 
Out[218]: 
<3x3 sparse matrix of type '<type 'numpy.int64'>' 
    with 4 stored elements in Compressed Sparse Row format> 

In [219]: b.A 
Out[219]: 
array([[10, 5, 0], 
     [ 3, 4, 0], 
     [ 0, 0, 0]])