python - scipy.sparse_matrix 中元素的批量归零

标签 python scipy sparse-matrix

我有一个 scipy.sparse_matrix A 并且我想将相当大的元素部分归零。 (在我今天使用的矩阵中,A 有大约 70M 个条目,我想将其中的大约 700K 个归零)。我有几种不同格式的这些元素,但现在它们位于与 A 具有相同维度且具有 0/1 值的 sparse_matrix B 中。

如果这些是密集矩阵(编辑:numpy 数组),我可以 A = A-A*B 但是我还没有想出任何简单的方法来用稀疏矩阵来做这些。 (或者实际上除了(a)遍历 B 中的元素并在这些元素处将 A 设置为 0 或(b)将所有内容转换为密集,对于我所拥有的大小,这几乎不适合内存......)

最佳答案

Scipy 的稀疏矩阵有一个multiply 方法可以进行逐点乘法。你可以简单地做:

A = A - A.multiply(B)

我认为您可能必须运行 eliminate_zeros() 方法来删​​除归零的条目,但显然这不是必需的:

>>> sp_mat
<1000000x1000000 sparse matrix of type '<type 'numpy.float64'>'
    with 1000 stored elements in Compressed Sparse Row format>
>>> zero_mat
<1000000x1000000 sparse matrix of type '<type 'numpy.int32'>'
    with 96 stored elements in Compressed Sparse Row format>
>>> sp_mat - sp_mat.multiply(zero_mat)
<1000000x1000000 sparse matrix of type '<type 'numpy.float64'>'
    with 904 stored elements in Compressed Sparse Row format>

关于python - scipy.sparse_matrix 中元素的批量归零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14840243/

相关文章:

cuda - 使用 cuSPARSE 在 CUDA 中进行稀疏矩阵矩阵乘法

python - 简单的 HTML 到 PDF python 库错误

python - 如何用一些规则将字符串分成组?

python - 如何将多个数据框附加到一个数据框中

Python:区分行向量和列向量

python - 树莓派 2-无法安装 scikit-image

使用求解器进行 Python 优化

python - 如何使用 scipy.sparse.csr_matrix.minimum 忽略隐式零?

python - 使用python计算输入的位数

c++逐列构造矩阵读取列