Skip to main content
 首页 » 编程设计

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

2025年02月15日8lyhabc

我有两个带有 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>