のんびりしているエンジニアの日記

ソフトウェアなどのエンジニア的な何かを書きます。

Gensimを使った自然言語処理

Sponsored Links

皆さんこんにちは
お元気ですか。私は元気です。

今日はGensimを使い、自然言語処理を行います。

Install

sudo pip install gensim

基本的なプロセス

まず、学習処理ですが
基本的にはCorpusを作成する⇒ベクトルに変換する⇒何らかの処理をする(LSI,LDAとか)

Corpus作成

まずは、Corpusを作らないといけません。
要はこの文章の中にどんな単語が含まれているのかを抽出します。
但し、今回は日本語ではなく英語で行います。

公式サイトの例として、以下の例を扱います。

documents = ["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"]

まずは、単語を読みませる為の形式に変換します。

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 documents]

stoplistは含めたくない文字列の一覧です。
これを解析すると、以下のようになります

['human', 'machine', 'interface', 'lab', 'abc', 'computer', 'applications']
['survey', 'user', 'opinion', 'computer', 'system', 'response', 'time']
['eps', 'user', 'interface', 'management', 'system']
['system', 'human', 'system', 'engineering', 'testing', 'eps']
['relation', 'user', 'perceived', 'response', 'time', 'error', 'measurement']
['generation', 'random', 'binary', 'unordered', 'trees']
['intersection', 'graph', 'paths', 'trees']
['graph', 'minors', 'iv', 'widths', 'trees', 'well', 'quasi', 'ordering']
['graph', 'minors', 'survey']

続いてこれらを用いて辞書を構築します。

dictionary = corpora.Dictionary(texts)
print dictionary.token2id

辞書の内容は以下のとおりです。ワードとidが対応しており、
表示順番は順不同になっています。

{u'minors': 30, u'generation': 22, u'testing': 16, u'iv': 29,・・・}

辞書からベクトル表現へ

辞書を使ってBag of Word表現をすることができます。

corpus = [dictionary.doc2bow(text) for text in texts]
print corpus

bag of Keyword表現からtfidfを計算することができます。
計算方法は以下のとおりです。

tfidf = models.TfidfModel(corpus)
print tfidf
corpus_tfidf = tfidf[corpus]

トピックモデル

最後にトピックモデルを紹介します。トピックモデルのアルゴリズムとして
LSIとLDAが用意されています。以下のコードで使うことができます。

lda = models.LdaModel(corpus, id2word=dictionary, num_topics=2)
corpus_lda = lda[corpus_tfidf]

print matutils.corpus2dense(corpus_lda, num_terms=2)