《推荐系统实践》用户协同过滤userCF测试代码

# -*- coding=utf-8 -*-

import math
from operator import itemgetter

dic={'A':('a','b','d'),'B':('a','c'),'C':('b','e'),'D':('c','d','e')}  


def Usersim(dicc):
        N=dict()
        item_user=dict()
        for u,items in dicc.items():
                N[u]=len(items)
                for i in items: 
                        if i not in item_user.keys():
                                item_user[i]=set()
                        item_user[i].add(u)

        C=dict()  

        for item,users in item_user.items():
                for u in users:
                        if u not in C.keys(): 
                                C[u]=dict()
                        for v in users:
                                if u==v:
                                        continue
                                else:
                                        if v not in C[u].keys():
                                                C[u][v] = 0
                                C[u][v]+=1 

        W=dict()
        for u,related_users in C.items():
                if not u in W.keys():
                        W[u] = dict()
                for v,cuv in related_users.items():
                        W[u][v] = cuv / math.sqrt(N[u]*N[v])
        return W


def Recommend(user,dicc,W,K):
        rvi=1    
        rank=dict()
        interacted_items=dicc[user]
        for v,wuv in sorted(W[user].items(), key=itemgetter(1), reverse=True)[0:K]:
                for i in dicc[v]:   
                        if i in interacted_items:
                                continue
                        if i not in rank.keys(): 
                                rank[i]=0
                        rank[i] += wuv*rvi
        return rank


if __name__ == '__main__':
        simMetric = Usersim(dic)
        rank = Recommend('A',dic,simMetric,3)
        print(rank)

参照书上的和网上的例子,修改补充后的完整的代码。可以执行。

你可能感兴趣的:(python)