繁体   English   中英

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

[英]Efficiently inversing a `csr_matrix` in `scipy` element-wise

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

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

这有两个缺点:

  1. 通过将 csr_matrix 转换为数组来增加内存使用量。
  2. 除以零发生

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

你可以做到这一点的方法之一是创建从一个新的矩阵dataindicesindptrAB = 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. , 0. , 0. ],
       [0. , 0. , 0. , 4. ],
       [2. , 0. , 0. , 0. ]])

In [110]: B = csr_matrix((1/A.data, A.indices, 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.  , 1.  , 0.4 , 0.  ],
       [0.  , 0.  , 0.  , 0.  ],
       [0.  , 0.  , 0.  , 0.25],
       [0.5 , 0.  , 0.  , 0.  ]])

csr有一个power方法:

In [598]: M = sparse.csr_matrix([[0,3,2],[.5,0,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,  0. , 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       ],
       [2.        , 0.        , 0.1       ]])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM