-
Notifications
You must be signed in to change notification settings - Fork 1
/
ucl_fm.py
305 lines (286 loc) · 9.17 KB
/
ucl_fm.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/python
import sys
import time
import math
import numpy as np
from sklearn.metrics import roc_auc_score
from sklearn.metrics import mean_squared_error
from time import gmtime, strftime
import dl_utils as ut
advertiser = '2997'
if len(sys.argv) > 1:
advertiser = sys.argv[1]
train_file='../../make-ipinyou-data/' + advertiser + '/train.fm.txt' #training file
test_file='../../make-ipinyou-data/' + advertiser + '/test.fm.txt' #test file
index_file='../../make-ipinyou-data/' + advertiser + '/featindex.fm.txt'
result_file='../log/ '+ 'log-fm-' + strftime("%Y-%m-%d", gmtime()) + '.txt'
model_file='../../make-ipinyou-data/' + advertiser + '/fm.model.txt'
trainlog_file='../../make-ipinyou-data/' + advertiser + '/train.log.txt' #training file
testlog_file='../../make-ipinyou-data/' + advertiser + '/test.log.txt'
traindl_file='../../make-ipinyou-data/' + advertiser + '/train.dl.txt' #training file
testdl_file='../../make-ipinyou-data/' + advertiser + '/test.dl.txt'
def sigmoid(p):
return 1.0 / (1.0 + math.exp(-p))
def pred_lr(x):
p = w_0
for (feat, val) in x:
p += w[feat] * val
p = sigmoid(p)
return p
def pred(x):
p = w_0
sum_1 = 0
sum_2 = 0
for (feat, val) in x:
tmp = v[feat] * val
sum_1 += tmp
sum_2 += tmp * tmp
p = np.sum(sum_1 * sum_1 - sum_2) / 2.0 + w_0
for (feat, val) in x:
p += w[feat] * val
p = sigmoid(p)
return (p, sum_1)
def one_data_y_x(line):
s = line.strip().replace(':', ' ').split(' ')
y = int(s[0])
x = []
for i in range(1, len(s), 2):
val = 1
if not one_value:
val = float(s[i+1])
x.append((int(s[i]), val))
return (y, x)
def output_model(model_file):
print 'output model to ' + model_file
foo = open(model_file, 'w')
foo.write('%.5f %d %d\n' % (w_0, feature_num, k))
for i in range(feature_num):
foo.write('%d %.5f' % (i, w[i]))
for j in range(k):
foo.write(' %.5f' % v[i][j])
foo.write(' %s\n' % index_feature[i])
foo.close()
def load_model(model_file):
global feature_num, k, w_0, w, v, index_feature, feature_index
print 'loading model from ' + model_file
fi = open(model_file, 'r')
line_num = 0
for line in fi:
line_num += 1
s = line.strip().split()
if line_num == 1:
w_0 = float(s[0])
feature_num = int(s[1])
k = int(s[2])
v = np.zeros((feature_num, k))
w = np.zeros(feature_num)
index_feature = {}
feature_index = {}
else:
i = int(s[0])
w[i] = float(s[1])
for j in range(2, 2 + k):
v[i][j] = float(s[j])
feature = s[2 + k]
index_feature[i] = feature
feature_index[feature] = i
fi.close()
feature_cols = ['weekday', 'hour', 'useragent', 'IP', 'region', 'city', 'adexchange', 'domain', 'slotid',
'slotwidth', 'slotheight', 'slotvisibility', 'slotformat', 'creative', 'advertiser'] #, 'usertag']
feature_cols_special = ['slotprice']
def feat_trans(name, content):
content = content.lower()
if name == 'slotprice':
price = int(content)
if price > 100:
return '101+'
elif price > 50:
return '51-100'
elif price > 10:
return '11-50'
elif price > 0:
return '1-10'
else:
return '0'
def get_tags(content):
if content == '\n' or len(content) == 0:
return ['null']
return content.strip().split(',')
def rewrite_train_test(input_file, rewrite_file):
namecol = {}
reader = open(input_file, 'r')
writer = open(rewrite_file, 'w')
first = True
for line in reader:
s = line.strip().split('\t')
if first:
first = False
for i in range(1, len(s)):
name = s[i]
if name in feature_cols or name in feature_cols_special:
namecol[name] = i
continue
writer.write('%s,%.5f' % (s[0], w_0))
fid = 1
for name in feature_cols + feature_cols_special:
i = namecol[name]
feature = s[i]
if name in feature_cols_special:
feature = feat_trans(name, s[i])
vfeat = np.zeros(k)
wfeat = 0.
if ',' in feature:
tags = get_tags(feature)
for tag in tags:
feature = name + ':' + tag
if feature not in feature_index:
feature = name + ':other'
idx = feature_index[feature]
vfeat += v[idx]
wfeat += w[idx]
vfeat /= len(tags)
wfeat /= len(tags)
else:
feature = name + ':' + feature
if feature not in feature_index:
feature = name + ':other'
idx = feature_index[feature]
vfeat = v[idx]
wfeat = w[idx]
writer.write(',%.5f' % wfeat)
#writer.write(' %d:%.5f' % (fid, wfeat))
fid += 1
for j in range(k):
writer.write(',%.5f' % vfeat[j])
#writer.write(' %d:%.5f' % (fid, vfeat[j]))
fid += 1
writer.write('\n')
reader.close()
writer.close()
def pred_best(x,best_w,best_v,best_w_0):
p = best_w_0
sum_1 = 0
sum_2 = 0
for (feat, val) in x:
tmp = best_v[feat] * val
sum_1 += tmp
sum_2 += tmp * tmp
p = np.sum(sum_1 * sum_1 - sum_2) / 2.0 + w_0
for (feat, val) in x:
p += best_w[feat] * val
p = sigmoid(p)
return p
def pred_all(file,best_w,best_v,best_w_0):
fi = open(file, 'r')
yp = []
for line in fi:
data = one_data_y_x(line)
pclk = pred_best(data[1],best_w,best_v,best_w_0)
yp.append(pclk)
fi.close()
print type(yp)
print len(yp)
return yp
# start here
# global setting
np.random.seed(10)
one_value = True
k = 10
learning_rate = 0.01
weight_decay = 1E-6
v_weight_decay = 1E-6
train_rounds = 40
buffer_num = 1000000
# initialise
feature_index = {}
index_feature = {}
max_feature_index = 0
feature_num = 0
print 'reading feature index'
fi = open(index_file, 'r')
for line in fi:
s = line.strip().split('\t')
index = int(s[1])
feature_index[s[0]] = index
index_feature[index] = s[0]
max_feature_index = max(max_feature_index, index)
fi.close()
feature_num = max_feature_index + 1
print 'feature number: ' + str(feature_num)
print 'initialising'
init_weight = 0.05
v = (np.random.rand(feature_num, k) - 0.5) * init_weight
w = np.zeros(feature_num)
w_0 = 0
# train
best_auc = 0.
best_w=w
best_v=v
best_w_0=w_0
overfitting = False
print 'training:'
fo = open(result_file, 'a')
for round in range(1, train_rounds+1):
start_time = time.time()
fi = open(train_file, 'r')
line_num = 0
train_data = []
while True:
line = fi.readline().strip()
if len(line) > 0:
line_num = (line_num + 1) % buffer_num
train_data.append(one_data_y_x(line))
if line_num == 0 or len(line) == 0:
for data in train_data:
y = data[0]
x = data[1]
# train one data
(p, vsum) = pred(x)
d = y - p
w_0 = w_0 * (1 - weight_decay) + learning_rate * d
for (feat, val) in x:
w[feat] = w[feat] * (1 - weight_decay) + learning_rate * d * val
for (feat, val) in x:
v[feat] = v[feat] * (1 - v_weight_decay) + learning_rate * d * (val * vsum - v[feat] * val * val)
train_data = []
if len(line) == 0:
break
fi.close()
train_time = time.time() - start_time
train_min = int(train_time / 60)
train_sec = int(train_time % 60)
# test for this round
y = []
yp = []
fi = open(test_file, 'r')
for line in fi:
data = one_data_y_x(line)
clk = data[0]
pclk = pred(data[1])[0]
y.append(clk)
yp.append(pclk)
fi.close()
auc = roc_auc_score(y, yp)
rmse = math.sqrt(mean_squared_error(y, yp))
print '%d\t%.8f\t%.8f\t%dm%ds' % (round, auc, rmse, train_min, train_sec)
fo.write('%d\t%.8f\t%.8f\t%dm%ds\n' % (round, auc, rmse, train_min, train_sec))
fo.flush()
if overfitting and auc < best_auc:
print 'rewriting ' + trainlog_file + ' into ' + traindl_file
rewrite_train_test(trainlog_file, traindl_file)
print 'rewriting ' + testlog_file + ' into ' + testdl_file
rewrite_train_test(testlog_file, testdl_file)
print 'output model into ' + model_file
output_model(model_file)
break # stop training when overfitting two rounds already
if auc > best_auc:
best_auc = auc
best_w=w
best_v=v
best_w_0=w_0
overfitting = False
else:
overfitting = True
ut.save_weights("fm_train_"+advertiser+".p",pred_all(train_file,best_w,best_v,best_w_0))
ut.save_weights("fm_test_"+advertiser+".p",pred_all(test_file,best_w,best_v,best_w_0))
fo.close()