This repository has been archived by the owner on Jun 23, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.py
2778 lines (2347 loc) · 118 KB
/
core.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
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import time
import copy
import inspect
import matplotlib
# matplotlib.use('Agg')
from matplotlib import pyplot as plt
from matplotlib import colors as mcolors
from matplotlib.animation import FuncAnimation
import multiprocessing as mp
MP_CONTEXT = mp.get_context('spawn')
import tensorflow as tf
from tensorflow.python import debug as tf_debug
from tensorflow.python.keras.engine.base_layer import Layer
from tensorflow.python.keras.layers.recurrent import RNN
from tensorflow.python.keras.layers import Dense
from tensorflow.python.framework import tensor_shape
from tensorflow.python.framework import ops
from tensorflow.python.keras import regularizers
from tensorflow.python.keras import activations
from tensorflow.python.keras import initializers
from tensorflow.python.keras import constraints
from tensorflow.python.keras import optimizers
from tensorflow.python.keras.engine import training_arrays
from tensorflow.python.keras.utils import tf_utils
from tensorflow.python.ops import math_ops
import numpy as np
import utils
import colors
import constants
import trading_data as tdata
import log as logging
LOG = logging.getLogger(__name__)
sess = utils.get_session()
session = utils.get_session()
SESS = utils.get_session()
SESSION = utils.get_session()
once = True
SENTINEL = utils.sentinel_marker()
tf.keras.backend.set_epsilon(1e-9)
hacking = 1
def do_guess_helper(step, direction, start_price, nb_plays, activation, sign, prev_states, weights, delta=0.001):
'''
Parameters:
--------------------
step: current attemping step
direction: in which direction the price should change
start_price: where the price start to do guessing
nb_plays: the number of plays attend in this transaction
activation: the type of activation used during prediction, can be 'None', 'tanh', 'relu'
sign: -1/+1, to correct the result of noise
prev_states: a list of previous state, see the architecture of Operator
weights: the weights of this trained neural network
delta: the minimum step should increase to find a root
Returns:
--------------------
guess_price: the price guess, scalar
predict_noise: the noise correpsonding to guess price, scalar
'''
predict_noise_list = []
guess = start_price + direction * step * delta
# LOG.debug("--------------------------------------------------------------------------------");
# LOG.debug("prev_states: {}".format(prev_states))
for i in range(nb_plays):
prev_state = prev_states[i]
p = phi(weights[0][i] * guess - prev_state) + prev_state
pp = weights[1][i] * p + weights[2][i]
if activation is None:
pass
elif activation == 'tanh':
pp = np.tanh(pp)
elif activation == 'relu':
pp = pp * (pp > 0)
elif activation == 'elu':
pp1 = (pp >= 0) * pp
pp2 = (pp < 0) * pp
pp2 = np.exp(pp2) - 1
pp = pp1 + pp2
elif activation == 'softmax':
pp = np.log(1 + np.exp(pp))
else:
raise Exception("not support for activation {}".format(colors.red(activation)))
ppp = (weights[3][i] * pp).sum() + weights[4][i]
predict_noise_list.append(ppp[0])
predict_noise = sign * sum(predict_noise_list) / nb_plays
return guess, predict_noise
def do_guess_seq(start,
seq,
prev_gt_price,
curr_gt_price,
prev_gt_prediction,
curr_gt_prediction,
mu,
sigma,
nb_plays,
activation,
sign,
individual_p_list,
weights,
hysteresis_info,
max_iteration=2000):
'''
Parameters:
--------------------
start: the start position of the prices going to do prediction
seq: the length of prices going to do prediction
prev_gt_price: previous ground-truth price
curr_gt_price: current ground-truth price
prev_gt_noise: previous ground-truth noise
curr_gt_noise: current ground-truth noise
mu: the empirical mean of prediction dataset(noise set)
sigma: the empirical standard derivation of prediction dataset(noise set)
nb_plays: the number of plays attend in this transaction
activation: the type of activation used during prediction, can be 'None', 'tanh', 'relu'
sign: -1/+1, to correct the result of noise
individual_p_list: a list of operator outputs, mainly we need to track the previous state
weights: the weights of this trained neural network
hysteresis_info: information collected for ploting the internal behaviours during each transaction
max_iteration: the max iterations during trying to find a root for the price
Returns:
--------------------
guess_price_seq: a list of guess price, the length of it is equal to `seq`
'''
logger_string1 = "Step: {}, true_price: {:.5f}, guess price: {:.5f}, guess noise: {:.5f}, generated noise: {:.5f}, true noise: {:.5f}, prev true noise: {:.5f}, curr_diff: {:.5f}, prev_diff: {:.5f}, direction: {}, delta: {}, mu: {}, sigma {}"
logger_string2 = "Step: {}, true_price: {:.5f}, guess price: {:.5f}, guess noise: {:.5f}, generated noise: {:.5f}, true noise: {:.5f}, curr_diff: {:.5f}, prev_diff: {:.5f}, direction: {}, delta: {}, mu: {}, sigma: {}"
delta = 0.001
####################################################################################################
# guess_price_seq: the first value in it is the start point of price in prediction #
# predict_noise_seq: the first value in it is the start point of gt-noise in prediction #
####################################################################################################
individual_p_list = copy.deepcopy(individual_p_list)
LOG.debug("Before do_guess_helper, len(individual_p_list): {}, len(individual_p_list[0]): {}".format(len(individual_p_list), len(individual_p_list[0])))
guess_price_seq = [prev_gt_price]
predict_noise_seq = [prev_gt_prediction]
interval = 0
while interval < seq:
k = start + interval
bk = np.random.normal(loc=mu, scale=sigma) + predict_noise_seq[-1]
# bk = curr_gt_prediction
# always predict noise at [-sigma] and [sigma]
# global hacking
# bk = 110 * hacking
# hacking = - hacking
if bk > predict_noise_seq[-1]:
direction = -1
elif bk < predict_noise_seq[-1]:
direction = +1
else:
direction = 0
step = 0
guess_hysteresis_list = [(guess_price_seq[-1], predict_noise_seq[-1])]
prev_states = [individual_p_list[i][-1] for i in range(nb_plays)]
guess, guess_noise = do_guess_helper(step, direction, guess_price_seq[-1], nb_plays, activation, sign, prev_states, weights)
if np.allclose(predict_noise_seq[-1], guess_noise) is False:
# sanity checking
LOG.error("predict_noise_seq[-1] is: {}, guess_noise is: {}, they should be the same".format(predict_noise_seq[-1], guess_noise)),
# import ipdb; ipdb.set_trace()
prev_diff, curr_diff = None, guess_noise - bk
good_guess = False
while step <= max_iteration:
step += 1
prev_diff = curr_diff
guess, guess_noise = do_guess_helper(step, direction, guess_price_seq[-1], nb_plays, activation, sign, prev_states, weights)
guess_hysteresis_list.append((guess, guess_noise))
curr_diff = guess_noise - bk
if np.abs(curr_diff) < 0.01 or curr_diff * prev_diff < 0:
LOG.debug(colors.yellow(logger_string1.format(step, float(curr_gt_price), float(guess), float(guess_noise), float(bk), float(curr_gt_prediction), float(prev_gt_prediction), float(curr_diff), float(prev_diff), direction,
delta, mu, sigma)))
good_guess = True
break
LOG.debug(logger_string2.format(step, float(curr_gt_price), float(guess), float(guess_noise), float(bk), float(curr_gt_prediction), float(curr_diff), float(prev_diff), direction, delta, mu, sigma))
#########################################################################################################################
# hysteresis_info: #
# guess_hysteresis_list -> hysteresis_info[0]: a list of (price, noise) tuples #
# original_prediction[k-1] -> hysteresis_info[1]: the ground truth of noise in previous step #
# original_prediction[k] -> hysteresis_info[2]: the ground truth of noise in current step #
# bk -> hysteresis_info[3]: the noise generated from random walk #
# price[k-1] -> hysteresis_info[4]: the ground truth of price in previous step #
# price[k] -> hysteresis_info[5]: the ground truth of price in current step #
#########################################################################################################################
hysteresis_info.append([guess_hysteresis_list, prev_gt_prediction, curr_gt_prediction, bk, prev_gt_price, curr_gt_price])
if good_guess is False:
LOG.warn(colors.red("Not a good guess"))
continue
guess_price_seq.append(guess)
predict_noise_seq.append(guess_noise)
for j in range(nb_plays):
p = phi(weights[0][j] * guess - individual_p_list[j][-1]) + individual_p_list[j][-1]
individual_p_list[j].append(p)
interval += 1
LOG.debug("After do_guess_helper, len(individual_p_list): {}, len(individual_p_list[0]): {}".format(len(individual_p_list), len(individual_p_list[0])))
return guess_price_seq[1:], bk
def repeat(k,
seq,
repeating,
prev_gt_price,
curr_gt_price,
prev_gt_prediction,
curr_gt_prediction,
mu,
sigma,
nb_plays,
activation,
sign,
operator_outputs,
weights,
ensemble,
real_mu,
real_sigma):
'''
Parameters:
--------------------
k: the index of the price starting to prediction
seq: the sequence of prices trying to predict
repeating: how many times this sequence should repeat
prev_gt_price: previous ground-truth price
curr_gt_price: current ground-truth price
prev_gt_noise: previous ground-truth noise
curr_gt_noise: current ground-truth noise
mu: the empirical mean of prediction dataset(noise set)
sigma: the empirical standard derivation of prediction dataset(noise set)
nb_plays: the number of plays attend in this transaction
activation: the type of activation used during prediction, can be 'None', 'tanh', 'relu'
sign: -1/+1, to correct the result of noise
operator_outputs: a list of operator outputs, mainly we need to track the previous state
weights: the weights of this trained neural network
Returns:
--------------------
guess_price_seq: the avearge of this guess price sequence.
'''
logger_string3 = "================ Guess k: {} successfully, predict price: {:.5f}, grouth-truth price: {:.5f} prev gt price: {:.5f}, std: {:.5f} ====================="
hysteresis_info = []
guess_price_seq_stack = []
individual_p_list = [[o[k-1]] for o in operator_outputs]
bk_list = []
for _ in range(repeating):
guess_price_seq, bk = do_guess_seq(k,
seq,
prev_gt_price,
curr_gt_price,
prev_gt_prediction,
curr_gt_prediction,
mu,
sigma,
nb_plays,
activation,
sign,
individual_p_list,
weights,
hysteresis_info)
bk_list.append(bk)
guess_price_seq_stack.append(guess_price_seq)
guess_price_seq_stack_ = np.array(guess_price_seq_stack)
bk_list_ = np.array(bk_list)
LOG.debug("guess_price_seq_stack_: {}".format(guess_price_seq_stack_))
LOG.debug("guess_price_seq_stack_.shape: {}".format(guess_price_seq_stack_.shape))
# LOG.debug("guess_price_seq_stack_.mean(): {}".format(guess_price_seq_stack_.mean()))
# LOG.debug("guess_price_seq_stack_.std(): {}".format(guess_price_seq_stack_.std()))
avg_guess = guess_price_seq_stack_.mean(axis=0)[-1]
LOG.debug(colors.red(logger_string3.format(k, float(avg_guess), float(curr_gt_price), float(prev_gt_price), float(guess_price_seq_stack_.std()))))
LOG.debug("********************************************************************************")
hysteresis_guess_list = []
for i, guess_hysteresis_list in enumerate(hysteresis_info):
hysteresis_guess_list += guess_hysteresis_list[0]
os.makedirs('./frames-mu-{}-sigma-{}-ensemble-17'.format(mu, sigma), exist_ok=True)
np.savetxt('./frames-mu-{}-sigma-{}-ensemble-17/guess-{}.csv'.format(mu, sigma, k), np.array(hysteresis_guess_list), fmt='%.3f', delimiter=',')
np.savetxt('./frames-mu-{}-sigma-{}-ensemble-17/guess-hnn-{}.csv'.format(mu, sigma, k), guess_hnn_lstm, fmt='%.3f', delimiter=',')
utils.plot_internal_transaction(hysteresis_info, k, predicted_price=float(avg_guess), mu=real_mu, sigma=real_sigma, guess_price_seq=guess_price_seq_stack_, bk_list=bk_list_, ensemble=ensemble)
return avg_guess
def wrapper_repeat(args):
k = args[0]
seq = args[1]
repeating = args[2]
prev_gt_price = args[3]
curr_gt_price = args[4]
prev_gt_prediction = args[5]
curr_gt_prediction = args[6]
mu = args[7]
sigma = args[8]
nb_plays = args[9]
activation = args[10]
sign = args[11]
operator_outputs = args[12]
weights = args[13]
ensemble = args[14]
real_mu = args[15]
real_sigma = args[16]
return repeat(k,
seq,
repeating,
prev_gt_price,
curr_gt_price,
prev_gt_prediction,
curr_gt_prediction,
mu,
sigma,
nb_plays,
activation,
sign,
operator_outputs,
weights,
ensemble,
real_mu,
real_sigma)
def phi(x, width=1.0):
if x[0] > (width/2.0):
return (x[0] - width/2.0)
elif x[0] < (-width/2.0):
return (x[0] + width/2.0)
else:
return float(0)
def Phi(x, width=1.0, weight=1.0):
'''
Phi(x) = x - width/2 , if x > width/2
= x + width/2 , if x < - width/2
= 0 , otherwise
'''
assert x.shape[0].value == 1 and x.shape[1].value == 1, "x must be a scalar"
ZEROS = tf.zeros(x.shape, dtype=tf.float32, name='zeros')
# _width = tf.constant([[width/2.0]], dtype=tf.float32)
_width = tf.constant([[width/2.0]], dtype=tf.float32)
r1 = tf.cond(tf.reduce_all(tf.less(x, -_width)), lambda: weight*(x + _width), lambda: ZEROS)
r2 = tf.cond(tf.reduce_all(tf.greater(x, _width)), lambda: weight*(x - _width), lambda: r1)
return r2
def LeakyPhi(x, width=1.0, alpha=0.001):
'''
TODO:
LeakyPhi(x) = x - width/2 , if x > width/2
= x + width/2 , if x < - width/2
= alpha , otherwise
'''
assert x.shape[0].value == 1 and x.shape[1].value == 1, "x must be a scalar"
ZEROS = tf.zeros(x.shape, dtype=tf.float32, name='zeros')
# _width = tf.constant([[width/2.0]], dtype=tf.float32)
_width = tf.constant([[width/2.0]], dtype=tf.float32)
r1 = tf.cond(tf.reduce_all(tf.less(x, -_width)), lambda: x + _width, lambda: ZEROS)
r2 = tf.cond(tf.reduce_all(tf.greater(x, _width)), lambda: x - _width, lambda: r1)
return r2
def gradient_operator(P, weights=None):
reshaped_P = tf.reshape(P, shape=(P.shape[0].value, -1))
diff_ = reshaped_P[:, 1:] - reshaped_P[:, :-1]
x0 = tf.slice(reshaped_P, [0, 0], [1, 1])
diff_ = tf.concat([x0, diff_], axis=1)
result = tf.cast(tf.abs(diff_) >= 1e-9, dtype=tf.float32) + 1e-5
# LOG.debug("Result.shape: {}".format(result.shape))
return tf.reshape(result * weights, shape=P.shape)
def jacobian(outputs, inputs):
jacobian_matrix = []
M = outputs.shape[1].value
for m in range(M):
# We iterate over the M elements of the output vector
grad_func = tf.gradients(outputs[0, m, 0], inputs)[0]
jacobian_matrix.append(tf.reshape(grad_func, shape=(M, )))
return ops.convert_to_tensor(jacobian_matrix, dtype=tf.float32)
def gradient_nonlinear_layer(fZ, weights=None, activation=None, reduce_sum=True):
LOG.debug("gradient nonlinear activation {}".format(colors.red(activation)))
_fZ = tf.reshape(fZ, shape=fZ.shape.as_list()[1:])
if activation is None:
partial_gradient = tf.keras.backend.ones(shape=_fZ.shape)
elif activation == 'tanh':
partial_gradient = (1.0 + _fZ) * (1.0 - _fZ)
elif activation == 'relu':
partial_gradient = tf.cast(_fZ >= 1e-9, dtype=tf.float32)
elif activation == 'elu':
a = tf.cast(_fZ >= 0, dtype=tf.float32)
b = tf.cast(_fZ < 0, dtype=tf.float32)
partial_gradient = a + b * (_fZ + 1)
elif activation == 'softmax':
partial_gradient = 1.0 - 1.0 / tf.math.exp(fZ)
else:
raise Exception("activation: {} not support".format(activation))
if reduce_sum is True:
gradient = tf.reduce_sum(partial_gradient * weights, axis=-1, keepdims=True)
else:
gradient = partial_gradient * weights
g = tf.reshape(gradient, shape=(fZ.shape.as_list()[:-1] + [gradient.shape[-1].value]))
return g
def gradient_linear_layer(weights, multiples=1, expand_dims=True):
if expand_dims is True:
return tf.expand_dims(tf.tile(tf.transpose(weights, perm=[1, 0]), multiples=[multiples, 1]), axis=0)
else:
return tf.tile(tf.transpose(weights, perm=[1, 0]), multiples=[multiples, 1])
def gradient_operator_nonlinear_layers(P,
fZ,
operator_weights,
nonlinear_weights,
activation,
debug=False,
inputs=None,
reduce_sum=True,
feed_dict=dict()):
if debug is True and inputs is not None:
LOG.debug(colors.red("Only use under unittest, not for real situation"))
J = jacobian(P, inputs)
g1 = tf.reshape(tf.reduce_sum(J, axis=0), shape=inputs.shape)
calc_g = gradient_operator(P, operator_weights)
utils.init_tf_variables()
J_result, calc_g_result = session.run([J, calc_g], feed_dict=feed_dict)
if not np.allclose(np.diag(J_result), calc_g_result.reshape(-1)):
LOG.error(colors.red("ERROR: gradient operator- and nonlinear- layers"))
import ipdb; ipdb.set_trace()
else:
g1 = gradient_operator(P, operator_weights)
g1 = tf.reshape(g1, shape=P.shape)
g2 = gradient_nonlinear_layer(fZ, nonlinear_weights, activation, reduce_sum=reduce_sum)
g3 = g1*g2
return g3
def gradient_all_layers(P,
fZ,
operator_weights,
nonlinear_weights,
linear_weights,
activation,
debug=False,
inputs=None,
feed_dict=dict()):
g1 = gradient_operator_nonlinear_layers(P, fZ,
operator_weights,
nonlinear_weights,
activation=activation,
debug=debug,
inputs=inputs,
reduce_sum=False,
feed_dict=feed_dict)
g2 = tf.expand_dims(tf.matmul(g1[0], linear_weights), axis=0)
return g2
def confusion_matrix(y_true, y_pred, labels=['increase', 'descrease']):
'''
# https://en.wikipedia.org/wiki/Confusion_matrix
confusion matrix is impolemented as following
| increase (truth) | descrease (truth) |
increase (pred) | | |
descrease (pred) | | |
'''
diff1 = ((y_true[1:] - y_true[:-1]) >= 0).tolist()
diff2 = ((y_pred[1:] - y_true[:-1]) >= 0).tolist()
confusion = np.zeros(4, dtype=np.int32)
for a, b in zip(diff1, diff2):
if a is True and b is True:
confusion[0] += 1
elif a is True and b is False:
confusion[2] += 1
elif a is False and b is True:
confusion[1] += 1
elif a is False and b is False:
confusion[3] += 1
return confusion.reshape([2, 2])
class PhiCell(Layer):
def __init__(self,
input_dim=1,
weight=1.0,
width=1.0,
hysteretic_func=Phi,
kernel_initializer='glorot_uniform',
kernel_regularizer=None,
activity_regularizer=None,
kernel_constraint="non_neg",
**kwargs):
self.debug = kwargs.pop("debug", False)
self.unroll = kwargs.pop('unittest', False)
super(PhiCell, self).__init__(
activity_regularizer=regularizers.get(activity_regularizer), **kwargs)
self._weight = weight
self._recurrent_weight = -1
self._width = width
self.units = 1
self.state_size = [1]
self.kernel_initializer = tf.keras.initializers.Constant(value=weight, dtype=tf.float32)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.hysteretic_func = hysteretic_func
self.input_dim = input_dim
self._timestep = 0
def build(self, input_shape):
if self.debug:
LOG.debug("Initialize *weight* as pre-defined: {} ....".format(self._weight))
self.kernel = tf.Variable([[self._weight]], name="weight", dtype=tf.float32)
else:
LOG.debug("Initialize *weight* randomly...")
assert self.units == 1, "Phi Cell unit must be equal to 1"
self.kernel = self.add_weight(
"weight",
shape=(1, 1),
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
dtype=tf.float32,
trainable=True)
# self._state = self.add_weight(
# "state",
# shape=(1, 1),
# initializer=self.kernel_initializer,
# regularizer=self.kernel_regularizer,
# constraint=self.kernel_constraint,
# dtype=tf.float32,
# trainable=True)
self.built = True
def call(self, inputs, states):
"""
Parameters:
----------------
inputs: `inputs` is a vector, the shape of inputs vector is like [1 * sequence length]
Here, we consider the length of sequence is the same as the batch-size.
state: `state` is randomly initialized, the shape of is [1 * 1]
"""
self._inputs = ops.convert_to_tensor(inputs, dtype=tf.float32)
# self._state = ops.convert_to_tensor(states[-1], dtype=tf.float32)
self._state = states[-1]
LOG.debug("PhiCellinputs.shape: {}".format(inputs.shape))
LOG.debug("PhiCell._inputs.shape: {}".format(self._inputs.shape))
LOG.debug("PhiCell._state.shape: {}".format(self._state.shape))
############### IMPL from Scratch #####################
# outputs_ = tf.multiply(self._inputs, self.kernel)
# outputs = [self._state]
# for i in range(outputs_.shape[-1].value):
# output = tf.add(Phi(tf.subtract(outputs_[0][i], outputs[-1]), self._width, 0.99), outputs[-1])
# outputs.append(output)
# outputs = ops.convert_to_tensor(outputs[1:], dtype=tf.float32)
# state = outputs[-1]
# outputs = tf.reshape(outputs, shape=self._inputs.shape)
# LOG.debug("before reshaping state.shape: {}".format(state.shape))
# state = tf.reshape(state, shape=(-1, 1))
# LOG.debug("after reshaping state.shape: {}".format(state.shape))
# return outputs, [state]
################ IMPL via RNN ###########################
def inner_steps(inputs, states):
# import ipdb; ipdb.set_trace()
print("inner timestep: ", self._timestep)
self._timestep += 1
LOG.debug("inputs: {}, states: {}".format(inputs, states))
outputs = Phi(inputs - states[-1], self._width, 1.0) + states[-1]
return outputs, [outputs]
# import ipdb; ipdb.set_trace()
self._inputs = tf.multiply(self._inputs, self.kernel)
inputs_ = tf.reshape(self._inputs, shape=(1, self._inputs.shape[0].value*self._inputs.shape[1].value, 1))
if isinstance(states, list) or isinstance(states, tuple):
self._states = ops.convert_to_tensor(states[-1], dtype=tf.float32)
else:
self._states = ops.convert_to_tensor(states, dtype=tf.float32)
assert self._state.shape.ndims == 2, colors.red("PhiCell states must be 2 dimensions")
# states_ = [tf.reshape(self._states, shape=self._states.shape.as_list())]
states_ = states
# import ipdb; ipdb.set_trace()
last_outputs_, outputs_, states_x = tf.keras.backend.rnn(inner_steps, inputs=inputs_, initial_states=states_, unroll=self.unroll)
LOG.debug("outputs_.shape: {}".format(outputs_))
LOG.debug("states_x.shape: {}".format(states_x))
print("timestep: ", self._timestep)
# import ipdb; ipdb.set_trace()
return outputs_, list(states_x)
class Operator(RNN):
def __init__(self,
weight=1.0,
width=1.0,
debug=False,
unittest=False):
cell = PhiCell(
weight=weight,
width=1.0,
debug=debug,
unittest=unittest)
unroll = True if unittest is True else False
super(Operator, self).__init__(
cell=cell,
return_sequences=True,
return_state=False,
stateful=True,
unroll=False)
def build(self, input_shape):
# import ipdb; ipdb.set_trace()
self._states = [self.add_weight(
name="states",
dtype=tf.float32,
initializer=tf.keras.initializers.Constant(value=0.0, dtype=tf.float32),
trainable=True,
shape=(1, 1))]
super(Operator, self).build(input_shape)
# if self.stateful:
# self.reset_states()
# self.built = True
def call(self, inputs, initial_state=None):
LOG.debug("Operator.inputs.shape: {}".format(inputs.shape))
output = super(Operator, self).call(inputs, initial_state=initial_state)
assert inputs.shape.ndims == 3, colors.red("ERROR: Input from Operator must be 3 dimensions")
shape = inputs.shape.as_list()
output_ = tf.reshape(output, shape=(shape[0], -1, 1))
return output_
@property
def kernel(self):
return self.cell.kernel
def reset_states(self, states=None):
if not self.stateful:
raise AttributeError('Layer must be stateful.')
batch_size = self.input_spec[0].shape[0]
if not batch_size:
raise ValueError('If a RNN is stateful, it needs to know '
'its batch size. Specify the batch size '
'of your input tensors: \n'
'- If using a Sequential model, '
'specify the batch size by passing '
'a `batch_input_shape` '
'argument to your first layer.\n'
'- If using the functional API, specify '
'the batch size by passing a '
'`batch_shape` argument to your Input layer.')
# initialize state if None
if self.states[0] is None:
self.states = [
tf.keras.backend.zeros([batch_size] + tensor_shape.as_shape(dim).as_list())
for dim in self.cell.state_size
]
elif states is None:
# import ipdb; ipdb.set_trace()
for state, dim in zip(self.states, self.cell.state_size):
tf.keras.backend.set_value(state,
np.zeros([batch_size] +
tensor_shape.as_shape(dim).as_list()))
else:
if not isinstance(states, (list, tuple)):
states = [states]
if len(states) != len(self.states):
raise ValueError('Layer ' + self.name + ' expects ' +
str(len(self.states)) + ' states, '
'but it received ' + str(len(states)) +
' state values. Input received: ' + str(states))
for index, (value, state) in enumerate(zip(states, self.states)):
dim = self.cell.state_size[index]
if value.shape != tuple([batch_size] +
tensor_shape.as_shape(dim).as_list()):
raise ValueError(
'State ' + str(index) + ' is incompatible with layer ' +
self.name + ': expected shape=' + str(
(batch_size, dim)) + ', found shape=' + str(value.shape))
# TODO(fchollet): consider batch calls to `set_value`.
tf.keras.backend.set_value(state, value)
def my_softmax(x):
return tf.math.log(1 + tf.math.exp(x))
class MyDense(Layer):
def __init__(self, units=1,
activation="tanh",
weight=1,
use_bias=True,
activity_regularizer=None,
kernel_initializer='glorot_uniform',
kernel_regularizer=None,
kernel_constraint=None,
bias_initializer='zeros',
bias_regularizer=None,
bias_constraint=None,
**kwargs):
self._debug = kwargs.pop("debug", False)
if '_init_kernel' in kwargs:
self._init_kernel = kwargs.pop("_init_kernel")
# self._init_kernel = 1.0
self._init_bias = kwargs.pop("_init_bias", 0)
super(MyDense, self).__init__(**kwargs)
self.units = units
self._weight = weight
if activation == 'softmax':
self.activation = my_softmax
else:
self.activation = activations.get(activation)
self.kernel_initializer = initializers.get(kernel_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
if use_bias is True:
self.bias_initializer = initializers.get(bias_initializer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.bias_constraint = constraints.get(bias_constraint)
self.use_bias = use_bias
def build(self, input_shape):
if self._debug:
LOG.debug("init mydense kernel/bias as pre-defined")
if hasattr(self, '_init_kernel'):
_init_kernel = np.array([[self._init_kernel for i in range(self.units)]])
else:
_init_kernel = np.random.uniform(low=0.0, high=1.5, size=self.units)
_init_kernel = _init_kernel.reshape([1, -1])
LOG.debug(colors.yellow("kernel: {}".format(_init_kernel)))
self.kernel = tf.Variable(_init_kernel, name="theta", dtype=tf.float32)
if self.use_bias is True:
# _init_bias = 0
_init_bias = self._init_bias
LOG.debug(colors.yellow("bias: {}".format(_init_bias)))
self.bias = tf.Variable(_init_bias, name="bias", dtype=tf.float32)
else:
self.kernel = self.add_weight(
"theta",
shape=(1, self.units),
initializer=self.kernel_initializer,
regularizer=self.kernel_regularizer,
constraint=self.kernel_constraint,
dtype=tf.float32,
trainable=True)
if self.use_bias:
self.bias = self.add_weight(
"bias",
shape=(1, self.units),
initializer=self.bias_initializer,
regularizer=self.bias_regularizer,
constraint=self.bias_constraint,
dtype=tf.float32,
trainable=True)
self.built = True
def call(self, inputs):
assert inputs.shape.ndims == 3
# XXX: double checked. it's correct in current model. no worried
outputs = inputs * self.kernel
if self.use_bias:
outputs += self.bias
if self.activation is not None:
outputs = self.activation(outputs)
return outputs
class MySimpleDense(Dense):
def __init__(self, **kwargs):
self._debug = kwargs.pop("debug", False)
self._init_bias = kwargs.pop("_init_bias", 0)
if '_init_kernel' in kwargs:
self._init_kernel = kwargs.pop("_init_kernel")
# self._init_kernel = 1.0
kwargs['activation'] = None
kwargs['kernel_constraint'] = None
super(MySimpleDense, self).__init__(**kwargs)
def build(self, input_shape):
assert self.units == 1
if self._debug is True:
LOG.debug("init mysimpledense kernel/bias as pre-defined")
if hasattr(self, '_init_kernel'):
_init_kernel = np.array([self._init_kernel for i in range(input_shape[-1].value)])
else:
_init_kernel = np.random.uniform(low=0.0, high=1.5, size=input_shape[-1].value)
_init_kernel = _init_kernel.reshape(-1, 1)
LOG.debug(colors.yellow("kernel: {}".format(_init_kernel)))
self.kernel = tf.Variable(_init_kernel, name="kernel", dtype=tf.float32)
if self.use_bias:
_init_bias = (self._init_bias,)
LOG.debug(colors.yellow("bias: {}".format(_init_bias)))
self.bias = tf.Variable(_init_bias, name="bias", dtype=tf.float32)
else:
super(MySimpleDense, self).build(input_shape)
self.built = True
def call(self, inputs):
return super(MySimpleDense, self).call(inputs)
class Play(object):
def __init__(self,
inputs=None,
units=1,
batch_size=1,
weight=1.0,
width=1.0,
debug=False,
activation="tanh",
loss="mse",
optimizer="adam",
network_type=constants.NetworkType.OPERATOR,
use_bias=True,
name="play",
timestep=1,
input_dim=1,
**kwargs):
np.random.seed(kwargs.pop("ensemble", 1))
self._weight = weight
self._width = width
self._debug = debug
self.activation = activation
self.loss = loss
self.optimizer = optimizer
self._play_timestep = timestep
self._play_batch_size = batch_size
self._play_input_dim = input_dim
self.units = units
self._network_type = network_type
self.built = False
self._need_compile = False
self.use_bias = use_bias
self._name = name
self._unittest = kwargs.pop('unittest', False)
def _make_batch_input_shape(self, inputs=None):
self._batch_input_shape = tf.TensorShape([1, self._play_timestep, self._play_input_dim])
def build(self, inputs=None):
if inputs is None and self._batch_input_shape is None:
raise Exception("Unknown input shape")
if inputs is not None:
_inputs = ops.convert_to_tensor(inputs, dtype=tf.float32)
if _inputs.shape.ndims == 1:
length = _inputs.shape[-1].value
if length % (self._play_input_dim * self._play_timestep) != 0:
LOG.error("length is: {}, input_dim: {}, play_timestep: {}".format(length,
self._play_input_dim,
self._play_timestep))
raise Exception("The batch size cannot be divided by the length of input sequence.")
# self.batch_size = length // (self._play_timestep * self._play_input_dim)
self._play_batch_size = length // (self._play_timestep * self._play_input_dim)
self.batch_size = 1
self._batch_input_shape = tf.TensorShape([self.batch_size, self._play_timestep, self._play_input_dim])
else:
raise Exception("dimension of inputs must be equal to 1")
length = self._batch_input_shape[1].value * self._batch_input_shape[2].value
self.batch_size = self._batch_input_shape[0].value
assert self.batch_size == 1, colors.red("only support batch_size is 1")
if not getattr(self, "_unittest", False):
assert self._play_timestep == 1, colors.red("only support outter-timestep 1")
self.model = tf.keras.models.Sequential()
CACHE = utils.get_cache()
input_layer = CACHE.get('play_input_layer', None)
if input_layer is None:
input_layer = tf.keras.layers.InputLayer(batch_size=self.batch_size,
input_shape=self._batch_input_shape[1:])
CACHE['play_input_layer'] = input_layer
self.model.add(input_layer)
self.model.add(Operator(weight=getattr(self, "_weight", 1.0),
width=getattr(self, "_width", 1.0),
debug=getattr(self, "_debug", False),
unittest=getattr(self, "_unittest", False)))
if self._network_type == constants.NetworkType.PLAY:
self.model.add(MyDense(self.units,
activation=self.activation,
use_bias=self.use_bias,
debug=getattr(self, "_debug", False)))
self.model.add(MySimpleDense(units=1,
activation=None,
use_bias=True,
debug=getattr(self, "_debug", False)))
if self._need_compile is True:
LOG.info(colors.yellow("Start to compile this model"))
self.model.compile(loss=self.loss,
optimizer=self.optimizer,
metrics=[self.loss])
self._early_stopping_callback = tf.keras.callbacks.EarlyStopping(monitor="loss", patience=100)
self._tensor_board_callback = tf.keras.callbacks.TensorBoard(log_dir=constants.LOG_DIR,
histogram_freq=0,
batch_size=self.batch_size,
write_graph=True,
write_grads=False,
write_images=False)
# if not getattr(self, "_preload_weights", False):
# utils.init_tf_variables()
if self._network_type == constants.NetworkType.OPERATOR:
LOG.debug(colors.yellow("SUMMARY of Operator"))
elif self._network_type == constants.NetworkType.PLAY:
LOG.debug(colors.yellow("SUMMARY of {}".format(self._name)))
else: