forked from iamccme/recommend-CF
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathItemCF.py
executable file
·239 lines (211 loc) · 6.51 KB
/
ItemCF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
@desc 基于物品的协同过滤算法,方法为ItemCF-IUF
@author cheng.cheng
@email [email protected]
@date 2012-06-19
'''
import sys
import random
import math
from operator import itemgetter
def ReadData(file,data):
''' 读取评分数据
@param file 评分数据文件
@param data 储存评分数据的List
'''
for line in file :
line = line.strip('\n')
linelist = line.split("::")
data.append([linelist[0],linelist[1]])
def SplitData(data, M, key, seed):
''' 将数据分为训练集和测试集
@param data 储存训练和测试数据的List
@param M 将数据分为M份
@param key 选取第key份数据做为测试数据
@param seed 随机种子
@return train 训练数据集Dict
@return test 测试数据集Dict
'''
test = dict ()
train = dict ()
random.seed(seed)
for user,item in data:
if random.randint(0,M) == key:
if user in test:
test[user].append(item)
else:
test[user] = []
else:
if user in train:
train[user].append(item)
else:
train[user] = []
return train, test
def UserSimilarityOld(train):
W = dict()
for u in train.keys():
W[u] = dict()
for v in train.keys():
if u == v:
continue
W[u][v] = len(list(set(train[u]) & set(train[v])))
W[u][v] /= math.sqrt(len(train[u]) * len(train[v]) * 1.0)
return W
def ItemSimilarity(train):
''' 计算物品相似度
@param train 训练数据集Dict
@return W 记录用户相似度的二维矩阵
'''
C = dict()
N = dict()
#计算没两个item共有的user数目
for u, items in train.items():
for i in items:
if i not in N:
N[i] = 0
N[i] += 1
for j in items:
if i == j:
continue
if i not in C :
C[i] = dict()
if j not in C[i]:
C[i][j] = 0
C[i][j] += 1
W = dict()
for i, related_items in C.items():
for j, cij in related_items.items():
if i not in W :
W[i] = dict()
W[i][j] = cij / math.sqrt(N[i] * N[j])
return W
def Coverage(train, test, W, N, K):
''' 获取推荐结果
@param user 输入的用户
@param train 训练数据集Dict
@param W 记录用户相似度的二维矩阵
@param N 推荐结果的数目
@param K 选取近邻的数目
'''
recommned_items = set()
all_items = set()
for user in train.keys():
for item in train[user]:
all_items.add(item)
rank = GetRecommendation(user, train, W, N, K)
for item, pui in rank:
recommned_items.add(item)
print 'len: ',len(recommned_items),'\n'
return len(recommned_items) / (len(all_items) * 1.0)
def GetRecommendation(user, train ,W, N, K):
''' 获取推荐结果
@param user 输入的用户
@param train 训练数据集Dict
@param W 记录用户相似度的二维矩阵
@param N 推荐结果的数目
@param K 选取近邻的数目
'''
rank = dict()
ru = train[user]
for i in ru:
for j,wj in sorted(W[i].items(), key=itemgetter(1),\
reverse = True)[0:K]:
if j in ru:
continue
if j in rank:
rank[j] += wj
else:
rank[j] = 0
rank = sorted(rank.items(), key=itemgetter(1), reverse = True)[0:N]
return rank
def Recall(train, test, W, N, K):
''' 计算推荐结果的召回率
@param train 训练数据集Dict
@param test 测试数据集Dict
@param W 记录用户相似度的二维矩阵
@param N 推荐结果的数目
@param K 选取近邻的数目
'''
hit = 0
all = 0
for user in train.keys():
if user in test:
tu = test[user]
rank = GetRecommendation(user, train, W, N, K)
for item, pui in rank:
if item in tu:
hit+= 1
all += len(tu)
print(hit)
print(all)
return hit/(all * 1.0)
def Precision(train, test, W, N, K):
''' 计算推荐结果的准确率
@param train 训练数据集Dict
@param test 测试数据集Dict
@param W 记录用户相似度的二维矩阵
@param N 推荐结果的数目
@param K 选取近邻的数目
'''
hit = 0
all = 0
for user in train.keys():
if user in test:
tu = test[user]
rank = GetRecommendation(user, train, W, N, K)
for item, pui in rank:
if item in tu:
hit+= 1
all += N
print(hit)
print(all)
return hit/(all * 1.0)
def Popularity(train, test, W, N, K):
''' 计算推荐结果的流行度
@param train 训练数据集Dict
@param test 测试数据集Dict
@param W 记录用户相似度的二维矩阵
@param N 推荐结果的数目
@param K 选取近邻的数目
'''
item_popularity = dict()
for user, items in train.items():
for item in items:
if item not in item_popularity:
item_popularity[item] = 0
item_popularity[item] += 1
ret = 0
n = 0
for user in train.keys():
rank = GetRecommendation(user, train, W, N, K)
for item, pui in rank:
ret += math.log(1+ item_popularity[item])
n += 1
ret /= n * 1.0
return ret
if __name__ == '__main__':
data = []
M = 7
key = 1
seed = 1
N = 10
K = 10
W = dict()
rank = dict()
print("this is the main function")
file = open('./ml-1m/rating.dat')
ReadData(file,data)
train,test = SplitData(data, M, key, seed)
W = ItemSimilarity(train)
recall = Recall(train, test, W, N, K)
precision = Precision(train, test, W, N, K)
popularity = Popularity(train, test, W, N, K)
coverage = Coverage(train, test, W, N, K)
print 'recall: ',recall,'\n'
print 'precision: ',precision,'\n'
print 'Popularity: ',popularity,'\n'
print 'coverage: ', coverage,'\n'
else :
print("this is not the main function")