如何在Python的SciPy中删除稀疏矩阵中的小元素?

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

我有一个与肖恩·劳斯的例子非常相似的问题,您可以在这里找到:https://seanlaw.github.io/2019/02/27/set-values-in-sparse-matrix/

就我而言,我想删除稀疏csr矩阵中的所有绝对值都小于某些epsilon的元素。

首先我尝试了类似的东西

x[abs(x) < 3] = 0

但是SciPy关于效率低下的警告使我在上面的链接中对Sean Laws进行了解释。然后,我尝试操纵他的示例代码,但是找不到解决我问题的方法。

这里是代码,其中添加了一些否定条目。该示例代码将删除所有小于3的否定条目。我尝试使用np.abs()并添加了第二个逻辑运算符,但到目前为止没有成功。

import numpy as np
from scipy.sparse import csr_matrix

x = csr_matrix(np.array([[1, 0.1, -2, 0, 3], 
                         [0, -4, -1, 5, 0]]))


nonzero_mask = np.array(x[x.nonzero()] < 3)[0]
rows = x.nonzero()[0][nonzero_mask]
cols = x.nonzero()[1][nonzero_mask]

x[rows, cols] = 0
print(x.todense())

给予

[[0. 0. 0. 0. 3.]
 [0. 0. 0. 5. 0.]]

但是我想要的是

[[0. 0. 0. 0. 3.]
 [0. -4. 0. 5. 0.]]

非常感谢您的帮助,我觉得我缺少一些非常基本的东西。预先谢谢!

python math scipy sparse-matrix linear-algebra
2个回答
0
投票

x[x.nonzero()]包装到np.abs()中解决了问题:

>>> nonzero_mask = np.array(np.abs(x[x.nonzero()]) < 3)[0]
... 
>>> print(x.todense())                                                                                 
[[ 0.  0.  0.  0.  3.]
 [ 0. -4.  0.  5.  0.]]

2
投票
In [286]: from scipy import sparse                                              
In [287]: x = sparse.csr_matrix(np.array([[1, 0.1, -2, 0, 3],  
     ...:                          [0, -4, -1, 5, 0]])) 
     ...:  
     ...:    

您对x的测试也会选择0值,因此会出现效率警告。但是仅应用于data属性中的非零值:

In [288]: x.data                                                                
Out[288]: array([ 1. ,  0.1, -2. ,  3. , -4. , -1. ,  5. ])
In [289]: mask = np.abs(x.data)<3                                               
In [290]: mask                                                                  
Out[290]: array([ True,  True,  True, False, False,  True, False])
In [291]: x.data[mask]=0                                                        
In [292]: x.A                                                                   
Out[292]: 
array([[ 0.,  0.,  0.,  0.,  3.],
       [ 0., -4.,  0.,  5.,  0.]])

这实际上并没有从矩阵中删除元素,但是有一种清除方法:

In [293]: x                                                                     
Out[293]: 
<2x5 sparse matrix of type '<class 'numpy.float64'>'
    with 7 stored elements in Compressed Sparse Row format>
In [294]: x.eliminate_zeros()                                                   
In [295]: x                                                                     
Out[295]: 
<2x5 sparse matrix of type '<class 'numpy.float64'>'
    with 3 stored elements in Compressed Sparse Row format>
© www.soinside.com 2019 - 2024. All rights reserved.