在gensim Word2Vec模型中匹配单词和向量

pat*_*ick 18 python vector machine-learning gensim word2vec

我有gensim Word2Vec实现为我计算一些单词嵌入.据我所知,一切都非常奇妙; 现在我正在聚集创建的单词vector,希望得到一些语义分组.

下一步,我想看一下每个集群中包含的单词(而不是向量).即如果我有嵌入的向量[x, y, z],我想找出这个向量代表的实际单词.我可以通过调用model.vocab和单词向量来获得单词/ Vocab项目model.syn0.但我找不到这些明确匹配的位置.

这比我想象的要复杂得多,我觉得我可能会错过这种明显的做法.任何帮助表示赞赏!

问题:

将单词与嵌入向量相匹配Word2Vec ()- 如何进行?

我的方法:

在创建模型(下面的代码*)之后,我现在想要将分配给每个单词的索引(在build_vocab()阶段期间)与输出的向量矩阵相匹配model.syn0.从而

for i in range (0, newmod.syn0.shape[0]): #iterate over all words in model
    print i
    word= [k for k in newmod.vocab if newmod.vocab[k].__dict__['index']==i] #get the word out of the internal dicationary by its index
    wordvector= newmod.syn0[i] #get the vector with the corresponding index
    print wordvector == newmod[word] #testing: compare result of looking up the word in the model -- this prints True
Run Code Online (Sandbox Code Playgroud)
  • 有没有更好的方法来做到这一点,例如将矢量输入模型以匹配单词?

  • 这甚至能让我得到正确的结果吗?

*我创建单词向量的代码:

model = Word2Vec(size=1000, min_count=5, workers=4, sg=1)

model.build_vocab(sentencefeeder(folderlist)) #sentencefeeder puts out sentences as lists of strings

model.save("newmodel")
Run Code Online (Sandbox Code Playgroud)

我发现这个问题很相似,但还没有真正得到解答.

Arc*_*yno 10

我一直在寻找syn0矩阵和词汇表之间的映射...这里是答案:使用model.index2word它只是正确顺序的单词列表!

这不在官方文档中(为什么?)但它可以直接在源代码中找到:https://github.com/RaRe-Technologies/gensim/blob/3b9bb59dac0d55a1cd6ca8f984cead38b9cb0860/gensim/models/word2vec.py#L441


bpa*_*hev 5

如果您要做的只是将一个单词映射到vector,则可以简单地使用[]运算符,例如model["hello"]将为您提供与hello相对应的矢量。

如果您需要从向量中恢复单词,则可以按照您的建议遍历向量列表并检查是否匹配。但是,这效率低下,而且不是pythonic。一个方便的解决方案是使用similar_by_vectorword2vec模型的方法,如下所示:

import gensim

documents = [['human', 'interface', 'computer'],
 ['survey', 'user', 'computer', 'system', 'response', 'time'],
 ['eps', 'user', 'interface', 'system'],
 ['system', 'human', 'system', 'eps'],
 ['user', 'response', 'time'],
 ['trees'],
 ['graph', 'trees'],
 ['graph', 'minors', 'trees'],
 ['graph', 'minors', 'survey']]

model = gensim.models.Word2Vec(documents, min_count=1)
print model.similar_by_vector(model["survey"], topn=1)
Run Code Online (Sandbox Code Playgroud)

输出:

[('survey', 1.0000001192092896)]
Run Code Online (Sandbox Code Playgroud)

其中的数字代表相似度。

但是,该方法仍然效率低下,因为它仍然必须扫描所有单词向量以搜索最相似的单词向量。解决问题的最佳方法是找到一种在聚类过程中跟踪向量的方法,从而不必依赖昂贵的反向映射。


pat*_*ick 5

所以我找到了一种简单的方法来做到这一点,nmodel模型的名称在哪里.

#zip the two lists containing vectors and words
zipped = zip(nmodel.wv.index2word, nmodel.wv.syn0)

#the resulting list contains `(word, wordvector)` tuples. We can extract the entry for any `word` or `vector` (replace with the word/vector you're looking for) using a list comprehension:
wordresult = [i for i in zipped if i[0] == word]
vecresult = [i for i in zipped if i[1] == vector]
Run Code Online (Sandbox Code Playgroud)

这是基于gensim代码.对于旧版本的gensim,您可能需要删除wv模型之后的版本.