How to operate elementwise on a matrix of type scipy.sparse.csr_matrix?

两盒软妹~` 提交于 2019-12-03 14:29:31

The following trick works for any operation which maps zero to zero, and only for those operations, because it only touches the non-zero elements. I.e., it will work for sin and sqrt but not for cos.

Let X be some CSR matrix...

>>> from scipy.sparse import csr_matrix
>>> X = csr_matrix(np.arange(10).reshape(2, 5), dtype=np.float)
>>> X.A
array([[ 0.,  1.,  2.,  3.,  4.],
       [ 5.,  6.,  7.,  8.,  9.]])

The non-zero elements' values are X.data:

>>> X.data
array([ 1.,  2.,  3.,  4.,  5.,  6.,  7.,  8.,  9.])

which you can update in-place:

>>> X.data[:] = np.sqrt(X.data)
>>> X.A
array([[ 0.        ,  1.        ,  1.41421356,  1.73205081,  2.        ],
       [ 2.23606798,  2.44948974,  2.64575131,  2.82842712,  3.        ]])

Update In recent versions of SciPy, you can do things like X.sqrt() where X is a sparse matrix to get a new copy with the square roots of elements in X.

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