建立数据集
为操作方便手动录入数据集(书中样例)
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}}
计算欧几里得距离
def sim_distance(prefs,person1,person2):
si = list(filter(lambda x:x in prefs[person2],prefs[person1]))
return 0 if len(si) == 0 else 1 /(1 + sum((prefs[person1][it] - prefs[person2][it]) ** 2
for it in si))
计算皮尔逊距离
def sim_pearson(prefs,p1,p2):
si = list(filter(lambda x:x in prefs[p2],prefs[p1]))
n = len(si)
sum1 = sum(prefs[p1][item] for item in si)
sum2 = sum(prefs[p2][item] for item in si)
sum1sq = sum([prefs[p1][it] ** 2 for it in si])
sum2sq = sum([prefs[p2][it] ** 2 for it in si])
pSum = sum([prefs[p1][it] * prefs[p2][it] for it in si])
num = pSum - (sum1 * sum2)/n
den = ((sum1sq - sum1 ** 2 / n ) * (sum2sq - sum2 ** 2 / n)) ** 0.5
r = 0 if n == 0 or den == 0 else num / den
return r
#待续