The elemental power of the matrix scipy.sparse

How to raise the scipy.sparse matrix to the level of power, by elements? numpy.power should, according to his manual , do this, but it does not work on sparse matrices:

 >>> X <1353x32100 sparse matrix of type '<type 'numpy.float64'>' with 144875 stored elements in Compressed Sparse Row format> >>> np.power(X, 2) Traceback (most recent call last): File "<stdin>", line 1, in <module> File ".../scipy/sparse/base.py", line 347, in __pow__ raise TypeError('matrix is not square') TypeError: matrix is not square 

Same problem with X**2 . Converting to a dense array works, but spends precious seconds.

I had the same problem with np.multiply , which I decided to use using the multiply sparse matrix method, but there seems to be no pow method.

+14
source share
2 answers

This is a bit low-level, but for basic operations you can directly work with the underlying data array:

 >>> import scipy.sparse >>> X = scipy.sparse.rand(1000,1000, density=0.003) >>> X = scipy.sparse.csr_matrix(X) >>> Y = X.copy() >>> Y.data **= 3 >>> >>> abs((X.toarray()**3-Y.toarray())).max() 0.0 
+9
source

I came across the same question and found that a sparse matrix now supports elemental strength. In the above case, it should be:

  X.power(2) 
+4
source

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


All Articles