首页 > 解决方案 > 使用 word2vec 和 gensim 查找相似词,抛出错误

问题描述

我试图找到与我给出代码的单词相似的单词。但不知何故,一切都很好,直到最后,它说这个词不存在。有人可以帮助我吗?

from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec

glove_file = datapath('/content/drive/MyDrive/Colab Notebooks/glove.6B.300d.txt')
tmp_file = get_tmpfile('/content/drive/MyDrive/Colab Notebooks/word2vec-glove.6B.300d.txt')

_ = glove2word2vec(glove_file, tmp_file)

model = KeyedVectors.load_word2vec_format(tmp_file)

model.most_similar(positive=["new"], topn=10)
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-32-0752cfe838d7> in <module>()
     10 model = KeyedVectors.load_word2vec_format(tmp_file)
     11 
---> 12 model.most_similar(positive=["new"], topn=10)

1 frames
/usr/local/lib/python3.7/dist-packages/gensim/models/keyedvectors.py in word_vec(self, word, use_norm)
    450             return result
    451         else:
--> 452             raise KeyError("word '%s' not in vocabulary" % word)
    453 
    454     def get_vector(self, word):

KeyError: "word 'new' not in vocabulary"

标签: pythongoogle-colaboratorygensimword2vecdrive

解决方案


如果你收到一个错误,KeyError: "word 'new' not in vocabulary"那么这个词'new'可能不在模型的词汇表中——即使你期望/打算这样做。

您是否检查了源 GLoVe 文件,/content/drive/MyDrive/Colab Notebooks/glove.6B.300d.txt以确认它具有预期的长度/内容?

您检查过输出文本 word2vec 格式文件/content/drive/MyDrive/Colab Notebooks/word2vec-glove.6B.300d.txt吗?

您是否检查过model,一旦加载, ( ) 内的字数是否符合预期len(model),或者它的第一个单词 ( model.index_to_key[20]) 是否正确?

这些检查可能会显示一些比您正在点击的更基本的问题KeyError-most_similar()因此重复 GLoVe 矢量下载/转换/加载并确保每个步骤都成功且没有错误可能会解决问题。

另请注意:

从 Gensim 版本 4.0 (2021) 开始,该glove2word2vec()函数/脚本现已弃用。如果您使用它,您应该会看到一条警告消息:

KeyedVectors.load_word2vec_format(.., binary=False, no_header=True) 加载 GLoVE 文本向量。

因此,您可以跳过显式转换,而直接使用它:

glove_vecs = KeyedVectors.load_word2vec_format(glove_file, binary=False, no_header=True)

(此读取将需要一个额外的初始通道,以计算包含的单词数,因此如果您要重复此加载很多,您可能仍希望将其重新保存glove_vecs到一个新的单独文件,.save_word2vec_format()如果加载-速度是一个问题。)


推荐阅读