How to work elementally on a matrix like scipy.sparse.csr_matrix?

In numpy, if you want to calculate the sine of each matrix entry (elementise) then

a = numpy.arange(0,27,3).reshape(3,3) numpy.sin(a) 

will do its job! If you want the authorities to say 2 of each entry

 a**2 

will do it.

But if you have rare matrix things, it seems more difficult to you. At least I did not understand the way to do this, except repeat each lil_matrix record and work with it.

I found this question on SO and tried to adapt this answer , but I was not successful.

The goal is to calculate scipy.sparse matrices of CSR format using the squareroot element (or power up to 1/2).

What would you suggest?

+4
source share
1 answer

The following trick works for any operation that maps zero to zero and only for these operations, since it applies only to nonzero elements. Ie, 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) >>> XA array([[ 0., 1., 2., 3., 4.], [ 5., 6., 7., 8., 9.]]) 

Values โ€‹โ€‹of nonzero X.data elements:

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

which you can update on the spot:

 >>> X.data[:] = np.sqrt(X.data) >>> XA 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 the sparse matrix to get a new copy with the square roots of the elements in X

+10
source

Source: https://habr.com/ru/post/1391596/


All Articles