协同过滤算法

关于相似度的三种计算,可用于电影推荐系统(希望有大神给我指导意见!)

from random import sample
import json
from math import sqrt
import time
from collections import defaultdict

#曼哈顿 欧式 cos 三种距离

users={"Angelica":{"星际穿越"3.5,“放牛班的春天”:2.0"肖申克的救赎"4.5"盗梦空间":5.0,
                    "阿甘正传"1.5"乱世佳人":2.5,
                    "傲慢与偏见":2.0},
        "Bill":{"星际穿越"2.0"放牛班的春天":3.5,
                "肖申克的救赎"4.5"盗梦空间": 5.0,
                "阿甘正传"1.5"乱世佳人": 2.5,
                "傲慢与偏见": 2.0},
        "Chan":{"星际穿越"2.0"放牛班的春天":3.5,
                "肖申克的救赎"3.5"盗梦空间": 5.0,
                "阿甘正传"2.5"乱世佳人": 2.5,
                "傲慢与偏见": 2.0}
        }

def man_dis(usrl,usr2):
    distance = 0
    flag=False
    for m in users[usrl]:
        if m in users [usr2]:
            distance += abs(users[usr1][m]-users[usr2][m])
            #distance += (users[usr1][m]-users[usr2][m])**2
            flag =True
    if flag == True:
        return distance
    else :
        return -1


def au1_dis(usrl,usr2):
    distance = 0
    flag=False
    for m in users[usrl]:
        if m in users [usr2]:
            distance += (users[usr1][m]-users[usr2][m])**2
            flag =True
    if flag == True:
        return sqrt(distance)
    else :
        return -1


def cos_dis(usrl,usr2):
    ratingl=users[usr1]
    rating2=users[usr2]
    common_movies=[x for x in ratingl if x in rating2]
    if len(common_movies)==0:
        return -1
    fenzi=sum([ratingl[x]*rating2[x] for x in common_movies])
    len_1=sqrt(sum([rating1[x]**2 for x in common_movies]))
    len_2=sqrt(sum([rating2[x]**2 for x in common_movies]))
    if len_1 + len_2==0:
        return -1
    return fenzi/(len_1 * len_2)


def au2_dis(usrl,usr2):
    ratingl=users[usr1]
    rating2=users[usr2]
    common_movies=[x for x in ratingl if x in rating2]
    if len(common_movies)==0:
        return -1
    return sqrt(sum([(ratingl[x] - rating2[x])**2 for x in common_movies]))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值