我在用自己的词汇训练word2vec时遇到错误。我也没理解为什么会这样。
代码:
from gensim.models import word2vec
import logging
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
sentences = word2vec.LineSentence('test_data')
model = word2vec.Word2Vec(sentences, size=20)
model.build_vocab(sentences,update=True)
model.train(sentences)
print model.most_similar(['course'])
它会抛出错误
2017-08-27 16:50:04,590 : INFO : precomputing L2-norms of word weight vectors
Traceback (most recent call last):
File "tryword2vec.py", line 23, in <module>
print model.most_similar(['course'])
File "/usr/local/lib/python2.7/dist-packages/gensim/models/word2vec.py", line 1285, in most_similar
return self.wv.most_similar(positive, negative, topn, restrict_vocab, indexer)
File "/usr/local/lib/python2.7/dist-packages/gensim/models/keyedvectors.py", line 97, in most_similar
raise KeyError("word '%s' not in vocabulary" % word)
KeyError: "word 'course' not in vocabulary"
test_data包含:
Engg学士学位课程。 M.Tech是一门课程。我是一门课程。 B.Tech是一门课程。文学学士是一门课程。时装设计是一个 课程。多媒体是一门课程。机械工程是一门课程。电脑 科学是一门课程。电子是一种资源。工程学是一门课程。 MBA是一门课程。 BBA是一门课程。
感谢任何帮助?
答案 0 :(得分:1)
您没有收到错误的原因是因为单词 course 不在词汇表中。相反,现在这个词是当然。
课程结束时有一段&#34;。&#34; 。
检查你的词汇量
model.wv.vocab
{u'a': <gensim.models.keyedvectors.Vocab at 0x7fe086c461d0>,
u'course.': <gensim.models.keyedvectors.Vocab at 0x7fe0b4704f90>,
u'is': <gensim.models.keyedvectors.Vocab at 0x7fe086ba0d10>}
并隐藏 api 键。