首页 > 解决方案 > 训练 Fasttext 模型

问题描述

我想使用“gensim”库在 Python 中训练一个 Fasttext 模型。首先,我应该将每个句子标记为其单词,从而将每个句子转换为单词列表。然后,应将此列表附加到最终列表中。因此,最后,我将有一个包含所有标记化句子的嵌套列表:

word_punctuation_tokenizer = nltk.WordPunctTokenizer()
word_tokenized_corpus = []
for line in open('sentences.txt'):
   new = line.strip()
   new = word_punctuation_tokenizer.tokenize(new)
   if len(new) != 0:
       word_tokenized_corpus.append(new)

然后,模型应该如下构建:

embedding_size = 60
window_size = 40
min_word = 5
down_sampling = 1e-2
ft_model = FastText(word_tokenized_corpus,
                  size=embedding_size,
                  window=window_size,
                  min_count=min_word,
                  sample=down_sampling,
                  sg=1,
                  iter=100)

但是“word_tokenized_corpus”的句子数量很大,程序处理不了。是否可以通过将每个标记化的句子一个一个地赋予模型来训练模型,例如:?

 for line in open('sentences.txt'):
  new = line.strip()
  new = word_punctuation_tokenizer.tokenize(new)
  if len(new) != 0:
   ft_model = FastText(new,
              size=embedding_size,
              window=window_size,
              min_count=min_word,
              sample=down_sampling,
              sg=1,
              iter=100)

这对最终结果有什么影响吗?是否可以在不必构建如此大的列表并将其保存在内存中的情况下训练模型?

标签: pythongensimfasttext

解决方案


由于数据量很大,最好将文本文件转换成COR文件。然后,按以下方式阅读:

from gensim.test.utils import datapath
corpus_file = datapath('sentences.cor')

至于下一步:

model = FastText(size=embedding_size,
                  window=window_size,
                  min_count=min_word,
                  sample=down_sampling,
                  sg=1,
                  iter=100)
model.build_vocab(corpus_file=corpus_file)
total_words = model.corpus_total_words
model.train(corpus_file=corpus_file, total_words=total_words, epochs=5)

推荐阅读