python - 获取稀疏矩阵的存储元素数量 - 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()
方法,但该方法实际上进行了计算(我猜它检查存储的元素实际上是否不同于零),因此对于我的大矩阵来说效率非常低。
解决方案
使用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
推荐阅读
- python - 让 POST 请求像 GET 请求一样工作?djangorestframework-datatables
- c++ - C++ 中的模块化
- javascript - Reactive Native TypeError: undefined is not an object (evalating 'response.success')
- google-bigquery - BigQuery 似乎每两个月就会删除一次从 Segment 传输的数据
- javascript - 是否可以返回字符串和数字实例的原始值?
- c - C 程序:[Done] 在 2.322 秒内以 code=3221225477 退出(Calloc / Free / Segmenation Error?)
- python - blit_buffer 函数在没有任何警告的情况下关闭 Kivy 应用程序
- c - 单独编译代码中结构的二进制兼容性
- git - 如何接管别人的开放拉取请求?
- vue.js - 如何仅在 vuejs 中上传图像文件?