python3でgihyoの機械学習はじめようのナイーブベイズをやる
gihyoのナイーブベイズはpython2.6なので、python3でやり直してみる。
とりあえず、python3環境を用意
beautifulsoupはanaconda だと元々入っているはず。。。
なければ
pip install beautifulsoup4
とする。
morphorogical.pyのimportを
import urllib
import urllib.parse
import urllib.request
from bs4 import BeautifulSoup
に変更。
urllibまわりの呼び出しを
sentence = sentence.encode("utf-8")
params = urllib.parse.urlencode({'appid':appid, 'results':results, 'filter':filter,'sentence':sentence}).encode('utf-8')
results = urllib.request.urlopen(pageurl, params)
に変更すればOK
あとは、maxintが廃止されたので
max = -sys.maxsizeに
classifierの
prob < maxは誤植だと思うので
prob > maxにする
print まわりは
words = 'ヴァンロッサム氏によって開発されました.'
print ('%s => 推定カテゴリ: %s' % (words ,nb.classifier(words)))
という感じに変更すれば、動きます。
お疲れ様でした。
あと、若干謎なのが、len(self.vacabularies)を足していることなんですよね。
prob = (self.incategory(word, cat) + 1.0) / (sum(self.wordcount[cat].values()) + len(self.vocabularies) * 1.0)
指定wordの数 / cat内の全単語数でいいと思うんですが...