Python + 不断增加的内存分配

Python + Ever-increasing memory allocation

我正在编写一个模块来在大型数据集上训练 ML 模型 - 它包括 0.6M 数据点,每个数据点 0.15M 维度。我在加载数据集本身时遇到问题。 (它都是 numpy 数组)

下面是一个代码片段(这复制了实际代码的主要行为):

import numpy
import psutil

FV_length = 150000
X_List = []
Y_List = []

for i in range(0,600000):
    feature_vector = numpy.zeros((FV_length),dtype=numpy.int)
    # using db data, mark the features to activated 
    class_label = 0
    X_List.append(feature_vector)
    Y_List.append(class_label)

    if (i%100 == 0):
        print(i)
        print("Virtual mem %s" %(psutil.virtual_memory().percent))
        print("CPU usage %s" %psutil.cpu_percent())

X_Data = np.asarray(X_List)
Y_Data = np.asarray(Y_List)

代码导致内存分配不断增加,直到它被杀死。有没有办法减少不断增加的内存分配

我试过使用 gc.collect() 但它总是 returns 0。我明确地使变量 = None,不再使用。

如评论中所述,此处的数据量非常大,即使您设法加载训练集,神经网络也可能会遇到困难。对您来说最好的选择可能是研究一些对数据点进行降维的方法。诸如主成分分析之类的东西可以帮助将 150K 维度降低到更合理的数字。

这是我针对类似问题所做的。当它应该被覆盖时,我总是再次创建空列表。

#initialize

X_List = [] 
Y_List = []


//do something with the list

现在,如果您不需要旧值,只需重新创建列表即可

X_List = [] 
Y_List = []

但我不知道您的情况是否需要或可能这样做。也许这是最惯用的方式,但它确实有效。