我有一个关于 Pearson's Correlation 相似性用户的 python 代码,我想分析计算步骤,因为我是 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)
?
我对[p1][it]
. 我希望你能帮助我,谢谢你的提前。