led*_*che 2 python math linear-algebra scipy sparse-matrix
我有一个与 Sean Laws 示例非常相似的问题,您可以在这里找到: https: //seanlaw.github.io/2019/02/27/set-values-in-sparse-matrix/
就我而言,我想删除稀疏 csr 矩阵中的所有元素,这些元素的绝对值小于某个 epsilon。
首先我尝试了类似的东西
x[abs(x) < 3] = 0
Run Code Online (Sandbox Code Playgroud)
但是 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())
Run Code Online (Sandbox Code Playgroud)
给出
[[0. 0. 0. 0. 3.]
[0. 0. 0. 5. 0.]]
Run Code Online (Sandbox Code Playgroud)
但我想要的是
[[0. 0. 0. 0. 3.]
[0. -4. 0. 5. 0.]]
Run Code Online (Sandbox Code Playgroud)
非常感谢任何帮助,我觉得我缺少一些非常基本的东西。先感谢您!
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]]))
...:
...:
Run Code Online (Sandbox Code Playgroud)
您的测试也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.]])
Run Code Online (Sandbox Code Playgroud)
这实际上并没有从矩阵中删除元素,但有一种清理方法:
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>
Run Code Online (Sandbox Code Playgroud)