|
| 1 | +# coding:UTF-8 |
| 2 | +''' |
| 3 | +Date:20160928 |
| 4 | +@author: zhaozhiyong |
| 5 | +''' |
| 6 | + |
| 7 | +importnumpyasnp |
| 8 | +fromuser_based_recommendimportload_data, similarity |
| 9 | + |
| 10 | +defitem_based_recommend(data, w, user): |
| 11 | +'''基于商品相似度为用户user推荐商品 |
| 12 | + input: data(mat):商品用户矩阵 |
| 13 | + w(mat):商品与商品之间的相似性 |
| 14 | + user(int):用户的编号 |
| 15 | + output: predict(list):推荐列表 |
| 16 | + ''' |
| 17 | +m, n=np.shape(data) # m:商品数量 n:用户数量 |
| 18 | +interaction=data[:,user].T# 用户user的互动商品信息 |
| 19 | + |
| 20 | +# 1、找到用户user没有互动的商品 |
| 21 | +not_inter= [] |
| 22 | +foriinxrange(n): |
| 23 | +ifinteraction[0, i] ==0: # 用户user未打分项 |
| 24 | +not_inter.append(i) |
| 25 | + |
| 26 | +# 2、对没有互动过的商品进行预测 |
| 27 | +predict={} |
| 28 | +forxinnot_inter: |
| 29 | +item=np.copy(interaction) # 获取用户user对商品的互动信息 |
| 30 | +forjinxrange(m): # 对每一个商品 |
| 31 | +ifitem[0, j] !=0: # 利用互动过的商品预测 |
| 32 | +ifxnotinpredict: |
| 33 | +predict[x] =w[x, j] *item[0, j] |
| 34 | +else: |
| 35 | +predict[x] =predict[x] +w[x, j] *item[0, j] |
| 36 | +# 按照预测的大小从大到小排序 |
| 37 | +returnsorted(predict.items(), key=lambdad:d[1], reverse=True) |
| 38 | + |
| 39 | +deftop_k(predict, k): |
| 40 | +'''为用户推荐前k个商品 |
| 41 | + input: predict(list):排好序的商品列表 |
| 42 | + k(int):推荐的商品个数 |
| 43 | + output: top_recom(list):top_k个商品 |
| 44 | + ''' |
| 45 | +top_recom= [] |
| 46 | +len_result=len(predict) |
| 47 | +ifk>=len_result: |
| 48 | +top_recom=predict |
| 49 | +else: |
| 50 | +foriinxrange(k): |
| 51 | +top_recom.append(predict[i]) |
| 52 | +returntop_recom |
| 53 | + |
| 54 | +if__name__=="__main__": |
| 55 | +# 1、导入用户商品数据 |
| 56 | +print"------------ 1. load data ------------" |
| 57 | +data=load_data("data.txt") |
| 58 | +# 将用户商品矩阵转置成商品用户矩阵 |
| 59 | +data=data.T |
| 60 | +# 2、计算商品之间的相似性 |
| 61 | +print"------------ 2. calculate similarity between items -------------" |
| 62 | +w=similarity(data) |
| 63 | +# 3、利用用户之间的相似性进行预测评分 |
| 64 | +print"------------ 3. predict ------------" |
| 65 | +predict=item_based_recommend(data, w, 0) |
| 66 | +# 4、进行Top-K推荐 |
| 67 | +print"------------ 4. top_k recommendation ------------" |
| 68 | +top_recom=top_k(predict, 2) |
| 69 | +printtop_recom |
0 commit comments