将稀疏矩阵分成两个

时间:2012-08-31 10:49:01

标签: python numpy scipy sparse-matrix

问题:如何根据列表中的值将1个稀疏矩阵拆分为2?

也就是说,我有一个稀疏矩阵X

>>print type(X)
<class 'scipy.sparse.csr.csr_matrix'>

我在脑海中将其视为列表列表,如下所示:

>>print X.todense()
[[1,3,4]
 [3,2,2]
 [4,8,1]]

我有一个列表y,如下所示:

y = [-1, 
      3, 
     -4]

如何将X分成两个稀疏矩阵,具体取决于y中的相应值是正还是负?例如,我该如何获得:

>>print X_pos.todense()
 [[3,2,2]] 
>>print X_neg.todense()
 [[1,3,4]
  [4,8,1]]

结果(X_posX_neg)也应该是稀疏矩阵,因为它只是将稀疏矩阵拆分为开头。

谢谢!

1 个答案:

答案 0 :(得分:8)

使用np.where为正和负y值生成两个索引数组,然后使用它们索引到稀疏矩阵。

>>> X = csr_matrix([[1,3,4], [3,2,2], [4,8,1]])
>>> y = np.array([-1, 3, -4])
>>> y_pos = np.where(y > 0)[0]
>>> y_neg = np.where(y < 0)[0]
>>> X_pos = X[y_pos]
>>> X_neg = X[y_neg]

现在您需要包含所需元素的CSR矩阵:

>>> X_pos
<1x3 sparse matrix of type '<type 'numpy.int64'>'
    with 3 stored elements in Compressed Sparse Row format>
>>> X_neg
<2x3 sparse matrix of type '<type 'numpy.int64'>'
    with 6 stored elements in Compressed Sparse Row format>
>>> X_pos.A
array([[3, 2, 2]])
>>> X_neg.A
array([[1, 3, 4],
       [4, 8, 1]])