如何解决在python中处理巨大数据集时分配内存的问题



我正在为30000行的数据集编程BOW代码。我有X_train,它是(21000,2(。这两行是:标题和说明。所以,我有以下代码:

def text_to_bow(text: str) -> np.array:
text = text.split()
res = np.zeros(len(bow_vocabulary)) #bow_vocabulary includes 10000 most popular tokens
for word in text:
for i in range(len(bow_vocabulary)):
if word == bow_vocabulary[i]:
res[i] += 1
return res
def items_to_bow(items: np.array) -> np.array:
desc_index = 1
res = np.empty((0,k), dtype='uint8')
for i in range(len(items)):
description = items[i][desc_index]
temp = text_to_bow(description)
res = np.append(res, [temp], axis=0)
return np.array(res)

我的代码似乎工作正常,因为我的任务中有几个断言。

所以,当我运行时:

X_train_bow = items_to_bow(X_train)

我得到错误:

MemoryError: Unable to allocate 12.1 MiB for an array with shape (158,
10000) and data type float64

我已经在Ubuntu中将overcommit_memory设置为1,但这并没有帮助。我不想使用64位python,因为模块可能有问题。

我还尝试了另一个函数(使用常规数组(:

def items_to_bow(items: np.array) -> np.array:
desc_index = 1
res = []
for i in range(len(items)):
description = items[i][desc_index]
temp = text_to_bow(description)
res.append(temp)
if len(res)//1000 > 0:
print(len(res))
return np.array(res)

但它似乎要工作一个小时左右,这并不方便。

有什么办法解决这个问题吗?如有任何可能的帮助,我们将不胜感激。

执行分块。在panda中,可以使用chunksize参数。读取数据块。处理数据。将输出附加到文件中。确保区块已删除。重复

最新更新