forked from fulifeng/Adv-ALSTM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpred_lstm.py
703 lines (640 loc) · 26.9 KB
/
pred_lstm.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
import argparse
import copy
import numpy as np
import os
import random
from sklearn.utils import shuffle
import tensorflow as tf
from time import time
try:
from tensorflow.python.ops.nn_ops import leaky_relu
except ImportError:
from tensorflow.python.framework import ops
from tensorflow.python.ops import math_ops
def leaky_relu(features, alpha=0.2, name=None):
with ops.name_scope(name, "LeakyRelu", [features, alpha]):
features = ops.convert_to_tensor(features, name="features")
alpha = ops.convert_to_tensor(alpha, name="alpha")
return math_ops.maximum(alpha * features, features)
from load import load_cla_data
from evaluator import evaluate
class AWLSTM:
def __init__(self, data_path, model_path, model_save_path, parameters, steps=1, epochs=50,
batch_size=256, gpu=False, tra_date='2014-01-02',
val_date='2015-08-03', tes_date='2015-10-01', att=0, hinge=0,
fix_init=0, adv=0, reload=0):
self.data_path = data_path
self.model_path = model_path
self.model_save_path = model_save_path
# model parameters
self.paras = copy.copy(parameters)
# training parameters
self.steps = steps
self.epochs = epochs
self.batch_size = batch_size
self.gpu = gpu
if att == 1:
self.att = True
else:
self.att = False
if hinge == 1:
self.hinge = True
else:
self.hinge = False
if fix_init == 1:
self.fix_init = True
else:
self.fix_init = False
if adv == 1:
self.adv_train = True
else:
self.adv_train = False
if reload == 1:
self.reload = True
else:
self.reload = False
# load data
self.tra_date = tra_date
self.val_date = val_date
self.tes_date = tes_date
self.tra_pv, self.tra_wd, self.tra_gt, \
self.val_pv, self.val_wd, self.val_gt, \
self.tes_pv, self.tes_wd, self.tes_gt = load_cla_data(
self.data_path,
tra_date, val_date, tes_date, seq=self.paras['seq']
)
self.fea_dim = self.tra_pv.shape[2]
def get_batch(self, sta_ind=None):
if sta_ind is None:
sta_ind = random.randrange(0, self.tra_pv.shape[0])
if sta_ind + self.batch_size < self.tra_pv.shape[0]:
end_ind = sta_ind + self.batch_size
else:
sta_ind = self.tra_pv.shape[0] - self.batch_size
end_ind = self.tra_pv.shape[0]
return self.tra_pv[sta_ind:end_ind, :, :], \
self.tra_wd[sta_ind:end_ind, :, :], \
self.tra_gt[sta_ind:end_ind, :]
def adv_part(self, adv_inputs):
print('adversial part')
if self.att:
with tf.variable_scope('pre_fc'):
self.fc_W = tf.get_variable(
'weights', dtype=tf.float32,
shape=[self.paras['unit'] * 2, 1],
initializer=tf.glorot_uniform_initializer()
)
self.fc_b = tf.get_variable(
'biases', dtype=tf.float32,
shape=[1, ],
initializer=tf.zeros_initializer()
)
if self.hinge:
pred = tf.nn.bias_add(
tf.matmul(adv_inputs, self.fc_W), self.fc_b
)
else:
pred = tf.nn.sigmoid(
tf.nn.bias_add(tf.matmul(self.fea_con, self.fc_W),
self.fc_b)
)
else:
# One hidden layer
if self.hinge:
pred = tf.layers.dense(
adv_inputs, units=1, activation=None,
name='pre_fc',
kernel_initializer=tf.glorot_uniform_initializer()
)
else:
pred = tf.layers.dense(
adv_inputs, units=1, activation=tf.nn.sigmoid,
name='pre_fc',
kernel_initializer=tf.glorot_uniform_initializer()
)
return pred
def construct_graph(self):
print('is pred_lstm')
if self.gpu == True:
device_name = '/gpu:0'
else:
device_name = '/cpu:0'
print('device name:', device_name)
with tf.device(device_name):
tf.reset_default_graph()
if self.fix_init:
tf.set_random_seed(123456)
self.gt_var = tf.placeholder(tf.float32, [None, 1])
self.pv_var = tf.placeholder(
tf.float32, [None, self.paras['seq'], self.fea_dim]
)
self.wd_var = tf.placeholder(
tf.float32, [None, self.paras['seq'], 5]
)
self.lstm_cell = tf.contrib.rnn.BasicLSTMCell(
self.paras['unit']
)
# self.outputs, _ = tf.nn.dynamic_rnn(
# # self.outputs, _ = tf.nn.static_rnn(
# self.lstm_cell, self.pv_var, dtype=tf.float32
# # , initial_state=ini_sta
# )
self.in_lat = tf.layers.dense(
self.pv_var, units=self.fea_dim,
activation=tf.nn.tanh, name='in_fc',
kernel_initializer=tf.glorot_uniform_initializer()
)
self.outputs, _ = tf.nn.dynamic_rnn(
# self.outputs, _ = tf.nn.static_rnn(
self.lstm_cell, self.in_lat, dtype=tf.float32
# , initial_state=ini_sta
)
self.loss = 0
self.adv_loss = 0
self.l2_norm = 0
if self.att:
with tf.variable_scope('lstm_att') as scope:
self.av_W = tf.get_variable(
name='att_W', dtype=tf.float32,
shape=[self.paras['unit'], self.paras['unit']],
initializer=tf.glorot_uniform_initializer()
)
self.av_b = tf.get_variable(
name='att_h', dtype=tf.float32,
shape=[self.paras['unit']],
initializer=tf.zeros_initializer()
)
self.av_u = tf.get_variable(
name='att_u', dtype=tf.float32,
shape=[self.paras['unit']],
initializer=tf.glorot_uniform_initializer()
)
self.a_laten = tf.tanh(
tf.tensordot(self.outputs, self.av_W,
axes=1) + self.av_b)
self.a_scores = tf.tensordot(self.a_laten, self.av_u,
axes=1,
name='scores')
self.a_alphas = tf.nn.softmax(self.a_scores, name='alphas')
self.a_con = tf.reduce_sum(
self.outputs * tf.expand_dims(self.a_alphas, -1), 1)
self.fea_con = tf.concat(
[self.outputs[:, -1, :], self.a_con],
axis=1)
print('adversarial scope')
# training loss
self.pred = self.adv_part(self.fea_con)
if self.hinge:
self.loss = tf.losses.hinge_loss(self.gt_var, self.pred)
else:
self.loss = tf.losses.log_loss(self.gt_var, self.pred)
self.adv_loss = self.loss * 0
# adversarial loss
if self.adv_train:
print('gradient noise')
self.delta_adv = tf.gradients(self.loss, [self.fea_con])[0]
tf.stop_gradient(self.delta_adv)
self.delta_adv = tf.nn.l2_normalize(self.delta_adv, axis=1)
self.adv_pv_var = self.fea_con + \
self.paras['eps'] * self.delta_adv
scope.reuse_variables()
self.adv_pred = self.adv_part(self.adv_pv_var)
if self.hinge:
self.adv_loss = tf.losses.hinge_loss(self.gt_var, self.adv_pred)
else:
self.adv_loss = tf.losses.log_loss(self.gt_var, self.adv_pred)
else:
with tf.variable_scope('lstm_att') as scope:
print('adversarial scope')
# training loss
self.pred = self.adv_part(self.outputs[:, -1, :])
if self.hinge:
self.loss = tf.losses.hinge_loss(self.gt_var, self.pred)
else:
self.loss = tf.losses.log_loss(self.gt_var, self.pred)
self.adv_loss = self.loss * 0
# adversarial loss
if self.adv_train:
print('gradient noise')
self.delta_adv = tf.gradients(self.loss, [self.outputs[:, -1, :]])[0]
tf.stop_gradient(self.delta_adv)
self.delta_adv = tf.nn.l2_normalize(self.delta_adv,
axis=1)
self.adv_pv_var = self.outputs[:, -1, :] + \
self.paras['eps'] * self.delta_adv
scope.reuse_variables()
self.adv_pred = self.adv_part(self.adv_pv_var)
if self.hinge:
self.adv_loss = tf.losses.hinge_loss(self.gt_var,
self.adv_pred)
else:
self.adv_loss = tf.losses.log_loss(self.gt_var,
self.adv_pred)
# regularizer
self.tra_vars = tf.trainable_variables('lstm_att/pre_fc')
for var in self.tra_vars:
self.l2_norm += tf.nn.l2_loss(var)
self.obj_func = self.loss + \
self.paras['alp'] * self.l2_norm + \
self.paras['bet'] * self.adv_loss
self.optimizer = tf.train.AdamOptimizer(
learning_rate=self.paras['lr']
).minimize(self.obj_func)
def get_latent_rep(self):
self.construct_graph()
sess = tf.Session()
saver = tf.train.Saver()
if self.reload:
saver.restore(sess, self.model_path)
print('model restored')
else:
sess.run(tf.global_variables_initializer())
bat_count = self.tra_pv.shape[0] // self.batch_size
if not (self.tra_pv.shape[0] % self.batch_size == 0):
bat_count += 1
tr_lat_rep = np.zeros([bat_count * self.batch_size, self.paras['unit'] * 2],
dtype=np.float32)
tr_gt = np.zeros([bat_count * self.batch_size, 1], dtype=np.float32)
for j in range(bat_count):
pv_b, wd_b, gt_b = self.get_batch(j * self.batch_size)
feed_dict = {
self.pv_var: pv_b,
self.wd_var: wd_b,
self.gt_var: gt_b
}
lat_rep, cur_obj, cur_loss, cur_l2, cur_al = sess.run(
(self.fea_con, self.obj_func, self.loss, self.l2_norm,
self.adv_loss),
feed_dict
)
print(lat_rep.shape)
tr_lat_rep[j * self.batch_size: (j + 1) * self.batch_size, :] = lat_rep
tr_gt[j * self.batch_size: (j + 1) * self.batch_size,:] = gt_b
# test on validation set
feed_dict = {
self.pv_var: self.val_pv,
self.wd_var: self.val_wd,
self.gt_var: self.val_gt
}
val_loss, val_lat_rep, val_pre = sess.run(
(self.loss, self.fea_con, self.pred), feed_dict
)
cur_val_perf = evaluate(val_pre, self.val_gt, self.hinge)
print('\tVal per:', cur_val_perf)
sess.close()
tf.reset_default_graph()
np.savetxt(self.model_save_path + '_val_lat_rep.csv', val_lat_rep)
np.savetxt(self.model_save_path + '_tr_lat_rep.csv', tr_lat_rep)
np.savetxt(self.model_save_path + '_val_gt.csv', self.val_gt)
np.savetxt(self.model_save_path + '_tr_gt.csv', tr_gt)
def predict_adv(self):
self.construct_graph()
sess = tf.Session()
saver = tf.train.Saver()
if self.reload:
saver.restore(sess, self.model_path)
print('model restored')
else:
sess.run(tf.global_variables_initializer())
bat_count = self.tra_pv.shape[0] // self.batch_size
if not (self.tra_pv.shape[0] % self.batch_size == 0):
bat_count += 1
tra_perf = None
adv_perf = None
for j in range(bat_count):
pv_b, wd_b, gt_b = self.get_batch(j * self.batch_size)
feed_dict = {
self.pv_var: pv_b,
self.wd_var: wd_b,
self.gt_var: gt_b
}
cur_pre, cur_adv_pre, cur_obj, cur_loss, cur_l2, cur_al = sess.run(
(self.pred, self.adv_pred, self.obj_func, self.loss, self.l2_norm,
self.adv_loss),
feed_dict
)
cur_tra_perf = evaluate(cur_pre, gt_b, self.hinge)
cur_adv_perf = evaluate(cur_adv_pre, gt_b, self.hinge)
if tra_perf is None:
tra_perf = copy.copy(cur_tra_perf)
else:
for metric in tra_perf.keys():
tra_perf[metric] = tra_perf[metric] + cur_tra_perf[metric]
if adv_perf is None:
adv_perf = copy.copy(cur_adv_perf)
else:
for metric in adv_perf.keys():
adv_perf[metric] = adv_perf[metric] + cur_adv_perf[metric]
for metric in tra_perf.keys():
tra_perf[metric] = tra_perf[metric] / bat_count
adv_perf[metric] = adv_perf[metric] / bat_count
print('Clean samples performance:', tra_perf)
print('Adversarial samples performance:', adv_perf)
# test on validation set
feed_dict = {
self.pv_var: self.val_pv,
self.wd_var: self.val_wd,
self.gt_var: self.val_gt
}
val_loss, val_pre, val_adv_pre = sess.run(
(self.loss, self.pred, self.adv_pred), feed_dict
)
cur_valid_perf = evaluate(val_pre, self.val_gt, self.hinge)
print('\tVal per clean:', cur_valid_perf)
adv_valid_perf = evaluate(val_adv_pre, self.val_gt, self.hinge)
print('\tVal per adversarial:', adv_valid_perf)
# test on testing set
feed_dict = {
self.pv_var: self.tes_pv,
self.wd_var: self.tes_wd,
self.gt_var: self.tes_gt
}
test_loss, tes_pre, tes_adv_pre = sess.run(
(self.loss, self.pred, self.adv_pred), feed_dict
)
cur_test_perf = evaluate(tes_pre, self.tes_gt, self.hinge)
print('\tTest per clean:', cur_test_perf)
adv_test_perf = evaluate(tes_adv_pre, self.tes_gt, self.hinge)
print('\tTest per adversarial:', adv_test_perf)
sess.close()
tf.reset_default_graph()
def predict_record(self):
self.construct_graph()
sess = tf.Session()
saver = tf.train.Saver()
if self.reload:
saver.restore(sess, self.model_path)
print('model restored')
else:
sess.run(tf.global_variables_initializer())
# test on validation set
feed_dict = {
self.pv_var: self.val_pv,
self.wd_var: self.val_wd,
self.gt_var: self.val_gt
}
val_loss, val_pre = sess.run(
(self.loss, self.pred), feed_dict
)
cur_valid_perf = evaluate(val_pre, self.val_gt, self.hinge)
print('\tVal per:', cur_valid_perf, '\tVal loss:', val_loss)
np.savetxt(self.model_save_path + '_val_prediction.csv', val_pre)
# test on testing set
feed_dict = {
self.pv_var: self.tes_pv,
self.wd_var: self.tes_wd,
self.gt_var: self.tes_gt
}
test_loss, tes_pre = sess.run(
(self.loss, self.pred), feed_dict
)
cur_test_perf = evaluate(tes_pre, self.tes_gt, self.hinge)
print('\tTest per:', cur_test_perf, '\tTest loss:', test_loss)
np.savetxt(self.model_save_path + '_tes_prediction.csv', tes_pre)
sess.close()
tf.reset_default_graph()
def test(self):
self.construct_graph()
sess = tf.Session()
saver = tf.train.Saver()
if self.reload:
saver.restore(sess, self.model_path)
print('model restored')
else:
sess.run(tf.global_variables_initializer())
# test on validation set
feed_dict = {
self.pv_var: self.val_pv,
self.wd_var: self.val_wd,
self.gt_var: self.val_gt
}
val_loss, val_pre = sess.run(
(self.loss, self.pred), feed_dict
)
cur_valid_perf = evaluate(val_pre, self.val_gt, self.hinge)
print('\tVal per:', cur_valid_perf, '\tVal loss:', val_loss)
# test on testing set
feed_dict = {
self.pv_var: self.tes_pv,
self.wd_var: self.tes_wd,
self.gt_var: self.tes_gt
}
test_loss, tes_pre = sess.run(
(self.loss, self.pred), feed_dict
)
cur_test_perf = evaluate(tes_pre, self.tes_gt, self.hinge)
print('\tTest per:', cur_test_perf, '\tTest loss:', test_loss)
sess.close()
tf.reset_default_graph()
def train(self, tune_para=False):
self.construct_graph()
sess = tf.Session()
saver = tf.train.Saver()
if self.reload:
saver.restore(sess, self.model_path)
print('model restored')
else:
sess.run(tf.global_variables_initializer())
best_valid_pred = np.zeros(self.val_gt.shape, dtype=float)
best_test_pred = np.zeros(self.tes_gt.shape, dtype=float)
best_valid_perf = {
'acc': 0, 'mcc': -2
}
best_test_perf = {
'acc': 0, 'mcc': -2
}
bat_count = self.tra_pv.shape[0] // self.batch_size
if not (self.tra_pv.shape[0] % self.batch_size == 0):
bat_count += 1
for i in range(self.epochs):
t1 = time()
# first_batch = True
tra_loss = 0.0
tra_obj = 0.0
l2 = 0.0
tra_adv = 0.0
for j in range(bat_count):
pv_b, wd_b, gt_b = self.get_batch(j * self.batch_size)
feed_dict = {
self.pv_var: pv_b,
self.wd_var: wd_b,
self.gt_var: gt_b
}
cur_pre, cur_obj, cur_loss, cur_l2, cur_al, batch_out = sess.run(
(self.pred, self.obj_func, self.loss, self.l2_norm, self.adv_loss,
self.optimizer),
feed_dict
)
tra_loss += cur_loss
tra_obj += cur_obj
l2 += cur_l2
tra_adv += cur_al
print('----->>>>> Training:', tra_obj / bat_count,
tra_loss / bat_count, l2 / bat_count, tra_adv / bat_count)
if not tune_para:
tra_loss = 0.0
tra_obj = 0.0
l2 = 0.0
tra_acc = 0.0
for j in range(bat_count):
pv_b, wd_b, gt_b = self.get_batch(
j * self.batch_size)
feed_dict = {
self.pv_var: pv_b,
self.wd_var: wd_b,
self.gt_var: gt_b
}
cur_obj, cur_loss, cur_l2, cur_pre = sess.run(
(self.obj_func, self.loss, self.l2_norm, self.pred),
feed_dict
)
cur_tra_perf = evaluate(cur_pre, gt_b, self.hinge)
tra_loss += cur_loss
l2 += cur_l2
tra_obj += cur_obj
tra_acc += cur_tra_perf['acc']
print('Training:', tra_obj / bat_count, tra_loss / bat_count,
l2 / bat_count, '\tTrain per:', tra_acc / bat_count)
# test on validation set
feed_dict = {
self.pv_var: self.val_pv,
self.wd_var: self.val_wd,
self.gt_var: self.val_gt
}
val_loss, val_pre = sess.run(
(self.loss, self.pred), feed_dict
)
cur_valid_perf = evaluate(val_pre, self.val_gt, self.hinge)
print('\tVal per:', cur_valid_perf, '\tVal loss:', val_loss)
# test on testing set
feed_dict = {
self.pv_var: self.tes_pv,
self.wd_var: self.tes_wd,
self.gt_var: self.tes_gt
}
test_loss, tes_pre = sess.run(
(self.loss, self.pred), feed_dict
)
cur_test_perf = evaluate(tes_pre, self.tes_gt, self.hinge)
print('\tTest per:', cur_test_perf, '\tTest loss:', test_loss)
if cur_valid_perf['acc'] > best_valid_perf['acc']:
best_valid_perf = copy.copy(cur_valid_perf)
best_valid_pred = copy.copy(val_pre)
best_test_perf = copy.copy(cur_test_perf)
best_test_pred = copy.copy(tes_pre)
if not tune_para:
saver.save(sess, self.model_save_path)
self.tra_pv, self.tra_wd, self.tra_gt = shuffle(
self.tra_pv, self.tra_wd, self.tra_gt, random_state=0
)
t4 = time()
print('epoch:', i, ('time: %.4f ' % (t4 - t1)))
print('\nBest Valid performance:', best_valid_perf)
print('\tBest Test performance:', best_test_perf)
sess.close()
tf.reset_default_graph()
if tune_para:
return best_valid_perf, best_test_perf
return best_valid_pred, best_test_pred
def update_model(self, parameters):
data_update = False
if not parameters['seq'] == self.paras['seq']:
data_update = True
for name, value in parameters.items():
self.paras[name] = value
if data_update:
self.tra_pv, self.tra_wd, self.tra_gt, \
self.val_pv, self.val_wd, self.val_gt, \
self.tes_pv, self.tes_wd, self.tes_gt = load_cla_data(
self.data_path,
self.tra_date, self.val_date, self.tes_date, seq=self.paras['seq']
)
return True
if __name__ == '__main__':
desc = 'the lstm model'
parser = argparse.ArgumentParser(description=desc)
parser.add_argument('-p', '--path', help='path of pv data', type=str,
default='./data/stocknet-dataset/price/ourpped')
parser.add_argument('-l', '--seq', help='length of history', type=int,
default=5)
parser.add_argument('-u', '--unit', help='number of hidden units in lstm',
type=int, default=32)
parser.add_argument('-l2', '--alpha_l2', type=float, default=1e-2,
help='alpha for l2 regularizer')
parser.add_argument('-la', '--beta_adv', type=float, default=1e-2,
help='beta for adverarial loss')
parser.add_argument('-le', '--epsilon_adv', type=float, default=1e-2,
help='epsilon to control the scale of noise')
parser.add_argument('-s', '--step', help='steps to make prediction',
type=int, default=1)
parser.add_argument('-b', '--batch_size', help='batch size', type=int,
default=1024)
parser.add_argument('-e', '--epoch', help='epoch', type=int, default=150)
parser.add_argument('-r', '--learning_rate', help='learning rate',
type=float, default=1e-2)
parser.add_argument('-g', '--gpu', type=int, default=0, help='use gpu')
parser.add_argument('-q', '--model_path', help='path to load model',
type=str, default='./saved_model/acl18_alstm/exp')
parser.add_argument('-qs', '--model_save_path', type=str, help='path to save model',
default='./tmp/model')
parser.add_argument('-o', '--action', type=str, default='train',
help='train, test, pred')
parser.add_argument('-m', '--model', type=str, default='pure_lstm',
help='pure_lstm, di_lstm, att_lstm, week_lstm, aw_lstm')
parser.add_argument('-f', '--fix_init', type=int, default=0,
help='use fixed initialization')
parser.add_argument('-a', '--att', type=int, default=1,
help='use attention model')
parser.add_argument('-w', '--week', type=int, default=0,
help='use week day data')
parser.add_argument('-v', '--adv', type=int, default=0,
help='adversarial training')
parser.add_argument('-hi', '--hinge_lose', type=int, default=1,
help='use hinge lose')
parser.add_argument('-rl', '--reload', type=int, default=0,
help='use pre-trained parameters')
args = parser.parse_args()
print(args)
parameters = {
'seq': int(args.seq),
'unit': int(args.unit),
'alp': float(args.alpha_l2),
'bet': float(args.beta_adv),
'eps': float(args.epsilon_adv),
'lr': float(args.learning_rate)
}
if 'stocknet' in args.path:
tra_date = '2014-01-02'
val_date = '2015-08-03'
tes_date = '2015-10-01'
elif 'kdd17' in args.path:
tra_date = '2007-01-03'
val_date = '2015-01-02'
tes_date = '2016-01-04'
else:
print('unexpected path: %s' % args.path)
exit(0)
pure_LSTM = AWLSTM(
data_path=args.path,
model_path=args.model_path,
model_save_path=args.model_save_path,
parameters=parameters,
steps=args.step,
epochs=args.epoch, batch_size=args.batch_size, gpu=args.gpu,
tra_date=tra_date, val_date=val_date, tes_date=tes_date, att=args.att,
hinge=args.hinge_lose, fix_init=args.fix_init, adv=args.adv,
reload=args.reload
)
if args.action == 'train':
pure_LSTM.train()
elif args.action == 'test':
pure_LSTM.test()
elif args.action == 'report':
for i in range(5):
pure_LSTM.train()
elif args.action == 'pred':
pure_LSTM.predict_record()
elif args.action == 'adv':
pure_LSTM.predict_adv()
elif args.action == 'latent':
pure_LSTM.get_latent_rep()