首页 > 解决方案 > 获取稀疏矩阵的存储元素数量 - Python

问题描述

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

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

我的问题是:如何让 Python 将数字返回1244024860给我?我想将此数字用作非零元素数量的近似值(即使某些存储的元素可能为零)。

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

标签: pythonscipysparse-matrix

解决方案


使用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中描述了类的属性(向下滚动以找到它们)。csr_matrix


推荐阅读