sqrt for element-wise sparse matrix

我是研究僧i 提交于 2019-12-08 04:24:26

问题


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?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/21070690/sqrt-for-element-wise-sparse-matrix

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