hogehoge foobar Blog Style Beta

Web,Mac,Linux,JavaScript,Perl,PHP,RegExp,Git,Vim,Redmineなど技術的なことのメモや、ちょっと便利そうなものの紹介をしています。

[]集合知プログラミングを読みはじめる

実践 Web Standards Design ~Web標準の基本とCSSレイアウト&Tips;~」読了したので、
以前に購入していた「集合知プログラミング」を読み始めました。

まだ、10ページくらいしか読めていませんが、内容が結構難しいので、
読むのに時間がかかりそうです。
この本でのサンプルコードはpythonで書かれているので、python学習も合わせて、
じっくりと読み込んでいこうと思います。

とりあえず今日書いたpythonスクリプトをおさらい。

集合知プログラミング(オライリージャパン)からの引用です。

##################################################
# ユークリッド距離によるスコア
##################################################

# データディクショナリ
critics={'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'The Night Listener': 3.0},
'Gene Seymour': {'Lady in the Water': 3.0, 'Snakes on a Plane': 3.5,
'Just My Luck': 1.5, 'Superman Returns': 5.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 3.5},
'Michael Phillips': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.0,
'Superman Returns': 3.5, 'The Night Listener': 4.0},
'Claudia Puig': {'Snakes on a Plane': 3.5, 'Just My Luck': 3.0,
'The Night Listener': 4.5, 'Superman Returns': 4.0,
'You, Me and Dupree': 2.5},
'Mick LaSalle': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'Just My Luck': 2.0, 'Superman Returns': 3.0, 'The Night Listener': 3.0,
'You, Me and Dupree': 2.0},
'Jack Matthews': {'Lady in the Water': 3.0, 'Snakes on a Plane': 4.0,
'The Night Listener': 3.0, 'Superman Returns': 5.0, 'You, Me and Dupree': 3.5},
'Toby': {'Snakes on a Plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}

# モジュールのインポート
from math import sqrt

##################################################
# person1とperson2の距離を基にした類似性スコアを返す
##################################################
def sim_distance(prefs,person1,person2):

# 二人共、評価しているアイテムリストを得る
si={}
for item in prefs[person1]:
if item in prefs[person2]: si[item]=1

# 両者に一致しているアイテムが泣ければreturn 0
if len(si)==0: return 0

# すべての平方根を足し合わせる
sum_of_squares=sum([pow(prefs[person1][item]-prefs[person2][item],2)
for item in prefs[person1] if item in prefs[person2]])

return 1/(1+sum_of_squares)


数学知識を忘れているので、ついでにおさらいしてみました。

平方根
 平方根とは2乗してxになるもの
 例えば、2は2乗すると→4になるので、2は4の平方根

・ルート
 平方根を記号であらわしたもの(?)
 √4 = 2