Question

I have a sparse matrix:

from scipy import sparse
a = sparse.diags([1,4,9],[-1,0,1],shape =(10,10),format ="csr")

I want to take the square root of each of the elements in the sparse matrix I look up on the internet and it says I can use numpy.sqrt() to implement this. But error occurs:

  b = numpy.sqrt(a)
  AttributeError: sqrt

How can I do it?

Was it helpful?

Solution

Caveat, this will create a resulting numpy ndarray instead of a sparse csr array.

from scipy import sparse
a = sparse.diags([1,4,9],[-1,0,1],shape =(10,10),format ="csr")

numpy.sqrt(a.data)

As far as I can tell most of the other ufunc operations (sin, cos, ... ) do have sparse ufuncs except for sqrt, don't know the reason why. See this issue: https://github.com/scipy/scipy/pull/208

OTHER TIPS

If you want to return a sparse matrix (which you almost certainly do!) you can apply the function to a.data instead.

>>> from scipy import sparse
>>> import numpy as np
>>> a = sparse.diags([1,4,9],[-1,0,1],shape =(10,10),format ="csr")
>>> a.data = np.sqrt(a.data)
>>> a
<10x10 sparse matrix of type '<class 'numpy.float64'>'
        with 28 stored elements in Compressed Sparse Row format>

Credit to DSM's comment for this answer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top