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.
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.
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.
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.
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).
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With