问题描述
我的句子非常多,问题是我无法一次将它们全部加载到内存中,特别是当我标记这些句子并将它们分成单词列表时,我的RAM很快就满了。
但是我找不到任何关于如何用批次训练gensim word2vec的示例,这意味着在每个时期,我想我都必须以某种方式从磁盘加载批次数据,将其标记化并提供给模型,然后卸载它并加载下一批。
当我没有足够的内存来加载所有句子(甚至连其中的20%)时,我如何克服这个问题并训练word2vec模型。
解决方法
您可以按照docs中的建议定义自己的语料库,在这种情况下,语料库的大小基本上无关紧要:
from gensim.test.utils import datapath
from gensim import utils
class MyCorpus(object):
"""An interator that yields sentences (lists of str)."""
def __iter__(self):
corpus_path = datapath('lee_background.cor')
for line in open(corpus_path):
# assume there's one document per line,tokens separated by whitespace
yield utils.simple_preprocess(line)
然后按照以下步骤进行训练:
import gensim.models
sentences = MyCorpus()
model = gensim.models.Word2Vec(sentences=sentences)