【问题标题】:How to load sentences into Python gensim?如何将句子加载到 Python gensim 中?
【发布时间】:2013-12-03 22:25:56
【问题描述】:

我正在尝试在 Python 中使用 gensim 自然语言处理库中的 word2vec 模块。

文档说要初始化模型:

from gensim.models import word2vec
model = Word2Vec(sentences, size=100, window=5, min_count=5, workers=4)

gensim 期望输入句子的格式是什么?我有原始文本

"the quick brown fox jumps over the lazy dogs"
"Then a cop quizzed Mick Jagger's ex-wives briefly."
etc.

我需要向word2fec 发布什么额外处理?


更新:这是我尝试过的。当它加载句子时,我什么也得不到。

>>> sentences = ['the quick brown fox jumps over the lazy dogs',
             "Then a cop quizzed Mick Jagger's ex-wives briefly."]
>>> x = word2vec.Word2Vec()
>>> x.build_vocab([s.encode('utf-8').split( ) for s in sentences])
>>> x.vocab
{}

【问题讨论】:

    标签: python nlp gensim


    【解决方案1】:

    A list of utf-8 sentences。您还可以从磁盘流式传输数据。

    确保它是utf-8,然后拆分它:

    sentences = [ "the quick brown fox jumps over the lazy dogs",
    "Then a cop quizzed Mick Jagger's ex-wives briefly." ]
    word2vec.Word2Vec([s.encode('utf-8').split() for s in sentences], size=100, window=5, min_count=5, workers=4)
    

    【讨论】:

    • 实际上,句子必须是单词列表,而不是字符串,即s.encode('utf-8').split()
    • 哎呀抱歉。更新。谢谢
    • RuntimeError: you must first build vocabulary before training the model
    • 启用日志记录并观察其内容。你的答案就在于此。剧透:min_count=5.
    • @alKid 很好的答案,但它是句子的序列(可迭代)=不一定是列表。当sentences 大于 RAM(即从磁盘流式传输)时,这会产生很大的不同。
    【解决方案2】:

    就像alKid 指出的那样,改成utf-8

    谈谈您可能需要担心的另外两件事。

    1. 输入太大,您正在从文件中加载它。
    2. 从句子中删除停用词。

    您可以执行以下操作,而不是将大列表加载到内存中:

    import nltk, gensim
    class FileToSent(object):    
        def __init__(self, filename):
            self.filename = filename
            self.stop = set(nltk.corpus.stopwords.words('english'))
    
        def __iter__(self):
            for line in open(self.filename, 'r'):
            ll = [i for i in unicode(line, 'utf-8').lower().split() if i not in self.stop]
            yield ll
    

    然后,

    sentences = FileToSent('sentence_file.txt')
    model = gensim.models.Word2Vec(sentences=sentences, window=5, min_count=5, workers=4, hs=1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-02-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多