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