为什么 scipy 稀疏矩阵内存使用量与矩阵中元素的数量无关?

Ser*_*rov 5 python memory scipy sparse-matrix

我有两个 scipy 矩阵“a”和“b”,其中包含布尔值。“a”比“b”大得多:765565 个值,而只有 3 个值。

\n\n
In\xc2\xa0[211]: a\nOut[211]: <388839x8455 sparse matrix of type '<class 'numpy.bool_'>'\n           with 765565 stored elements in Compressed Sparse Row format>\nIn\xc2\xa0[212]: b\nOut[212]: <5x3 sparse matrix of type '<class 'numpy.bool_'>'\n           with 3 stored elements in Compressed Sparse Row format>\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
In\xc2\xa0[213]: from sys import getsizeof\n          'Size of a: {}. Size of b: {}'.format(getsizeof(a), getsizeof(b))\nOut[213]: 'Size of a: 56. Size of b: 56'\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n

Max*_*axU 3

这是一个小演示:

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
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)