【发布时间】:2019-09-25 18:27:08
【问题描述】:
我目前正在使用 python,我使用我提供的句子训练 Word2Vec 模型。然后,我保存并加载模型以获取用于训练模型的句子中每个单词的词嵌入。但是,我收到以下错误。
KeyError:“单词 'n1985_chicago_bears' 不在词汇表中”
然而,训练期间提供的句子之一如下。
sportsteam n1985_chicago_bears teamplaysincity city chicago
因此,我想知道为什么词汇表中缺少一些单词,尽管我接受了该句子语料库中的这些单词的训练。
在自己的语料库上训练 word2vec 模型
import nltk
import numpy as np
from termcolor import colored
from gensim.models import Word2Vec
from gensim.models import KeyedVectors
from sklearn.decomposition import PCA
#PREPARING DATA
fname = '../data/sentences.txt'
with open(fname) as f:
content = f.readlines()
# remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
#TOKENIZING SENTENCES
sentences = []
for x in content:
nltk_tokens = nltk.word_tokenize(x)
sentences.append(nltk_tokens)
#TRAINING THE WORD2VEC MODEL
model = Word2Vec(sentences)
words = list(model.wv.vocab)
model.wv.save_word2vec_format('model.bin')
sentence.txt 中的示例句子
sportsteam hawks teamplaysincity city atlanta
stadiumoreventvenue honda_center stadiumlocatedincity city anaheim
sportsteam ducks teamplaysincity city anaheim
sportsteam n1985_chicago_bears teamplaysincity city chicago
stadiumoreventvenue philips_arena stadiumlocatedincity city atlanta
stadiumoreventvenue united_center stadiumlocatedincity city chicago
...
sentences.txt 文件中有 1860 行这样的行,每行正好包含 5 个单词且没有停用词。
保存模型后,我尝试从与保存的model.bin 相同的目录中的不同python文件加载它,如下所示。
加载保存的model.bin
import nltk
import numpy as np
from gensim import models
w = models.KeyedVectors.load_word2vec_format('model.bin', binary=True)
print(w['n1985_chicago_bears'])
但是,我最终得到以下错误
KeyError: "word 'n1985_chicago_bears' not in vocabulary"
有没有办法使用相同的方法为训练好的句子语料库中的每个单词获取单词嵌入?
在这方面的任何建议将不胜感激。
【问题讨论】:
标签: python tensorflow nltk gensim word2vec