ベイズ識別器、通称ベイジアンフィルタを使って、あるウェブページの内容と似たウェブページを探してみたときのメモ。ベイズ識別器となる Python モジュールは http://divmod.org/trac/wiki/DivmodReverend です。Reverend に渡す日本語データは「わかち書き」しないといけないので mecab を使った。
ソースコード
1 import sys
2 import os
3 import glob
4
5 from reverend.thomas import Bayes
6
7 # 類似ページを発見したいHTMLファイル
8 inputfile = os.path.abspath(sys.argv[1])
9 # 判定用のデータとなるHTMLファイルが格納されたディレクトリ (Unix shell-style wildcards)
10 sourcefiles = "/path/to/*.html"
11
12 # 比較元のHTMLをわかち書きする
13 cmd = "mecab -Owakati %s" % inputfile
14 sysin,sysout = os.popen2(cmd)
15 source = sysout.read()
16
17 # 識別器のオブジェクト
18 guesser = Bayes()
19
20 # 比較対象のデータを学習する
21 for htmlfile in glob.glob(sourcefiles):
22 if htmlfile == inputfile or htmlfile.endswith('index.html'):
23 continue
24 cmd = "mecab -Owakati %s" % htmlfile
25 sysin,sysout = os.popen2(cmd)
26 guesser.train(htmlfile, sysout.read())
27
28 # 類似の計算
29 for name,rate in guesser.guess(source):
30 print "%.2f\t%s" % (rate*100,name)
このプログラムを実行すると以下のような出力結果が得られます。当サイトで公開しているUNIXの設計思想を比較元として実行してみました。比較のページ群は金持ちプログラマのエクリチュールで公開しているウェブページです。
$ python ./bayesian-classifer.py The-UNIX-Philosophy.html 9.40 digital-economy-internet.html 2.17 Ultra-Low-level-Information-Society.html 0.44 seo-technique.html 0.29 p2p-bbs.html 0.28 Development-of-access-log-analysis-software.html 0.20 website-production.html 0.14 meanings-of-language.html 0.13 helpful-hints-for-business-blog.html 0.12 website-design.html 0.12 lernu-esperanto.html 0.11 Freakonomics.html 0.11 math-ISBN9784774132297.html 0.10 PhotoReading.html 0.10 web-customer.html 0.10 cause-and-effect.html 0.10 my-job.html 0.08 anti-seo.html 0.08 kill-ppc-advertisement.html 0.07 i-believe.html 0.07 wants-and-needs.html 0.07 web-analytics-and-web-site.html 0.06 about-government.html 0.06 how-to-make-money.html 0.06 install-llvm22-gentoo-linux.html 0.06 make-money-on-internet.html 0.05 quote.html 0.05 accessibility.html 0.05 learn-from-the-manager.html 0.05 daemon-process.html 0.05 numbers3-numbers4.html 0.05 growing-up-with-lucy.html 0.04 good-songs-to-cry-to.html 0.04 online-lesson.html 0.04 stop-smoking.html 0.04 human.html 0.04 shinbun.html 0.04 save-personal-information.html 0.01 Liquid Tension Experiment - Acid Rain.html
左の列が類似度で、右の列がHTMLファイル名。数字が大きいほど似ているということです。結果はUNIXの設計思想に最も似ているページはデジタルデータと経済とインターネットになりました。似ているかと言われれば違うと思うのだけど、ベイズの定理がさっぱり理解できないので、どうしてこのような結果になるのか想像もできません(笑)。
