wikipediaを利用して | python3Xのブログ

python3Xのブログ

ここでは40代、50代の方が日々の生活で役に立つ情報や私の趣味であるプログラム、Excelや科学に関する内容で投稿する予定です。

下記URLお内容をそのまま(Windows環境でないのでそのままという訳にはいきませんでしたが)

実行させて頂きました。(赤い文字部分が変更や追加をしなければならなかった部分です)

URL:http://hironsan.hatenablog.com/entry/learning-character-embeddings

 

pythonで日本語の文字分散表現を学習するにあたって

必ずと言っていいほどでてくるのがMeCabです

ただ、残念なことに

『WindowsにMeCabをインストールするのは容易である』

とは、とても言えません

数えきれないほどの書き換えや、コンパイル済み(目的)のMeCabファイル群、

pythonでMeCabを利用するファイル群・・・

# 単語単位で区切られているja.text8を文字単位+空白で区切る
# 但し、cp932のencode、decodeエラーを避けなければなりません
# そのため(encoding='utf8')を行っています

# 前回は(replaceのあとencode)でした
f =  open('ja.text8', 'r' , encoding='utf8')
text = f.read()
chars = [c for c in text if c != ' ']
f =  open('ja.char8', 'w', encoding='utf8')
f.write(' '.join(chars))          # 空白で区切られたja.char8が作られる
 
この後は訓練word2vecを使っての訓練に入ります
import logging
from gensim.models import word2vec
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
 
sentences = word2vec.Text8Corpus('ja.char8')
model = word2vec.Word2Vec(sentences, size=50, window=50, workers=4)
==================================================================================================
2018-08-01 10:14:59,568 : INFO : EPOCH 5 - PROGRESS: at 94.02% examples, 193245 words/s, in_qsize 7, out_qsize 0
2018-08-01 10:15:00,600 : INFO : EPOCH 5 - PROGRESS: at 94.97% examples, 193241 words/s, in_qsize 7, out_qsize 0
2018-08-01 10:15:01,639 : INFO : EPOCH 5 - PROGRESS: at 95.91% examples, 193241 words/s, in_qsize 8, out_qsize 0
2018-08-01 10:15:02,638 : INFO : EPOCH 5 - PROGRESS: at 96.82% examples, 193242 words/s, in_qsize 7, out_qsize 0
2018-08-01 10:15:03,668 : INFO : EPOCH 5 - PROGRESS: at 97.80% examples, 193329 words/s, in_qsize 7, out_qsize 0
2018-08-01 10:15:04,702 : INFO : EPOCH 5 - PROGRESS: at 98.82% examples, 193469 words/s, in_qsize 7, out_qsize 0
2018-08-01 10:15:05,750 : INFO : EPOCH 5 - PROGRESS: at 99.56% examples, 193065 words/s, in_qsize 7, out_qsize 0
では確認してみます
print(model.most_similar(['膝']))
[('肘', 0.8124829530715942), ('腱', 0.7912985682487488), ('靭', 0.7820127010345459), ('蹴', 0.7669538259506226), ('肩', 0.7345666289329529), ('腰', 0.7200089693069458), ('腿', 0.714104175567627), ('靱', 0.7117882966995239), ('腕', 0.7027574777603149), ('痛', 0.701032817363739)]
 
print(model.most_similar(['猫']))
[('犬', 0.7342474460601807), ('裸', 0.6774367094039917), ('猿', 0.6499794721603394), ('鳥', 0.6463407874107361), ('昔', 0.639254093170166), ('髪', 0.6287513971328735), ('鮎', 0.628650963306427), ('匂', 0.6264489889144897), ('扮', 0.6136317253112793), ('ぬ', 0.6079254746437073)]