-
Notifications
You must be signed in to change notification settings - Fork 9
/
TransRec.py
207 lines (170 loc) · 6.43 KB
/
TransRec.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
# -*- coding: utf-8 -*-
"""
Translation based recommendation
Created on Sat Jan 20 14:11:02 2018
@author: zyf
"""
import numpy as np
import random
from math import exp
from math import log
import matplotlib.pyplot as plt
dataset_name = 'Automotive'
dataset = np.load('../data/'+dataset_name+'Partitioned.npy')
[user_train,user_validation,user_test, usernum,itemnum] = dataset
item_successor = [[] for it in range(itemnum)]
for user in user_train:
for i in range(len(user_train[user])-1):
pre = user_train[user][i]
suc = user_train[user][i+1]
item_successor[pre].append(suc)
num_relation = sum([len(item_successor[item]) for item in range(itemnum)])
def sigmoid(x):
return 1.0 / (1 + exp(-x))
def findUser():
while 1:
user = random.randint(0,usernum-1)
if len(user_train[user]) > 1:
return user
def findNegSucc(pos_item):
while 1:
neg_item = random.randint(0,itemnum-1)
if neg_item != pos_item:
return neg_item
def TransPredict(user, pre, cur):
return - beta[cur] - np.sum(np.square(H[pre,:] + r + R[user,:] - H[cur,:]))
def AUC():
auc_train = 0
auc_valid = 0
auc_test = 0
testnum = 0 # event num per user in AUC testing
# max_itemid = max(item_train.keys())
for user in user_test:
if len(user_train[user])<2 or len(user_test[user])==0:
continue
testnum += 1
train_pre_item = user_train[user][-2]
train_item = user_train[user][-1]
train_score = TransPredict(user, train_pre_item, train_item)
valid_pre_item = user_validation[user][0]
valid_item = user_validation[user][1]
valid_score = TransPredict(user, valid_pre_item, valid_item)
test_pre_item = user_test[user][0]
test_item = user_test[user][1]
test_score = TransPredict(user, test_pre_item, test_item)
count_train, count_valid, count_test = 0, 0, 0
neg_num = 0
for ind in range(100):
itemid = random.randint(0,itemnum-1)
if itemid not in user_train[user] and itemid not in user_test[user]:
neg_num += 1
neg_score = TransPredict(user, train_pre_item, itemid)
if neg_score < train_score:
count_train += 1
elif neg_score == valid_score:
count_train += 0.5
else:
count_train += 0
neg_score = TransPredict(user, valid_pre_item, itemid)
if neg_score < valid_score:
count_valid += 1
elif neg_score == valid_score:
count_valid += 0.5
else:
count_valid += 0
neg_score = TransPredict(user, test_pre_item, itemid)
if neg_score < test_score:
count_test += 1
elif neg_score == test_score:
count_test += 0.5
else:
count_test += 0
auc_train += count_train*1.0 / neg_num
auc_valid += count_valid*1.0 / neg_num
auc_test += count_test*1.0 / neg_num
auc_train = auc_train/testnum
auc_valid = auc_valid/testnum
auc_test = auc_test/testnum
print "training AUC: ", auc_train
print "validation AUC: ", auc_valid
print "testing AUC: ", auc_test
return auc_train, auc_valid, auc_test
def normalization(it):
dist = np.sqrt(np.sum(np.square(H[it,:])))
if dist > 1:
H[it,:] = H[it,:] / dist
lam = 0.05
bias_lam = 0.01
reg_lam = 0.1
K = 10
learn_rate = 0.05
max_iter = 500
r = np.zeros(K)
R = np.random.rand(usernum, K)/1 - 0.5
H = np.random.rand(itemnum, K)/1 - 0.5
beta = np.zeros(itemnum)
auc_rec_train = []
auc_rec_valid = []
auc_rec_test = []
for it in range(max_iter):
objective = 0
regularization = 0
# dg = np.zeros((itemnum, K))
# de = np.zeros((K, itemnum))
for ind in range(num_relation):
u = findUser()
position = random.randint(0,len(user_train[u])-2)
p = user_train[u][position] # previous item
i = user_train[u][position + 1] # positive item
j = findNegSucc(i) # negative item
d1 = H[p,:] + r + R[u,:] - H[i,:]
d2 = H[p,:] + r + R[u,:] - H[j,:]
z = sigmoid(-beta[i] + beta[j] - \
np.sum(np.square(d1)) + \
np.sum(np.square(d2)))
# dg[u,:] += (1-z)*(eta[:,i]-eta[:,j])
# de[:,i] += (1-z)*(gam[u,:])
# de[:,j] += (1-z)*(-gam[u,:])
beta[i] += learn_rate*(-(1-z) - 2*bias_lam*beta[i])
beta[j] += learn_rate*((1-z) - 2*bias_lam*beta[j])
H[p,:] += learn_rate*((1-z)*2*(d2-d1) - 2*lam*H[p,:])
H[i,:] += learn_rate*((1-z)*2*(d1) - 2*lam*H[i,:])
H[j,:] += learn_rate*((1-z)*2*(-d2) - 2*lam*H[j,:])
r += learn_rate*((1-z)*2*(d2-d1) - 2*lam*r)
R[u] = learn_rate*((1-z)*2*(d2-d1) - 2*reg_lam*R[u])
normalization(p)
normalization(i)
normalization(j)
objective += log(z)
# dg -= lam*gam
# de -= lam*eta
# gam += learn_rate*dg
# eta += learn_rate*de
regularization = objective - lam*np.sum(np.square(H)) - \
lam*np.sum(np.square(r)) - \
reg_lam*np.sum(np.square(R)) - \
bias_lam*np.sum(np.square(beta))
if (it+1)%5 == 0:
print 'iteration: ' + str(it+1) + '\t' + str(regularization) \
+ '\t' + str(objective)
if (it+1)%10 == 0:
auc = AUC()
auc_rec_train.append(auc[0])
auc_rec_valid.append(auc[1])
auc_rec_test.append(auc[2])
plt.figure()
plt.plot(auc_rec_train)
plt.figure()
plt.plot(auc_rec_valid)
plt.figure()
plt.plot(auc_rec_test)
#np.save("itemVector.npy",H)
#np.save("userVector.npy",R)
R = np.load("userVector.npy")
for idx in range(20):
i = random.randint(0,usernum-1)
j = random.randint(0,usernum-1)
a = R[i]
b = R[j]
cos_angle = a.dot(b) / np.sqrt(a.dot(a) * b.dot(b))
print cos_angle