次のページで公開されているプログラムを使い, 英語の文書(ドキュメント)についての,単語の切り出し,ストップワードの除去,頻出単語の抽出とIDの付与,Bag of Words の作成,LSI,LDA の作成を行う.
https://radimrehurek.com/gensim/auto_examples/core/run_core_concepts.html#core-concepts-document
【サイト内の関連ページ】
謝辞:このページで使用しているソフトウェア類の作者に感謝します.
Windows での Python 3.10,関連パッケージ,Python 開発環境のインストール: 別ページ »で説明
【サイト内の関連ページ】
Python のまとめ: 別ページ »にまとめ
【関連する外部ページ】
Python の公式ページ: https://www.python.org/
Windows では,コマンドプロン プトを管理者として実行する.
次のコマンドを実行.
python -m pip install gensim
sudo pip3 install gensim
Python 処理系として,Jupyter Qt Console を起動
jupyter qtconsole
Python プログラムを動かして,結果をビジュアルに見たい.
ここでは,Jupyter Qt Console を使っている. 他の開発環境(Spyder,PyCharm,PyScripter
ここから先は,Jupyter Qt Console の画面で説明する.
文書(ドキュメントの集まり)をコーパスという.
text_corpus = [ "Human machine interface for lab abc computer applications", "A survey of user opinion of computer system response time", "The EPS user interface management system", "System and human system engineering testing of EPS", "Relation of user perceived response time to error measurement", "The generation of random binary unordered trees", "The intersection graph of paths in trees", "Graph minors IV Widths of trees and well quasi ordering", "Graph minors A survey", ] print(text_corpus)
英語の文書から,単語を切り出す.切り出しには split() を用いる. このとき,次のことを行う.
stoplist = set('for a of the and to in'.split(' ')) texts = [[word for word in document.lower().split() if word not in stoplist] for document in text_corpus] print(texts)
単語の出現数の数え上げは次で行う.
from collections import defaultdict frequency = defaultdict(int) for text in texts: for token in text: frequency[token] += 1 print(frequency)
単語の切り出し結果について,頻出する単語(出現回数 2回以上のみ)を残す.
processed_corpus = [[token for token in text if frequency[token] > 1] for text in texts] print(processed_corpus)
単語に,整数の ID を割り振る.
from gensim import corpora dictionary = corpora.Dictionary(processed_corpus) print(dictionary.token2id)
Bag of Words は,単語IDと出現回数のペアを文書(ドキュメント)ごとに作ったもの.
bow_corpus = [dictionary.doc2bow(text) for text in processed_corpus] print(bow_corpus)
先ほど作成した bow_corpus (Bag of Words) をTF/IDF値に変換する.
gensim の次のページで公開されている Python プログラムを使用
from gensim import models tfidf = models.TfidfModel(bow_corpus) corpus_tfidf = tfidf[bow_corpus] for doc in corpus_tfidf: print(doc)
先ほど作成した corpus_tfidf (TF/IDF コーパス) をLatent Semantic Indexing に変換する. ここでは, トピックス数を 2 に設定.
gensim の次のページで公開されている Python プログラムを使用
N = 2 lsi_model = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=N) corpus_lsi = lsi_model[corpus_tfidf] for doc, as_text in zip(corpus_lsi, text_corpus): print(doc, as_text)
先ほど作成した bow_corpus (Bag of Words) をLatent Dirichlet Allocation (LDA) に変換する. ここでは, トピックス数を 100 に設定.
gensim の次のページで公開されている Python プログラムを使用
N = 100 lda_model = models.LdaModel(bow_corpus, id2word=dictionary, num_topics=N) corpus_lda = lda_model[bow_corpus] for doc, as_text in zip(corpus_lda, text_corpus): print(doc, as_text)