我在编程集体智慧中使用下面的代码,这是一本计算两位电影评论家之间的距离的函数。Euclidian距离Python的实现
该函数将字典中排名的差异相加,但n维中的欧式距离也包括该和的平方根。由于我们使用相同的函数来排列每个人,无论我们是否平方根都没有关系,但我想知道是否有特定的原因呢?
from math import sqrt
# Returns a distance-based similarity score for person1 and person2
def sim_distance(prefs,person1,person2):
# Get the list of shared_items
si={}
for item in prefs[person1]:
if item in prefs[person2]:
si[item]=1
# if they have no ratings in common, return 0
if len(si)==0: return 0
# Add up the squares of all the differences
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)