使用 gensim.utils.simple_preprocess 的 Python 内存错误

问题描述

我是 gensim word2vec 的初学者,在准备用于训练模型的文本时遇到内存错误。我正在使用 Python 3.8.8。我在 12 个不同的文件夹中有大约 900,000 个文本文件。我想我应该通过 gensim.utils.simple_preprocess 发送所有文本文档,然后我会有一个模型列表。在浏览了大约 150,000 个文档后,我收到了一个内存错误

Traceback (most recent call last):
  File "word2vec_part1.py",line 58,in <module>
    documents = list(read_input(paths))
  File "word2vec_part1.py",line 39,in read_input
    myfile = infile.read()
MemoryError

有没有办法解决这个内存问题?我在下面包含了我正在使用的代码。我是 Python、word2vec 和 stackoverflow 的新手,所以如果我的问题措辞不当或者这是一个愚蠢的问题,我深表歉意!感谢您的时间!

# imports and logging

import gensim 
import logging
import os
import os.path
import glob


logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s',level=logging.INFO)

# define function

def read_input(inputs):

    # logging info
    logging.info("reading files")

    # set working directories and load files into a list
    for path in inputs:
        os.chdir(path)
        read_files=glob.glob("*.txt") 
        # preprocess and counting
        for i,file in enumerate(read_files):
            if(i%10000==0):
                logging.info("read {0} reviews".format(i))
            # preprocessing and return a list of words
            with open(file,"rb") as infile:
                myfile = infile.read()
                yield gensim.utils.simple_preprocess(myfile)


# create a list of all file paths
paths = [#here is a list of file paths]

# call function
documents = list(read_input(paths))
logging.info("done reading files!!")
print(len(documents))
print(documents[1])

# training word2vec model
model = gensim.models.Word2Vec (documents,size=150,window=10,min_count=2)
model.train(documents,total_examples=len(documents),epochs=10)
model.save("word2vec.model")

# look up top 6 words similar to 'law'
w1 = ["law"]
model.wv.most_similar (positive=w1,topn=6)

logging.info("done!!!")

解决方法

似乎试图将 list 中的所有文档保存在内存中需要比系统更多的 RAM。 (也许还有:其中一个文件很大。最大的单个文件是多少?)

没有必要将所有文档都保存在内存中。 Gensim 的 Word2Vec(和其他算法)几乎总是可以接受任何 Python iterable 对象 - 一个可以一一、重复地迭代其内容的对象,即使它们来自某些其他后端。这通常使用更少的 RAM。

Gensim 项目的负责人发表了一篇关于可迭代对象的有用帖子,可以帮助您将 read_input() 函数调整为可以重复遍历文件的包装类:

https://rare-technologies.com/data-streaming-in-python-generators-iterators-iterables/

另外两个注意事项:

(1) simple_preprocess() 不是特别复杂,您可能想要进行自己的标记化;但是:

(2) 如果您在每次迭代时都重新标记化,特别是如果您的标记化做任何复杂的事情或使用正则表达式,那么您正在对相同的文本进行大量冗余的重新标记化,这很可能是一个你训练的瓶颈。因此,实际上您可能只想使用您的 read_input() 不将所有 rokenized 文档填充到一个列表中,而是将它们写入一个新文件、后标记化、一个文档到一行以及所有标记由单个空格分隔.然后,像 Gensim 的 LineSentence 这样的实用程序类可以提供迭代包装器,用于将几乎完全准备好的文件提供给 Word2Vec