欧几里得距离:m维空间中两个点之间的真实距离。
from math import sqrt
critics = {'Lisa':{'A':2.5,'B':3.5,'C':3.0,'D':3.5,'E':2.5,'F':3.0},
'Gene':{'A':3.0,'B':3.5,'C':1.5,'D':5.0,'F':3.0,'E':3.5},
'Michael':{'A':2.5,'B':3.0,'D':3.5,'F':4.0},
'Claudia':{'B':3.5,'C':3.0,'F':4.5,'D':4.0,'E':2.5},
'Mick':{'A':3.0,'B':4.0,'C':2.0,'D':3.0,'F':3.0,'E':2.0},
'Jack':{'A':3.0,'B':4.0,'F':3.0,'D':5.0,'E':3.5},
'Toby':{'B':4.5,'D':4.0,'E':1.0}}
"""""
欧几里得距离评价
Euclidean Distance Score
"""""
#书本算法
def sim_distance(prefs,person1,person2):
si = {}
for item in prefs[person1]:
if item in prefs[person2]:
si[item] = 1
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+sqrt(sum_of_squares))
#自己编写
def sim_distance2(prefs,person1,person2):
si = {}
for item in prefs[person1]:
if item in prefs[person2]:
si[item] = 1
if len(si) == 0:
return 0
sum = 0
for item in si:
sum = sum + pow((prefs[person1][item]-prefs[person2][item]),2)
sim_dis = 1/(1+sqrt(sum))
return sim_dis
网友评论