今天看了一篇文章寫的挺好的,因此本身總結一下,發出來你們一塊兒學習一下python
歐幾里德距離(百度來的哦):歐幾里得度量(euclidean metric)(也稱歐式距離)是一個一般採用的距離定義,指在m維空間中兩個點之間的真實距離,或者向量的天然長度(即該點到原點的距離),在二維和三維空間中的歐氏距離就是兩點之間的實際距離。web
計算類似度評價值的一個很是簡單的方法就是歐幾里德距離評估法,它以通過人們一致評價的物品做爲座標軸,而後將參與評價的人繪製在圖上,並考察他們彼此的距離,以下圖所示c#
該圖顯示了人員的分佈狀況,Toby在Snakes軸上和Dupree軸上座標值爲:4.5,1.0,在圖中兩人距離越近,他們興趣偏好就約相近。ide
爲了計算圖上Toby和LaSalle之間的距離,咱們計算出每一軸向上得差值,窮平方後再相加,最後對總和取平方根。函數
在python中可使用pow(n,2)對某數求平方,並使用sqrt函數求平方根:學習
>>> from math import sqrt >>> sqrt(pow(4.5-4,2)+pow(1-2,2)) 1.118033988749895
上述代碼能夠計算出距離值,偏好越相近的人,距離就越短。不過,咱們還須要一個函數,來對偏好越相近的狀況給出最大的值,爲此,咱們能夠將函數值加1(這樣避免遇到被零整除的錯誤),並取其倒數:ui
>>> 1/(1+sqrt(pow(4.5-4,2)+pow(1-2,2))) 0.4721359549995794
這個數字的值老是在0和1 之間,返回1則表示兩人具備相同的愛好,下面的代碼是計算類似度的函數。idea
from math import sqrt #先定義一個字典,裏面是用戶的評價 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,'You, Me and Dupree':3.0, 'The Night Listener':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, 'Superman Returns':4.0,'The Night Listener':4.5,'You, Me and Dupree':2.5}, 'Toby': {'Snakes on a Plane':4.5, 'Superman Returns':4.0,'You, Me and Dupree':1.0} } #本函數來計算用戶類似度 def sim_distance(prefs,preson1,preson2): #獲得shared_items的列表 si = {} for item in prefs[preson1]: if item in prefs[preson2]: si[item]=1 #無類似度返回0 if len(si) == 0: return 0 #求平方和 sum_of_squares = sum([pow(prefs[preson1] [item]-prefs[person2] [item],2) for itme in prefs[preson1] if item in prefs[preson2]]) print sum_of_squares return 1/(1+sqrt(sum_of_squares))