制作大零矩阵python的内存有效方法

epa*_*aro 1 python memory performance numpy scipy

我目前正在尝试制作一个非常大的矩阵,我不确定如何以高效的内存方式进行。

我试图使用 numpy,它适用于我的小机箱 (2750086X300) 但是,我得到了一个更大的 2750086X1000,它对我来说太大了,无法运行。

我想用整数来制作它,但我会向它添加浮点值,所以不确定 cld 会如何影响它。

我试图找到一些关于制作稀疏零填充数组的东西,但 cldnt 在这里或其他地方找不到任何很好的主题/问题/建议。

有人有什么好的建议吗?我目前正在使用 python,所以我正在寻找一个 pythonic 解决方案,但我愿意尝试其他语言。

谢谢


编辑:

谢谢你的建议,我试过 scipy.sparse.csr_matrix 它设法创建了一个矩阵,但大大增加了通过它的时间。

这是我正在做的事情:

matrix = scipy.sparse.csr_matrix((df.shape[0], 300))
## matrix = np.zeros((df.shape[0], 

for i, q in enumerate(df['column'].values):    

    matrix[i, :] = function(q)
Run Code Online (Sandbox Code Playgroud)

其中函数几乎是该行上的向量运算函数。

现在,如果我在 np.zeros 上进行循环,它会很容易完成,大约 10 分钟。

现在,如果我尝试对 scipy 稀疏矩阵做同样的事情,大约需要 50 个小时。这不是那么合理。

有什么建议吗?


编辑2:

scipy.sparse.lil_matrix 做到了

循环需要大约 20 分钟,并且使用的内存比 np.zeros 少

谢谢。


编辑3:

还是内存贵。决定不在矩阵上存储数据。一次处理 1 行。从中获取相关值/指标,将值存储在原始 df 中,再次运行。

Mir*_*ber 7

尝试scipy.sparse.csr_matrix

from scipy.sparse import *
from scipy import *
a=csr_matrix( (2750086,1000), dtype=int8 )
Run Code Online (Sandbox Code Playgroud)

然后a

<2750086x1000 sparse matrix of type '<class 'numpy.int8'>'
    with 0 stored elements in Compressed Sparse Row format>
Run Code Online (Sandbox Code Playgroud)

例如,如果你这样做:

from scipy.sparse import *
from scipy import *
a=csr_matrix( (5,4), dtype=int8 ).todense()
print(a)
Run Code Online (Sandbox Code Playgroud)

你得到:

[[0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]
 [0 0 0 0]]
Run Code Online (Sandbox Code Playgroud)

另一种选择是使用scipy.sparse.lil_matrix

a = scipy.sparse.lil_matrix((2750086,1000), dtype=int8 )
Run Code Online (Sandbox Code Playgroud)

这对于设置元素(如a[1,1]=2)似乎更有效。