Fre*_*Foo 16 python numpy exponentiation scipy sparse-matrix
如何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
Run Code Online (Sandbox Code Playgroud)
同样的问题X**2.转换为密集阵列有效,但浪费了宝贵的秒数.
我有同样的问题np.multiply,我用稀疏矩阵的multiply方法解决了,但似乎没有pow方法.
DSM*_*DSM 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4870 次 |
| 最近记录: |