python - 为什么 scipy 稀疏矩阵内存使用对矩阵中元素的数量无动于衷?

标签 python memory scipy sparse-matrix

我有两个带有 bool 值的 scipy 矩阵“a”和“b”。 “a”比“b”大得多:765565 个值,而只有 3 个值。

In [211]: a
Out[211]: <388839x8455 sparse matrix of type '<class 'numpy.bool_'>'
           with 765565 stored elements in Compressed Sparse Row format>
In [212]: b
Out[212]: <5x3 sparse matrix of type '<class 'numpy.bool_'>'
           with 3 stored elements in Compressed Sparse Row format>

但是当我根据内存使用情况检查它们的大小时,我发现它们都只有 56 字节:

In [213]: from sys import getsizeof
          'Size of a: {}. Size of b: {}'.format(getsizeof(a), getsizeof(b))
Out[213]: 'Size of a: 56. Size of b: 56'

为什么这些矩阵的大小相同,而矩阵“a”必须存储比矩阵“b”多 20 万倍的值?

最佳答案

这是一个小演示:

from scipy import sparse

M = sparse.random(10**4, 10**3, .001, 'csr')

def sparse_memory_usage(mat):
    try:
        return mat.data.nbytes + mat.indptr.nbytes + mat.indices.nbytes
    except AttributeError:
        return -1

In [140]: sparse_memory_usage(np.random.rand(100, 100))
Out[140]: -1

In [141]: M = sparse.random(10**4, 10**3, .001, 'csr')

In [142]: sparse_memory_usage(M)
Out[142]: 160004

In [144]: M
Out[144]:
<10000x1000 sparse matrix of type '<class 'numpy.float64'>'
        with 10000 stored elements in Compressed Sparse Row format>

关于python - 为什么 scipy 稀疏矩阵内存使用对矩阵中元素的数量无动于衷?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43681279/

相关文章:

C++ 无锁模板化对象池

python - scipy stats binom cdf 返回 nan

python - 基于网格的多元三次插值

python - 如何使用 Cloudflare SSL 证书设置简单的 https 服务器?

python - 在 Python 中即时在磁盘上构造稀疏矩阵

c++ - 为什么我需要删除[]?

python - 如何确定哪条回归曲线拟合得更好? PYTHON

python - os.walk() 缓存/加速

python - 网络驱动程序异常 : Message: quit

python - Python 中的 'Type' 和 'Object' 有什么区别