简体   繁体   English

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

[英]Getting the number of stored elements of sparse matrix - Python

I'm working with large sparse matrices in Python.我正在使用 Python 处理大型稀疏矩阵。 The representation of my matrix gives me the number of stored elements, for example例如,矩阵的表示给出了存储元素的数量

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

My question is: how do I get Python to return the number 1244024860 to me?我的问题是:如何让 Python 将数字1244024860返回给我? I want to use this number as an approximation to the number of nonzero elements (even though some of the stored elements could be zeros).我想使用这个数字作为非零元素数量的近似值(即使一些存储的元素可能为零)。

For smaller matrices I was using the sparse_mat.count_nonzero() method but this method actually does computations (I guess that it checks that the stored elements are actually different from zero) and therefore it is very inefficient for my large matrix.对于较小的矩阵,我使用的是sparse_mat.count_nonzero()方法,但该方法实际上会进行计算(我猜它会检查存储的元素实际上是否不同于零),因此对于我的大矩阵来说效率非常低。

Use the nnz attribute.使用nnz属性。 For example,例如,

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

The attributes of the csr_matrix class are described in the csr_matrix documentation (scroll down to find them). csr_matrix类的属性在csr_matrix文档中进行了描述(向下滚动以找到它们)。

You ale looking for scipy.sparse.csr_matrix.getnnz .你正在寻找scipy.sparse.csr_matrix.getnnz

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

Number of stored values, including explicit zeros.存储值的数量,包括显式零。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM