简介
欧几里德距离计算指多维空间两点间的距离,当为二维平面的时候我们可以很好的进行想象,两个点的距离计算就是,横坐标相减的平方加上纵坐标相减的平方然后开方,多维的话,以此类推。
实战,例子选自集体智慧编程。
# A dictionary of movie critics and their ratings of a small
# set of movies
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
#计算两个人的相似度。
def sim_distance(prefs,person1,person2):
person1Items = prefs[person1]
#两个具有的相同爱好,即是计算维度的多少。
commonItemName = [itemName for itemName in person1Items if itemName in prefs[person2]]
#没有相似度的时候返回0
if len(commonItemName) == 0:
return 0
distance = sqrt(sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in commonItemName]))
return 1/(1+distance)
网友评论