将 .data 属性中的元素设置为零 scipy.sparse 中令人不快的行为

2023-12-29

当我设置值时,我的行为令人不快.data of csr_matrix为零。这是一个例子:

from scipy import sparse
a = sparse.csr_matrix([[0,0,2,0], [1,1,0,0],[0,3,0,0]])

Output:

>>> a.A
array([[0, 0, 2, 0],
       [1, 1, 0, 0],
       [0, 3, 0, 0]])
>>> a.data
array([2, 1, 1, 3])
>>> a.data[3] = 0   # setting one element to zero
>>> a.A
array([[0, 0, 2, 0],
       [1, 1, 0, 0],
       [0, 0, 0, 0]])
>>> a.data
array([2, 1, 1, 0]) # however, this zero is still considered part of data
                    # what I would like to see is:
                    # array([2, 1, 1])

>>> a.nnz           # also `nnz` tells me that there 4 non-zero elements 
                    # which is incorrect, I would like 3 as an output
4

>>> a.nonzero()     # nonzero method does follow the behavior I expected
(array([0, 1, 1], dtype=int32), array([2, 0, 1], dtype=int32))

上述情况的最佳做法是什么?应该设置元素.data可以避免为零吗?是.nnz找到零个数的方法不可靠吗?


scipy 中的稀疏矩阵(至少 CSC 和 CSR)有一个.eliminate_zeros() http://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.csc_matrix.eliminate_zeros.html#scipy.sparse.csc_matrix.eliminate_zeros方法来处理这种情况。跑步

a.eliminate_zeros()

每次你惹事a.data,它应该照顾它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将 .data 属性中的元素设置为零 scipy.sparse 中令人不快的行为 的相关文章

随机推荐