关于python编程的一个问题
这是在《集体智慧编程》里的一个例子:critics={'LisaRose':{'ladyinthewater':2.5,'snakesonaplane':3.5,'jus...
这是在《集体智慧编程》里的一个例子:
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.5,'the night listener':3.0},}
from math import sqrt
def sim__pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]:si[item]=1
n=len(si)
if n==0: return 1
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p1][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
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
求皮尔逊距离,最后pierxun.sim__pearson(pierxun.critics,'Lisa Rose','Gene Seymour')为什么结果总是0? 展开
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.5,'the night listener':3.0},}
from math import sqrt
def sim__pearson(prefs,p1,p2):
si={}
for item in prefs[p1]:
if item in prefs[p2]:si[item]=1
n=len(si)
if n==0: return 1
sum1=sum([prefs[p1][it] for it in si])
sum2=sum([prefs[p2][it] for it in si])
sum1Sq=sum([pow(prefs[p1][it],2) for it in si])
sum2Sq=sum([pow(prefs[p1][it],2) for it in si])
pSum=sum([prefs[p1][it]*prefs[p2][it] for it in si])
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
求皮尔逊距离,最后pierxun.sim__pearson(pierxun.critics,'Lisa Rose','Gene Seymour')为什么结果总是0? 展开
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询