相似度计算的若干函数
from math import sqrt
def sim_distance(p1,p2):
c=set(p1.keys())&set(p2.keys())
if not c: return 0
sum_of_squares=sum([pow(p1.get(sk)-p2.get(sk), 2 ) for sk in c])
p= 1 /( 1 +sqrt(sum_of_squares))
return p
def sim_distance_pir(p1,p2):
c=set(p1.keys())&set(p2.keys())
if not c: return 0
s1=sum([p1.get(sk) for sk in c])
s2=sum([p2.get(sk) for sk in c])
sq1=sum([pow(p1.get(sk), 2 ) for sk in c])
sq2=sum([pow(p2.get(sk), 2 ) for sk in c])
ss=sum([p1.get(sk)*p2.get(sk) for sk in c])
n=len(c)
num=ss-(s1*s2/n)
den=sqrt((sq1-pow(s1, 2 )/n)*(sq2-pow(s2, 2 )/n))
#print s1,s2,sq1,sq2,ss,n,num,den
if den== 0 : return 0
p=num/den
return p
def sim_distance_jacc(p1,p2):
c=set(p1.keys())&set(p2.keys())
if not c: return 0
ss=sum([p1.get(sk)*p2.get(sk) for sk in c])
sq1=sum([pow(sk, 2 ) for sk in p1.values()])
sq2=sum([pow(sk, 2 ) for sk in p2.values()])
p=float(ss)/(sq1 + sq2 - ss)
return p
def sim_distance_cos(p1,p2):
c=set(p1.keys())&set(p2.keys())
if not c: return 0
ss=sum([p1.get(sk)*p2.get(sk) for sk in c])
sq1=sqrt(sum([pow(sk, 2 ) for sk in p1.values()]))
sq2=sqrt(sum([pow(sk, 2 ) for sk in p2.values()]))
p=float(ss )/(sq1*sq2)
return p
#
#a={'a':4.5,'b':1.0,'c':7}
from distance import *
def topsimilar(item,data,n= 5 ,sim_func=sim_distance):
score=[(sim_func(data.get(item),data.get(ik)),ik) for ik in data.keys() if ik!=item]
score.sort()
score.reverse()
return score
prefs= {
"A" : { "1" : 3 , "2" : 4 , "3" : 0 , "4" : 3 , "5" : 3 },
"B" : { "1" : 2 , "2" : 3 , "3" : 2 },
"C" : { "1" : 2 , "2" : 4 , "3" : 4 , "4" : 3 , "5" : 0 },
"D" : { "1" : 0 , "2" : 4 , "3" : 0 , "4" : 2 , "5" : 4 }
}
print topsimilar( 'A' , prefs,)
print topsimilar( 'A' , prefs,sim_func=sim_distance_pir)
print topsimilar( 'A' , prefs,sim_func=sim_distance_cos)
print topsimilar( 'A' , prefs,sim_func=sim_distance_jacc)