scipy.sparse 矩阵的逐元素幂
如何将 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
方法。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我刚刚遇到了同样的问题,发现稀疏矩阵现在支持逐元素幂。对于上面的情况,应该是:
I just ran into the same question and find that sparse matrix now supports element-wise power. For the case above, it should be:
这有点低级,但对于逐元素操作,您可以直接使用底层数据数组:
This is a little low-level, but for element-wise operations you can work with the underlying data array directly: