ItemCF算法

本文介绍了一种基于协同过滤原理的个性化推荐算法,通过计算不同物品之间的相似度,为用户推荐与其兴趣相匹配的商品。算法首先计算相似用户间的共评商品数量,然后根据这些商品的共同评价来计算物品相似度。接着,使用相似度矩阵进行个性化推荐,并展示如何通过调整相似度阈值和推荐数量来优化推荐效果。
摘要由CSDN通过智能技术生成
import math
from operator import itemgetter

data = {'A':{'a','b','d'}, 'B':{'b','c','e'}, 'C':{'c','d'}, 'D':{'b','c','d'}, 'E':{'a','d'}}
def ItemSimilarity(data):
    #calculate co-rated users between itme
    C = dict()
    N = dict()
    for u, items in data.items():
        for i in items:
            if i not in N:
                N[i] = 1
            else :
                N[i] += 1
            if i not in C:
                C[i] = dict()
            for j in items:
                if i == j:
                    continue
                if j not in C[i]:
                    C[i][j] = 1
                else :
                    C[i][j] += 1
        '''
        for i , k in C.items():
            for j, sim in k.items():
                print i, j, sim
            print
        print '-----------'
        '''
    #calculate final similarity matrix W
    W = dict()
    for i, related_items in C.items():
        W[i] = dict()
        for j, cij in related_items.items():
            W[i][j] = cij / math.sqrt(N[i] * N[j])
    return W

Item_Simi = ItemSimilarity(data) #compute similarity between different items
for i, item in Item_Simi.items():
    for j, Simi in sorted(item.items(), key = itemgetter(1), reverse = True):
        print 'The similarity between ' + i + ' and ' + j + ' is ',
        print Simi


def Recommendation(data, W, K):
    rank = dict()
    ru = data.keys()
    rui = 1
    for k in ru:#user k
        rank[k] = dict()
        for i in data[k]:#i is the items user k buyed
            #print W[i]#the items buyed by k when k buyed i
            for j, wj in sorted(W[i].items(), key = itemgetter(1), reverse = True)[0:K]:
            #j is item ranked top K similarest with i buyed by k
                if j not in rank[k]:#when the interest user k see item j has never computed
                    rank[k][j] = rui * wj
                else:
                    rank[k][j] += rui * wj
    return rank
result = Recommendation(data,Item_Simi, 3) 

for i, j_item in result.items():
    for j, interest in sorted(j_item.items(), key = itemgetter(1), reverse = True):
        print ' the interest ' + i + ' buy ' + j +' is ',
        print interest

 

转载于:https://www.cnblogs.com/taotao315/archive/2013/06/10/3130767.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值