减去csr矩阵而不减少存储的元素

问题描述 投票:0回答:1

我正在处理减去稀疏矩阵。不幸的是,如果某个单元格减去后等于0,它就会消失。

我期望它在存储的元素中,但是值等于零。

一些简化的示例:

import scipy.sparse as sparse
import numpy as np
row = np.array([0, 1])
col = np.array([0, 1])
data = np.array([1 ,1])
sample_csr=sparse.csr_matrix((data, (row, col)))
display(sample_csr-sample_csr) # what I have
display(sample_csr*0) # what I want
python scipy sparse-matrix
1个回答
0
投票
In [844]: row = np.array([0, 1]) 
     ...: col = np.array([0, 1]) 
     ...: data = np.array([1 ,1]) 
     ...: sample_csr=sparse.csr_matrix((data, (row, col)))                                             
In [845]: sample_csr                                                                                   
Out[845]: 
<2x2 sparse matrix of type '<class 'numpy.longlong'>'
    with 2 stored elements in Compressed Sparse Row format>
In [846]: _.A                                                                                          
Out[846]: 
array([[1, 0],
       [0, 1]], dtype=int64)

减去2个矩阵将返回一个新矩阵;它不会修改sample_csr

In [847]: sample_csr-sample_csr                                                                        
Out[847]: 
<2x2 sparse matrix of type '<class 'numpy.longlong'>'
    with 0 stored elements in Compressed Sparse Row format>

您可以就地修改矩阵的data

In [848]: sample_csr=sparse.csr_matrix((data, (row, col)))                                             
In [849]: sample_csr.data *= 0                                                                         
In [850]: sample_csr                                                                                   
Out[850]: 
<2x2 sparse matrix of type '<class 'numpy.longlong'>'
    with 2 stored elements in Compressed Sparse Row format>

实际上,为了提高效率,sparse.csr允许进行许多更改而无需弄清新的稀疏性。如果尝试执行需要更改稀疏度的操作(例如添加非零值),您甚至可能收到效率警告。

并在一系列操作后清理稀疏性:

In [851]: sample_csr.eliminate_zeros()                                                                 
In [852]: sample_csr                                                                                   
Out[852]: 
<2x2 sparse matrix of type '<class 'numpy.longlong'>'
    with 0 stored elements in Compressed Sparse Row format>

我不知道您想要保留0的方法。大概需要对跟踪两个操作数的稀疏性的方式进行深刻的更改。

稀疏矩阵,尤其是csr格式,已针对矩阵乘法进行了优化。其他数学运算(例如元素逐加法和减法)要慢得多。

© www.soinside.com 2019 - 2024. All rights reserved.