scipy.sparse 矩阵逐元素幂运算

17 投票
2 回答
8189 浏览
提问于 2025-04-16 20:02

我想知道怎么对一个 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 方法。

2 个回答

21

我刚好遇到了同样的问题,发现稀疏矩阵现在支持逐元素的幂运算。对于上面的情况,应该是:

 X.power(2)
12

这有点儿底层,不过对于逐个元素的操作,你可以直接使用底层的数据数组:

>>> 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

撰写回答