如何有效地在内存中存储可变数量的 scipy sparse.csr_matrix?

How to efficiently store variable number of scipy sparse.csr_matrix in memory?

我有大约 10,000 个稀疏矩阵,每个矩阵的大小为 50,000x5,平均密度为 0.0004。 对于每个循环(10000 次),我正在计算 numpy 数组并将其转换为 csr_matrix 并将其附加到列表中。但是内存消耗与附加 numpy 数组一样高,但不如附加 csr_matrices.

如何在内存中保留这 10K 个稀疏矩阵以进行进一步计算时减少内存消耗?

示例代码:

from scipy.sparse import csr_matrix
import numpy as np
sparse_matrices = []

for i in range(10000):
    np_array = get_np_array()
    sparse_matrix = csr_matrix(np_array)
    sparse_matrices.append(sparse_matrix)
    print np_array.nbytes, sparse_matrix.data.nbytes, repr(sparse_matrix)

会输出类似的东西,这清楚地表明我正在附加压缩矩阵。但是,内存的增长与附加 numpy 矩阵一样。

1987520 520 <49688x5 sparse matrix of type '<type 'numpy.float64'>'
    with 65 stored elements in Compressed Sparse Row format>
1987520 512 <49688x5 sparse matrix of type '<type 'numpy.float64'>'
    with 64 stored elements in Compressed Sparse Row format>

刚刚意识到,如果我使用 coo_matrix 而不是 csr_matrix,内存消耗是合理的。如果那是 csr_matrix 内存大约 ~8gb。

对于矩阵:

<49688x5 sparse matrix of type '<type 'numpy.float64'>'
with 65 stored elements in Compressed Sparse Row format>

coo格式中,关键属性为rowcoldata,均有65个元素。 data 是浮点数,其他是整数(行和列索引)。

csr 格式中,row 属性被替换为 indptr,每行有一个值(加 1?)。使用这种形状 indptr 是 49688 个元素长。如果是 csc 格式 indptr 将只有 5 个元素。

csr 通常比 coo 更紧凑。但是在您的情况下,有很多空白行;所以它要大得多。 csr如果是单行矩阵会特别紧凑;如果它是列向量,则根本不紧凑。