问题:如何根据列表中的值将 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]
如何根据 y
中的对应值是正数还是负数,将 X
分成两个稀疏矩阵?例如,我怎样才能得到:
>>print X_pos.todense()
[[3,2,2]]
>>print X_neg.todense()
[[1,3,4]
[4,8,1]]
结果(X_pos
和 X_neg
)显然也应该是稀疏矩阵,因为它只是开始分割一个稀疏矩阵。
谢谢!
最佳答案
使用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]])
关于python - 将稀疏矩阵一分为二,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12213818/