17

如何在scipy.sparse元素方面将矩阵提升到幂?numpy.power应该,根据它的手册,这样做,但它在稀疏矩阵上失败:

>>> 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。转换为密集阵列是可行的,但会浪费宝贵的时间。

我遇到了同样的问题np.multiply,我使用稀疏矩阵的multiply方法解决了这个问题,但似乎没有pow方法。

4

2 回答 2

20

我刚刚遇到了同样的问题,发现稀疏矩阵现在支持按元素计算。对于上述情况,它应该是:

 X.power(2)
于 2017-04-09T07:19:08.143 回答
11

这有点低级,但对于元素操作,您可以直接使用底层数据数组:

>>> 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
于 2011-06-21T21:23:21.707 回答