【问题标题】:Python: gensim: RuntimeError: you must first build vocabulary before training the modelPython: gensim: RuntimeError: 在训练模型之前必须先建立词汇表
【发布时间】:2016-03-03 13:42:00
【问题描述】:

我知道已经有人问过这个问题,但我仍然无法找到解决方案。

我想在自定义数据集上使用 gensim 的 word2vec,但现在我仍在弄清楚数据集必须采用什么格式。我查看了this post,其中输入基本上是一个列表列表(一个包含其他列表的大列表,这些列表是来自 NLTK Brown 语料库的标记化句子)。所以我认为这是我必须用于命令word2vec.Word2Vec() 的输入格式。但是,它不适用于我的小测试集,我不明白为什么。

我尝试过的:

成功了

from gensim.models import word2vec
from nltk.corpus import brown
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

brown_vecs = word2vec.Word2Vec(brown.sents())

这不起作用

sentences = [ "the quick brown fox jumps over the lazy dogs","yoyoyo you go home now to sleep"]
vocab = [s.encode('utf-8').split() for s in sentences]
voc_vec = word2vec.Word2Vec(vocab)

我不明白为什么它不适用于“模拟”数据,即使它与布朗语料库中的句子具有相同的数据结构:

词汇

[['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dogs'], ['yoyoyo', 'you', 'go', 'home', 'now', 'to', 'sleep']]

brown.sents():(它的开头)

[['The', 'Fulton', 'County', 'Grand', 'Jury', 'said', 'Friday', 'an', 'investigation', 'of', "Atlanta's", 'recent', 'primary', 'election', 'produced', '``', 'no', 'evidence', "''", 'that', 'any', 'irregularities', 'took', 'place', '.'], ['The', 'jury', 'further', 'said', 'in', 'term-end', 'presentments', 'that', 'the', 'City', 'Executive', 'Committee', ',', 'which', 'had', 'over-all', 'charge', 'of', 'the', 'election', ',', '``', 'deserves', 'the', 'praise', 'and', 'thanks', 'of', 'the', 'City', 'of', 'Atlanta', "''", 'for', 'the', 'manner', 'in', 'which', 'the', 'election', 'was', 'conducted', '.'], ...]

谁能告诉我我做错了什么?

【问题讨论】:

    标签: python gensim word2vec


    【解决方案1】:

    gensim 的 Word2Vec 的输入可以是句子列表或单词列表或句子列表。

    例如

    1. sentences = ['I love ice-cream', 'he loves ice-cream', 'you love ice cream']
    2. words = ['i','love','ice - cream', 'like', 'ice-cream']
    3. sentences = [['i love ice-cream'], ['he loves ice-cream'], ['you love ice cream']]
    

    在训练前建立词汇

    model.build_vocab(sentences, update=False)
    

    just check out the link for detailed info

    【讨论】:

      【解决方案2】:

      gensim 的 Word2Vec 中的默认 min_count 设置为 5。如果您的 vocab 中没有频率大于 4 的单词,您的 vocab 将为空,因此出现错误。试试

      voc_vec = word2vec.Word2Vec(vocab, min_count=1)
      

      【讨论】:

      • 此外,如果您的数据来自迭代器,请确保它尚未被使用。
      • +1 来自文档:min_count:(默认 5)训练模型时要考虑的最小字数;出现次数少于此计数的单词将被忽略
      猜你喜欢
      • 1970-01-01
      • 2020-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-10-27
      相关资源
      最近更新 更多