簡介
指多維空間兩點間的距離,當(dāng)為二維平面的時候我們可以很好的進行想象,兩個點的距離計算就是,橫坐標(biāo)相減的平方加上縱坐標(biāo)相減的平方然后開方,多維的話,以此類推。
歐幾里德距離計算
實戰(zhàn),例子選自集體智慧編程。
# 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)