微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在`scipy`元素方面有效地反转`csr_matrix`

如何解决在`scipy`元素方面有效地反转`csr_matrix`

让$A$ 是一个csr_matrix,代表一个图的连通性矩阵,其中$A_{ij}$ 是一条边的权重。现在,我需要以有效的方式反转矩阵的每个非零元素。我现在这样做的方式是

B = 1.0 / A.toarray()
B[B == np.inf] = 0

这有两个缺点:

  1. 将 csr_matrix 转换为数组会增加内存使用量。
  2. 发生被零除

有什么建议可以更有效地做到这一点吗?

解决方法

您可以这样做的一种方法是从 dataindicesindptrA 创建一个新矩阵:B = csr_matrix((1/A.data,A.indices,A.indptr))

(假设 A 中没有明确存储的零,因此 1/A.data 不会导致某些值为 inf。)

例如

In [108]: A
Out[108]: 
<4x4 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

In [109]: A.A
Out[109]: 
array([[0.,1.,2.5,0. ],[0.,0.,4. ],[2.,0. ]])

In [110]: B = csr_matrix((1/A.data,A.indptr))

In [111]: B
Out[111]: 
<4x4 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>

In [112]: B.A
Out[112]: 
array([[0.,0.4,0.  ],0.25],[0.5,0.  ]])
,

csr 有一个 power 方法:

In [598]: M = sparse.csr_matrix([[0,3,2],[.5,10]])
In [599]: M
Out[599]: 
<2x3 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>
In [600]: M.A
Out[600]: 
array([[ 0.,3.,2. ],[ 0.5,10. ]])
In [601]: x = M.power(-1)
In [602]: x
Out[602]: 
<2x3 sparse matrix of type '<class 'numpy.float64'>'
    with 4 stored elements in Compressed Sparse Row format>
In [603]: x.A
Out[603]: 
array([[0.,0.33333333,0.5       ],0.1       ]])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。