Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise power of scipy.sparse matrix

How do I raise a scipy.sparse matrix to a power, element-wise? numpy.power should, according to its manual, do this, but it fails 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 wastes precious seconds.

I've had the same problem with np.multiply, which I solved using the sparse matrix's multiply method, but there seems to be no pow method.

like image 894
Fred Foo Avatar asked Jun 21 '11 20:06

Fred Foo


People also ask

What is a SciPy sparse matrix?

Python's SciPy provides tools for creating sparse matrices using multiple data structures, as well as tools for converting a dense matrix to a sparse matrix. The sparse matrix representation outputs the row-column tuple where the matrix contains non-zero values along with those values.

Which element in sparse matrix is?

Explanation: Sparse Matrix is a matrix in which most of the elements are Zero. Identity Matrix is a matrix in which all principle diagonal elements are 1 and rest of the elements are Zero.

What is the time complexity of sparse matrix?

The computational complexity of sparse matrix multiplication on AP is shown to be an O(nnz) where nnz is the number of nonzero elements. The AP is found to be especially efficient in binary sparse matrix multiplication. AP outperforms conventional solutions in power efficiency.

How do SciPy sparse matrices multiply?

We use the multiply() method provided in both csc_matrix and csr_matrix classes to multiply two sparse matrices. We can multiply two matrices of same format( both matrices are csc or csr format) and also of different formats ( one matrix is csc and other is csr format).


1 Answers

I just ran into the same question and find that sparse matrix now supports element-wise power. For the case above, it should be:

 X.power(2)
like image 63
Joyce Zhang Avatar answered Oct 02 '22 14:10

Joyce Zhang