稀疏矩阵操作

时间:2014-08-19 19:22:45

标签: python numpy

我有一个看起来像这样的原始矩阵:

(32, 69901)     1
(108, 69901)    1
(32, 69902)     1
(108, 69903)    1
(108, 69904)    1
(432, 69905)    1
(432, 69906)    1
(432, 69907)    1

我想将前X行分成一个矩阵,其余的分成另一个矩阵。我尝试使用一个简单的for循环来实现它:

mat1 = []
mat2 = []
for i,line in enumerate(original_matrix):
        if i < cutoff:
            mat1.append(line)
        else:
            mat2.append(line)

但这会产生一个如下所示的矩阵:

with 223 stored elements in Compressed Sparse Row format>, <1x103515 sparse matrix of type '<type 'numpy.int64'>'
with 253 stored elements in Compressed Sparse Row format>, <1x103515 sparse matrix of type '<type 'numpy.int64'>'
with 142 stored elements in Compressed Sparse Row format>, <1x103515 sparse matrix of type '<type 'numpy.int64'>'
with 222 stored elements in Compressed Sparse Row format>, <1x103515 sparse matrix of type '<type 'numpy.int64'>'

如何让它看起来像原作?

1 个答案:

答案 0 :(得分:3)

最简单的方法可能是更改您使用的稀疏矩阵类型。看起来您正在使用压缩的稀疏列矩阵(csc)。如果需要按行分解,请考虑使用压缩稀疏行矩阵(csr)(我认为doc和lil稀疏矩阵也可以工作,但我没有完全测试它们)。例如,让我们从csc矩阵开始。

In [1]: from scipy import sparse

In [2]: original_matrix = sparse.csc_matrix(([1,1,1,1,1,1,1,1], 
([32, 108, 32, 108, 108, 432, 432, 432], [69901, 69901, 69902, 
69903, 69904, 69905, 69906, 69907])), shape=[500,103515])

In [3]: print original_matrix
  (32, 69901)   1
  (108, 69901)  1
  (32, 69902)   1
  (108, 69903)  1
  (108, 69904)  1
  (432, 69905)  1
  (432, 69906)  1
  (432, 69907)  1

我们不能使用数组拼接按行拆分,但我们可以很容易地将csc矩阵转换为汽车矩阵。

In [4]: new_matrix = original_matrix.tocsr()
Out[4]:
<500x103515 sparse matrix of type '<type 'numpy.int64'>'
    with 8 stored elements in Compressed Sparse Row format>

In [5]: print new_matrix
  (32, 69901)   1
  (32, 69902)   1
  (108, 69901)  1
  (108, 69903)  1
  (108, 69904)  1
  (432, 69905)  1
  (432, 69906)  1
  (432, 69907)  1

如果您有car,doc或lil类型的稀疏矩阵,可以使用数组拼接将其拆分。

In [6]: cutoff = 100

In [7]: mat1 = original_matrix[:cutoff]

In [8]: mat2 = original_matrix[cutoff:]

会给你两件你想要的东西。请注意,截止值是实际矩阵的行,而不是调用print语句时看到的行。

In [9]: print mat1
  (32, 69901)   1
  (32, 69902)   1

In [10]: print mat2
  (108, 69901)  1
  (108, 69903)  1
  (108, 69904)  1
  (432, 69905)  1
  (432, 69906)  1
  (432, 69907)  1

如果您没有我假设的csc矩阵,那么还有内置的方法可以将其他类型的稀疏矩阵转换为csr。