-
Notifications
You must be signed in to change notification settings - Fork 0
/
LFM.py
94 lines (84 loc) · 2.6 KB
/
LFM.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
import random
import operator
allItemSet = set()
def InitAllItemSet(user_items):
allItemSet.clear()
for user, items in user_items.items():
for i, r in items.items():
allItemSet.add(i)
def InitItems_Pool(items):
interacted_items = set(items.keys())
items_pool = list(allItemSet - interacted_items)
# items_pool = list(allItemSet)
return items_pool
"""
负采样过程
"""
def RandSelectNegativeSample(items):
ret = dict()
for i in items.keys():
ret[i] = 1
n = 0
for i in range(0,len(items) * 3):
items_pool = InitItems_Pool(items)
item = items_pool[random.randint(0,len(items_pool) - 1 )]
if item in ret:
continue
ret[item] = 0
n += 1
if n > len(items):
break
return ret
def Predict(user,item,P,Q):
rate = 0
for f,puf in P[user].items():
qif = Q[item][f]
rate += puf * qif
return rate
def InitModel(user_items,F):
P = dict()
Q = dict()
for user, items in user_items.items():
P[user] = dict()
for f in range(0,F):
P[user][f] = random.random()
for i,r in items.items():
if i not in Q:
Q[i] = dict()
for f in range(0,F):
Q[i][f] = random.random()
return P,Q
def LatentFactorModel(user_items, F,T, alpha, lamb):
InitAllItemSet(user_items)
[P,Q] = InitModel(user_items, F)
for step in range(0,T):
for user, items in user_items.items():
samples = RandSelectNegativeSample(items)
for item, rui in samples.items():
eui = rui - Predict(user, item, P,Q)
for f in range(0,F):
P[user][f] += alpha * (eui * Q[item][f] - \
lamb * P[user][f])
Q[item][f] += alpha * (eui * P[user][f] - \
lamb * Q[item][f])
alpha *= 0.9
return P,Q
def Recommend(user,train,P,Q):
rank = dict()
interacted_items = train[user]
for i in Q:
if i in interacted_items.keys():
continue
rank.setdefault(i,0)
for f,qif in Q[i].items():
puf = P[user][f]
rank[i] += puf * qif
return rank
def Recommendation(users, train,P,Q):
result = dict()
for user in users:
rank = Recommend(user,train,P,Q)
R = sorted(rank.items(), key = operator.itemgetter(1), \
reverse = True)
result[user] = R
return result