word2vecで名詞のみかつリスト化された文章から分散表現取得したいのですが、
python3
1from pymongo import MongoClient 2from bs4 import BeautifulSoup 3import MeCab 4from gensim.models import word2vec 5mecab = MeCab.Tagger ('/usr/local/lib/mecab/dic/mecab-ipadic-neologd') 6def main(): 7 recipes = [] 8 client = MongoClient('localhost', 27017) 9 db = client.html.cookpad_html 10 collection = db.test_collection 11 htmls = list(db.find().limit(1)) 12 recipes = [] 13 for num, html in enumerate(htmls): 14 soup = BeautifulSoup(html["html"], 'lxml') 15 for steps in soup.find_all(attrs={"class": "step_text"}): 16 node = mecab.parseToNode(steps.get_text()) 17 while node: 18 feature = node.feature.split(",") 19 if feature[0] == "名詞" and feature[1] == "一般": 20 word = node.feature.split(",")[6] 21 recipes.append(node.surface if word == "*" else word) 22 node = node.next 23 recipes = list(set(recipes)) 24 print(recipes) 25 model = word2vec.Word2Vec(recipes, size=200,min_count=1) 26 out = model.wv.most_similar ( positive=['ハチミツ'] , negative=None , topn=10 , indexer=None ) 27 for x in out: 28 print (x[0],x[1]) 29if __name__ == '__main__':
['卵白', '卵黄', '生地', '玉子', 'ツノ', 'ハチミツ', 'ボウル', 'オリーブ油', 'レンジ', 'ヨーグルト', 'おから', 'w', 'レモン', 'ラップ', 'マグカップ']
結果はこう出るんですが、エラーコードがこのように出ます。
python3
1--------------------------------------------------------------------------- 2KeyError Traceback (most recent call last) 3<ipython-input-2-c8877629ece6> in <module> 4 28 print (x[0],x[1]) 5 29 if __name__ == '__main__': 6---> 30 main() 7 8<ipython-input-2-c8877629ece6> in main() 9 24 print(recipes) 10 25 model = word2vec.Word2Vec(recipes, size=200,min_count=1) 11---> 26 out = model.wv.most_similar ( positive=['ハチミツ'] , negative=None , topn=10 , indexer=None ) 12 27 for x in out: 13 28 print (x[0],x[1]) 14 15~/anaconda3/lib/python3.7/site-packages/gensim/models/keyedvectors.py in most_similar(self, positive, negative, topn, restrict_vocab, indexer) 16 551 mean.append(weight * word) 17 552 else: 18--> 553 mean.append(weight * self.word_vec(word, use_norm=True)) 19 554 if word in self.vocab: 20 555 all_words.add(self.vocab[word].index) 21 22~/anaconda3/lib/python3.7/site-packages/gensim/models/keyedvectors.py in word_vec(self, word, use_norm) 23 466 return result 24 467 else: 25--> 468 raise KeyError("word '%s' not in vocabulary" % word) 26 469 27 470 def get_vector(self, word): 28 29KeyError: "word 'ハチミツ' not in vocabulary" 30
ハチミツ以外の単語でも調べたのですが、なぜか出来ません。
以前同じようなことを聞いたら、
*Word2Vecモデルの初期化時にはlist of lists of tokensを渡す必要がある
*学習データに含まれない単語に対しては距離の計算ができない。
*word2vecのmostsimilarは与えた単語をベクトル化して、最も近似するベクトルを有する単語を返す関数
と言われたのですが、どのように直せばいいのか分かりません、誰か教えて下さい。
あなたの回答
tips
プレビュー