将稀疏矩阵分成两个

Zac*_*ach 8 python numpy scipy sparse-matrix

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

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

>>print type(X)
<class 'scipy.sparse.csr.csr_matrix'>
Run Code Online (Sandbox Code Playgroud)

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

>>print X.todense()
[[1,3,4]
 [3,2,2]
 [4,8,1]]
Run Code Online (Sandbox Code Playgroud)

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

y = [-1, 
      3, 
     -4]
Run Code Online (Sandbox Code Playgroud)

我如何X分成两个稀疏矩阵,取决于相应的值y是正还是负?例如,我怎样才能得到:

>>print X_pos.todense()
 [[3,2,2]] 
>>print X_neg.todense()
 [[1,3,4]
  [4,8,1]]
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Fre*_*Foo 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]
Run Code Online (Sandbox Code Playgroud)

您现在需要包含所需元素的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]])
Run Code Online (Sandbox Code Playgroud)