16

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

文档说要初始化模型:

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
{}
4

2 回答 2

14

utf-8句子列表。您还可以从磁盘流式传输数据。

确保它是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)
于 2013-12-03T22:34:08.440 回答
4

就像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)
于 2017-03-31T09:18:06.550 回答