【问题标题】:Getting the number of stored elements of sparse matrix - Python获取稀疏矩阵的存储元素数量 - Python
【发布时间】:2018-08-24 10:03:33
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: python scipy sparse-matrix


    【解决方案1】:

    使用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 documentation 中进行了描述(向下滚动以找到它们)。

    【讨论】:

      【解决方案2】:

      你在寻找scipy.sparse.csr_matrix.getnnz

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

      存储值的数量,包括显式零。

      【讨论】:

      • 使用该方法而不是nnz属性有优势吗?
      • 可能不会。我根本不知道底层属性是公开的和记录在案的。
      • A.getnnz( axis=1 ) 获取每行非零的数量,A.getnnz( axis=0 ) 每列,A.getnnz() == A.nnz
      猜你喜欢
      • 2021-12-30
      • 2012-08-27
      • 2021-06-26
      • 1970-01-01
      • 2015-09-01
      • 2016-04-15
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      相关资源
      最近更新 更多