gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 16:48:49 26 4
gpt4 key购买 nike

我有一个与 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com