我在編程集體智慧中使用下面的代碼,這是一本計算兩位電影評論家之間的距離的函數。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)