我有一個關於相似性用戶與皮爾森相關性的python代碼,我想分析一下計算的步驟,因爲我是一個Python hehe的初學者。當我嘗試手動計算並與此程序的結果進行比較時,結果總是不一樣。我想知道如果我在手動計算時錯誤了。該代碼是這樣的:皮爾遜在Python中的相關性
# A dictionary of movie critics and their ratings of a small set of movies
critics={'User 1': {'Spiderman': 1.0, 'Batman Begins': 2.0, 'Superman': 4.0},
'User 2': {'Spiderman': 2.0, 'Batman Begins': 3.0, 'Superman': 3.0}
}
from math import sqrt
# Returns the Pearson correlation coefficient for p1 and p2
def sim_pearson(prefs,p1,p2):
# Get the list of mutually rated items
si={}
for item in prefs[p1]:
if item in prefs[p2]: si[item]=1
# if they are no ratings in common, return 0
if len(si)==0: return 0
# Sum calculations
n=len(si)
# Sums of all the preferences
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
# Sums of the squares
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p2][it],2) for it in si])
# Sum of the products
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
# Calculate r (Pearson score)
num=pSum-(sum1*sum2/n)
den=sqrt((sum1Sq-pow(sum1,2)/n)*(sum2Sq-pow(sum2,2)/n))
if den==0: return 0
r=num/den
return r
def main():
z = sim_pearson(critics, 'User 1','User 2')
print z
if __name__ == "__main__":
main()
我要計算用戶1和用戶2之間的相似性,但我在這部分很困惑:
([prefs[p1][it] for it in si])
是什麼意思[它] ?
相似的結果,如果我使用這個程序是:0.755928946018
是真正的驗證碼([prefs[p1][it] for it in si])
被乘以用戶1的評級的含義是什麼?像1*2*4
?或者它必須乘以用戶2的評分?像(1*2)+(1*3)+(4*3)
?我對感到困惑。我希望你能幫助我,謝謝你的提前。
好的答案!非常詳細的 – Llopis 2014-09-19 10:02:39
和'n'指的是用戶數量或用戶評級的電影數量? – user3528526 2014-09-19 10:10:28
我得到了'sum1 = 7'' sum2 = 8'' sum1sq = 21'' sum2sq = 22''psum = 56',這是真的嗎?因爲每次手動計算hmm時結果總是不一樣 – user3528526 2014-09-19 10:18:52