获取稀疏矩阵的存储元素数 - Python

Getting the number of stored elements of sparse matrix - Python

我正在 Python 中处理大型稀疏矩阵。我的矩阵表示给出了存储元素的数量,例如

<100000x100000 sparse matrix of type '<type 'numpy.float64'>'
    with 1244024860 stored elements in Compressed Sparse Row format>

我的问题是:如何让 Python 到 return 号码 1244024860 给我? 我想使用这个号码作为非零元素数量的近似值(即使某些存储的元素可能为零)。

对于较小的矩阵,我使用的是 sparse_mat.count_nonzero() 方法,但该方法实际上会进行计算(我猜它会检查存储的元素实际上是否不同于零),因此对于我的大矩阵来说效率非常低.

您正在寻找 scipy.sparse.csr_matrix.getnnz

https://docs.scipy.org/doc/scipy-0.19.0/reference/generated/scipy.sparse.csr_matrix.getnnz.html

Number of stored values, including explicit zeros.

使用 nnz 属性。例如,

In [80]: a = csr_matrix([[0, 1, 2, 0], [0, 0, 0, 0], [0, 0, 0, 3]])

In [81]: a
Out[81]: 
<3x4 sparse matrix of type '<class 'numpy.int64'>'
    with 3 stored elements in Compressed Sparse Row format>

In [82]: a.nnz
Out[82]: 3

csr_matrix class 的属性在 csr_matrix documentation 中描述(向下滚动找到它们)。