Slicing a scipy sparse matrix using a boolean mask

房东的猫 提交于 2019-12-10 16:12:34

问题


I have encountered a difference in how slicing a scipy sparse matrix works in 0.10.0 and 0.10.1. Consider the following piece of code:

from numpy import array, ravel
from scipy.sparse import csr_matrix

mat = csr_matrix(array([[1, 0, 0], [0,1,0], [1,0,0]]))
desired_cols = ravel(mat.sum(0)) > 0

print mat[:, desired_cols].A

In scipy 0.10.0, I get what I expect to get:

[[1 0]
 [0 1]
 [1 0]]

In 0.10.1 and 0.12.0, I get

[[0 0 1]
 [1 1 0]
 [0 0 1]]

I am not sure if this is a bug or I am doing something wrong. I get the same results using coo_matrix and csc_matrix.

I am trying to remove all rows that sum to 0 from the matrix. I understand that csr_matrix does not support efficient column slicing and I should not being this.


回答1:


What is desired_cols in these cases. In recent scipy (0.13.0) the results match your first one (0.10.0). You may have to dig into the github source for scipy if you want to track down changes this far back in the versions.




回答2:


Use np.flatnonzero(desired_cols) instead of desired_cols and scipy.sparse will support it. Full matrix API support is unavailable in scipy.sparse and features are gradually being introduced.



来源:https://stackoverflow.com/questions/20080332/slicing-a-scipy-sparse-matrix-using-a-boolean-mask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!