mk-toolブログ

エンジニアと家のことをごちゃごちゃと書いてます

【機械学習】gensimのチュートリアルをやってみた(その1)

gensimのチュートリアルをやってみました。
pythonがあまりわからないので、わからない関数があったらそこも触れながら。

チュートリアルは以下です。
radimrehurek.com

このうちの「Corpora and Vector Spaces」をやってみます。

まず、9つの文を配列として用意しています。

from gensim import corpora
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())

pythonのset関数がよくわからないので調べました。

#実行コマンド
spam1 = set('monty python')
spam2 = set('monty python'.split())
spam3 = set(['monty','python',])

spam1
spam2
spam3
#実行結果
{' ', 'h', 'm', 'n', 'o', 'p', 't', 'y'} #setはランダムでしかも文字列の重複がないように格納されるのですね
{'monty', 'python'} #split()で半角空白で文字列を区切り配列としてセット
{'monty', 'python'} #これでも良さそうです

用意した文を配列として格納します(stoplistに登録した文字は除きます)。

texts = [[word for word in document.lower().split() if word not in stoplist] for document in documents]

この書き方は、、、わからん!調べました。
これは「リスト内包表記」というらしいのですが、forの書き方を省略できるみたいです。
例えば、

data = [1, 2, 3, 4, 5]
newData = []
for d in data:
  newData.append(d * 2) #配列dataの中身を2倍にする

という書き方は、

data = [1, 2, 3, 4, 5]
newData = [d * 2 for d in data]

という書き方に置き換えられます。配列へのappendがかなりすっきりかけますね!

さらに、

data = [1, 2, 3, 4, 5]
newData = []
for d in data:
    if d % 2 == 0:
        newData.append(d * 2)

という書き方は

data = [1, 2, 3, 4, 5]
newData = [d * 2 for d in data if d % 2 == 0]

という書き方に置き換えられます。すごい!

お世話になったサイト
www.yoheim.net
openbook4.me


長くなるのでここで一度きります。続きは以下です。
【機械学習】gensimのチュートリアルをやってみた(その2) - gamushiroS’s diary