Gensimの使い方 ~Modelの作り方編~

主に見るべきところ
http://radimrehurek.com/gensim/tut2.html

Tf-idモデルとLSIモデルの構築の仕方が書いてある。

ページを見る限りはモデルの構築方法は

>> models.Tfidf(対象コーパス)

でいいみたい。
ちなみにここでの対象コーパスはbag-of-wordで(素性No,頻度)のタプルのリストになっている(はず)
一応、表示しておくと、

>> for doc in corpus:
... print doc

[(0, 1.0), (1, 1.0), (2, 1.0)]
[(0, 1.0), (3, 1.0), (4, 1.0), (5, 1.0), (6, 1.0), (7, 1.0)]
[(2, 1.0), (5, 1.0), (7, 1.0), (8, 1.0)]
[(1, 1.0), (5, 2.0), (8, 1.0)]
[(3, 1.0), (6, 1.0), (7, 1.0)]
[(9, 1.0)]
[(9, 1.0), (10, 1.0)]
[(9, 1.0), (10, 1.0), (11, 1.0)]
[(4, 1.0), (10, 1.0), (11, 1.0)]

>>> print corpus
MmCorpus(9 documents, 12 features, 28 non-zero entries)

となっている。

あと、LSIモデルの構築の方法も書いてあるが、
>> lsi = models.LsiModel(corpus_tfidf, id2word=dictionary, num_topics=2) # initialize an LSI transformation

と、tfidでのコーパスを元にすることになっている。
ここがよくわからない。bag-of-wordのコーパスから直接モデルを構築はできないのだろうか??

そこで、試してみた。元コーパスをbag-of-wordsにしてみる。
>> lsi = models.LsiModel(corpus, id2word=dictionary, num_topics=2)

num_topics=2は圧縮する次元のことを指しているらしい。なので、ここでは2次元に圧縮されている。

>> lsi.print_topics(2)

['-0.644*"system" + -0.404*"user" + -0.301*"eps" + -0.265*"response" + -0.265*"time" + -0.240*"computer" + -0.221*"human" + -0.206*"survey" + -0.198*"interface" + -0.036*"graph"', '-0.623*"graph" + -0.490*"trees" + -0.451*"minors" + -0.274*"survey" + 0.167*"system" + 0.141*"eps" + 0.113*"human" + -0.107*"time" + -0.107*"response" + 0.072*"interface"']

本来なら、チュートリアルの解説によれば

>>> lsi.print_topics(2)

topic #0(1.594): -0.703*"trees" + -0.538*"graph" + -0.402*"minors" + -0.187*"survey" + -0.061*"system" + -0.060*"response" + -0.060*"time" + -0.058*"user" + -0.049*"computer" + -0.035*"interface"
topic #1(1.476): -0.460*"system" + -0.373*"user" + -0.332*"eps" + -0.328*"interface" + -0.320*"response" + -0.320*"time" + -0.293*"computer" + -0.280*"human" + -0.171*"survey" + 0.161*"trees"


(なぜか表示の型も違うのも気になるが..)まったく違う数値が表示される。ということは、やはり元コーパスはbag-of-wordsではいけないようだ。
LSIモデルの元コーパスはtf-idfコーパスでないといけないよっと。

と、思ってたら、ちゃんとページの一番下に説明書きがありました。

>>> model = tfidfmodel.TfidfModel(bow_corpus, normalize=True)

>>> model = lsimodel.LsiModel(tfidf_corpus, id2word=dictionary, num_topics=300)

ただ、上の通りにコマンドうっても「そんなのねーよ」と返ってくるので、
>> models.

と続けるのが正解