【发布时间】:2013-01-08 19:06:32
【问题描述】:
我有一组填充了布尔值的稀疏矩阵,我需要对这些矩阵执行逻辑运算(主要是按元素或)。
在 numpy 中,使用 dtype='bool' 对矩阵求和给出了元素 OR,但是有一个讨厌的副作用:
>>> from scipy import sparse
>>> [a,b] = [sparse.rand(5,5,density=0.1,format='lil').astype('bool')
... for x in range(2)]
>>> b
<5x5 sparse matrix of type '<class 'numpy.bool_'>'
with 2 stored elements in LInked List format>
>>> a+b
<5x5 sparse matrix of type '<class 'numpy.int8'>'
with 4 stored elements in Compressed Sparse Row format>
数据类型更改为“int8”,这会导致以后的操作出现问题。这可以通过以下方式解决:
(a+b).astype('bool')
但我的印象是,所有这些类型的更改都会导致性能下降。
为什么结果的 dtype 与操作数不同?
有没有更好的方法在 python 中对稀疏矩阵进行逻辑运算?
【问题讨论】:
标签: python scipy sparse-matrix