1

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?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Guangyue He
  • 269
  • 1
  • 3
  • 14
  • 2
    I think your question is answered [here](http://stackoverflow.com/questions/8906506/how-to-operate-elementwise-on-a-matrix-of-type-scipy-sparse-csr-matrix): you can use `a.sqrt()` or act on `a.data` for anything that doesn't have a native hook. – DSM Jan 12 '14 at 02:59
  • @DSM: `a.sqrt()` should be an answer. – Warren Weckesser Jan 12 '14 at 03:50
  • @DSM thanks. a.sqrt() works. Just need to make sure that the right version of scipy is installed. – Guangyue He Jan 12 '14 at 16:33
  • @DSM What if I want to take power of two(square) of each of the elements in a sparse matrix? Any suggestions? thanks. – Guangyue He Jan 12 '14 at 17:10
  • @DSM for square, I just found out a method. a.multiply(a) works.I can use it as a substitute. – Guangyue He Jan 12 '14 at 17:24

2 Answers2

2

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

Stephen Diehl
  • 8,271
  • 5
  • 38
  • 56
1

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.

Scott Gigante
  • 1,450
  • 1
  • 17
  • 29