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

标签 python math scipy sparse-matrix linear-algebra

我有一个与 Sean Laws 示例非常相似的问题,您可以在此处找到: 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.]]

非常感谢任何帮助,我觉得我缺少一些非常基本的东西。 提前致谢!

最佳答案

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>

关于python - 如何在 Python 的 SciPy 中删除稀疏矩阵中的小元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59567002/

相关文章:

python - python multiprocessing 出现奇怪的进程克隆

c++ - 从 3d 中的起点和角度计算直线

python - numba 类型与 nd 过滤器匹配

python - scipy.linalg.inv 是否检查矩阵是否为对角矩阵?

python - 在 GIL 之外使用 scipy 例程

python - 如何存储回调方法?

python - 在使用 django-filter 进行过滤时如何将过滤后的值导出到 csv 文件中

python - 查找由具有 x、y、w、h 像素坐标的矩形覆盖的图 block 的坐标

python - 将文件加载到变量中

math - Mathematica 中的整数优化?