稀疏矩阵的逐元素方次幂 [英] Element-wise power of scipy.sparse matrix
本文介绍了稀疏矩阵的逐元素方次幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何将scipy.sparse
矩阵提升为幂(逐元素)?根据其手册 ,执行此操作,但在稀疏矩阵上失败:
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
与X**2
相同的问题.转换为密集数组是可行的,但会浪费宝贵的时间.
Same problem with X**2
. Converting to a dense array works, but wastes precious seconds.
我遇到了与np.multiply
相同的问题,我使用稀疏矩阵的multiply
方法解决了该问题,但似乎没有pow
方法.
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.
推荐答案
这有点底层,但是对于元素级操作,您可以直接使用基础数据数组:
This is a little low-level, but for element-wise operations you can work with the underlying data array directly:
>>> 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
这篇关于稀疏矩阵的逐元素方次幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文