python中的巨大稀疏矩阵

python中的巨大稀疏矩阵,python,memory,numpy,scipy,sparse-matrix,Python,Memory,Numpy,Scipy,Sparse Matrix,我需要在numpy/scipy中迭代构造一个巨大的稀疏矩阵。初始化在循环中完成: from scipy.sparse import dok_matrix, csr_matrix def foo(*args): dim_x = 256*256*1024 dim_y = 128*128*512 matrix = dok_matrix((dim_x, dim_y)) for i in range(dim_x): # compute stuff

我需要在numpy/scipy中迭代构造一个巨大的稀疏矩阵。初始化在循环中完成:

from scipy.sparse import dok_matrix, csr_matrix

def foo(*args):
    dim_x = 256*256*1024
    dim_y = 128*128*512
    matrix = dok_matrix((dim_x, dim_y))    

    for i in range(dim_x):
        # compute stuff in order to get j
        matrix[i, j] = 1.
    return matrix.tocsr()
然后我需要将其转换为csr_矩阵,因为进一步的计算如下:

matrix = foo(...)
result = matrix.T.dot(x)
一开始,这一切都很顺利。但是我的矩阵越来越大,我的电脑开始崩溃。有没有更优雅的方法来存储矩阵

基本上我有以下要求:

  • 矩阵需要从0存储浮点值。对1
  • 我需要计算矩阵的转置
  • 我需要用x_维向量计算点积
  • 矩阵尺寸可以在1*10^9 x 1*10^8左右

我的ram存储空间超过了。我读了几篇关于堆栈溢出和互联网其他部分的帖子;)我找到了PyTables,它不是真正为矩阵计算而设计的。。。等有更好的方法吗?

您可能已经达到了Python可以为您做的极限,或者您可以做得更多一些。尝试将数据类型设置为
np.float32
,如果您在64位计算机上,这种降低的精度可能会减少内存消耗
np.float16
可能对您的内存有更大的帮助,但您的计算速度可能会减慢(我见过一些示例,其中处理可能需要10倍的时间):

或者可能要慢得多,但内存消耗更少:

    matrix = dok_matrix((dim_x, dim_y), dtype=np.float16)    

另一个选择:购买更多的系统内存



最后,如果您可以避免使用
dok_matrix
创建矩阵,而可以使用
csr_matrix
创建矩阵(我不知道这是否适用于您的计算),您可以在
dok_matrix
使用的dict上节省一点开销。

对于您的情况,我建议使用数据类型
np.int8
(或
np.uint8
)每个元素只需要一个字节:

matrix = dok_matrix((dim_x, dim_y), dtype=np.int8)
直接构建
csr_矩阵
也将允许您进一步使用最大矩阵大小:

from scipy.sparse import csr_matrix

def foo(*args):
    dim_x = 256*256*1024
    dim_y = 128*128*512
    row = []
    col = []

    for i in range(dim_x):
        # compute stuff in order to get j
        row.append(i)
        col.append(j)
    data = np.ones_like(row, dtype=np.int8)

    return csr_matrix((data, (row, col)), shape=(dim_x, dim_y), dtype=np.int8)

我认为这可能更像是一个数学/数值分析问题:)在我的数值分析中。当然,制作这种大小的矩阵的唯一方法是使其成为三对角矩阵。另外,我知道您要求的是numpy,但我有一个完成了一些的python库。当你问这个问题时,你似乎想存储浮点数,但你接受了一个建议ints的答案。我只是好奇——我错过了什么?谢谢
from scipy.sparse import csr_matrix

def foo(*args):
    dim_x = 256*256*1024
    dim_y = 128*128*512
    row = []
    col = []

    for i in range(dim_x):
        # compute stuff in order to get j
        row.append(i)
        col.append(j)
    data = np.ones_like(row, dtype=np.int8)

    return csr_matrix((data, (row, col)), shape=(dim_x, dim_y), dtype=np.int8)