前提・実現したいこと
TF-IDFを使ってFAQに回答するという記事を読みながら実装を進めています。
TF-IDF値が高い順に出力を得ることを実現したいです。
発生している問題・エラーメッセージ
以下のコードのコメントアウトされている部分のvectorizer.vocabulary_.items()が何を指しているのか理解できません。何を指しているのか教えていただきたいです。
検索でもこの部分を説明したものは出てきませんでした。
#for k,v in vectorizer.vocabulary_.items(): # print(k, v)
該当のソースコード
from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity import numpy as np import MeCab import argparse parser = argparse.ArgumentParser(description="convert csv") parser.add_argument("input", type=str, help="faq tsv file") parser.add_argument("--dictionary", "-d", type=str, help="mecab dictionary") parser.add_argument("--stop_words", "-s", type=str, help="stop words list") args = parser.parse_args() mecab = MeCab.Tagger("-Owakati" + ("" if not args.dictionary else " -d " + args.dictionary)) questions = [] answers = [] for line in open(args.input, "r", encoding="utf-8"): cols = line.strip().split('\t') questions.append(mecab.parse(cols[0]).strip()) answers.append(cols[1]) stop_words = [] if args.stop_words: for line in open(args.stop_words, "r", encoding="utf-8"): stop_words.append(line.strip()) vectorizer = TfidfVectorizer(token_pattern="(?u)\b\w+\b", stop_words=stop_words) vecs = vectorizer.fit_transform(questions) #for k,v in vectorizer.vocabulary_.items(): # print(k, v) while True: line = input("> ") if not line: break index = np.argmax(cosine_similarity(vectorizer.transform([mecab.parse(line)]), vecs)) print(questions[index]) print() print(answers[index]) print()
試したこと
類似するコードが載っていた記事を使って、vectorizer.vocabulary_.items()の振る舞いを確認しようとしましたが、
sortを行うとあいうえお順に出力され、sortをしないとただ分かち書きされた単語が順番に出力されるだけだったので、TF-IDF値が高い順に並べることはできないのでしょうか。
python
1import numpy as np 2from sklearn.feature_extraction.text import TfidfVectorizer 3 4np.set_printoptions(precision=2) 5 6docs = np.array([ 7 'みぞれ とは 何ですか?', # 文書1 8 '台風 と ハリケーン の 違いは?', # 文書2 9 '異常気象 に ついて' 10 ]) 11 12vectorizer = TfidfVectorizer(use_idf=True) 13vecs = vectorizer.fit_transform(docs) 14 15print (vecs.toarray()) 16for k,v in sorted(vectorizer.vocabulary_.items(), key=lambda x:x[1]): 17 print (k)
[[ 0. 0.58 0.58 0. 0.58 0. 0. 0. ] [ 0. 0. 0. 0.58 0. 0.58 0. 0.58] [ 0.71 0. 0. 0. 0. 0. 0.71 0. ]] ついて とは みぞれ ハリケーン 何ですか 台風 異常気象 違いは
補足情報(FW/ツールのバージョンなど)
Python 3.6.0 :: Anaconda 4.3.0
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2018/09/05 22:28
2018/09/05 22:31