协作型过滤(一) 欧几里得距离评价

欧几里得距离评价值(Euclidean Distance Score)

搜集数据
建立recommendation.py文件,使用一个python嵌套的字典,加入以下代码

critics = {'Lisa Rose':{'Lady in the water':2.5, 'Snakes on the 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 the plane':3.5,'Just my luck':1.5,'Superman Returns':5.0,'The Night Listener':3.0,'You, Me and Dupree':3.5},
'Micheal Phillips':{'Lady in the water':2.5, 'Snakes on the plane':3.0,'Superman Returns':3.5,'The Night Listener':4.0},
'Claudia Puig':{'Snakes on the plane':3.5,'Just my luck':3.0,'The Night Listener':4.5,'Superman Returns':4.0,'You, Me and Dupree':0.5},
'Mick LaSalle':{'Lady in the water':3.0, 'Snakes on the plane':4.0,'Just my luck':2.0,'Superman Returns':3.0,'The Night Listener':3.0,'You, Me and Dupree':2.0},
'Jack Matthews':{'Lady in the water':3.0, 'Snakes on the plane':4.0,'The Night Listener':3.0,'Superman Returns':5.0,'You, Me and Dupree':3.5},
'Toby':{'Snakes on the plane':4.5,'You, Me and Dupree':1.0,'Superman Returns':4.0}}

欧几里得距离(空间勾股定理)
在Python中,利用函数pow(n,2)对某数求平方,并使用sqrt函数求平方根。

from math import sqrt
sqrt(pow(4.5-4,2)+pow(1-2,2))

pow()函数: 通过内置的方法直接调用,内置方法会把参数作为整型,而 math 模块则会把参数转换为 float。 如果没有import math 而直接pow(1.0-2.0,2)会报错,import math以后不会报错。

计算两人的相似度
根据欧几里得距离值,偏好越相似的人,他们之间的距离值就越小。如果要求距离越近,得出的值越大,就取其倒数,但是为了防止两人没有相似度,被零整除,就将分母数值加1:

>>> 1/(1+sqrt(pow(4.5-4,2)+pow(1-2,2)))

python 代码

from math import sqrt


def sim_distance(prefs,person1,person2):


    sum_of_squares = sum([pow(prefs[person1][item]-prefs[person2][item],2) for item in prefs[person1] if item in prefs[person2]])

    return 1/(1+sqrt(sum_of_squares))

命令行:>>> recommendations.sim_distance(recommendations.critics,'Lisa Rose','Gene Seymour')
0.29429805508554946


第一篇博客产生于《集体智慧编程》总结。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值