forked from makramchahine/drone_causality
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnode_cell.py
executable file
·705 lines (587 loc) · 25.2 KB
/
node_cell.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
import numpy as np
import tensorflow as tf
class CTRNNCell(tf.keras.layers.Layer):
def __init__(self, units, method, num_unfolds=None, tau=1, **kwargs):
self.fixed_step_methods = {
"euler": self.euler,
"heun": self.heun,
"rk4": self.rk4,
}
allowed_methods = ["euler", "heun", "rk4", "dopri5"]
if not method in allowed_methods:
raise ValueError(
"Unknown ODE solver '{}', expected one of '{}'".format(
method, allowed_methods
)
)
if method in self.fixed_step_methods.keys() and num_unfolds is None:
raise ValueError(
"Fixed-step ODE solver requires argument 'num_unfolds' to be specified!"
)
self.units = units
self.state_size = units
self.num_unfolds = num_unfolds
self.method = method
self.tau = tau
super(CTRNNCell, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self.kernel = self.add_weight(
shape=(input_dim, self.units), initializer="glorot_uniform", name="kernel"
)
self.recurrent_kernel = self.add_weight(
shape=(self.units, self.units),
initializer="orthogonal",
name="recurrent_kernel",
)
self.bias = self.add_weight(
shape=(self.units), initializer=tf.keras.initializers.Zeros(), name="bias"
)
self.scale = self.add_weight(
shape=(self.units),
initializer=tf.keras.initializers.Constant(1.0),
name="scale",
)
if self.method == "dopri5":
# Only load tfp packge if it is really needed
import tensorflow_probability as tfp
# We don't need the most precise solver to speed up training
self.solver = tfp.math.ode.DormandPrince(
rtol=0.01,
atol=1e-04,
first_step_size=0.01,
safety_factor=0.8,
min_step_size_factor=0.1,
max_step_size_factor=10.0,
max_num_steps=None,
make_adjoint_solver_fn=None,
validate_args=False,
name="dormand_prince",
)
self.built = True
def call(self, inputs, states):
hidden_state = states[0]
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
if self.method == "dopri5":
# Only load tfp packge if it is really needed
import tensorflow_probability as tfp
if not type(elapsed) == float:
batch_dim = tf.shape(elapsed)[0]
elapsed = tf.reshape(elapsed, [batch_dim])
idx = tf.argsort(elapsed)
solution_times = tf.gather(elapsed, idx)
else:
solution_times = tf.constant([elapsed])
hidden_state = states[0]
res = self.solver.solve(
ode_fn=self.dfdt_wrapped,
initial_time=0,
initial_state=hidden_state,
solution_times=solution_times, # tfp.math.ode.ChosenBySolver(elapsed),
constants={"input": inputs},
)
if not type(elapsed) == float:
i2 = tf.stack([idx, tf.range(batch_dim)], axis=1)
hidden_state = tf.gather_nd(res.states, i2)
else:
hidden_state = res.states[-1]
else:
delta_t = elapsed / self.num_unfolds
method = self.fixed_step_methods[self.method]
for i in range(self.num_unfolds):
hidden_state = method(inputs, hidden_state, delta_t)
return hidden_state, [hidden_state]
def dfdt_wrapped(self, t, y, **constants):
inputs = constants["input"]
hidden_state = y
return self.dfdt(inputs, hidden_state)
def dfdt(self, inputs, hidden_state):
h_in = tf.matmul(inputs, self.kernel)
h_rec = tf.matmul(hidden_state, self.recurrent_kernel)
dh_in = self.scale * tf.nn.tanh(h_in + h_rec + self.bias)
if self.tau > 0:
dh = dh_in - hidden_state * self.tau
else:
dh = dh_in
return dh
def euler(self, inputs, hidden_state, delta_t):
dy = self.dfdt(inputs, hidden_state)
return hidden_state + delta_t * dy
def heun(self, inputs, hidden_state, delta_t):
k1 = self.dfdt(inputs, hidden_state)
k2 = self.dfdt(inputs, hidden_state + delta_t * k1)
return hidden_state + delta_t * 0.5 * (k1 + k2)
def rk4(self, inputs, hidden_state, delta_t):
k1 = self.dfdt(inputs, hidden_state)
k2 = self.dfdt(inputs, hidden_state + k1 * delta_t * 0.5)
k3 = self.dfdt(inputs, hidden_state + k2 * delta_t * 0.5)
k4 = self.dfdt(inputs, hidden_state + k3 * delta_t)
return hidden_state + delta_t * (k1 + 2 * k2 + 2 * k3 + k4) / 6.0
class LSTMCell(tf.keras.layers.Layer):
def __init__(self, units, **kwargs):
self.units = units
self.state_size = (units, units)
self.initializer = "glorot_uniform"
self.recurrent_initializer = "orthogonal"
super(LSTMCell, self).__init__(**kwargs)
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
return (
tf.zeros([batch_size, self.units], dtype=tf.float32),
tf.zeros([batch_size, self.units], dtype=tf.float32),
)
def build(self, input_shape):
if isinstance(input_shape[0], tuple):
# Nested tuple
input_shape = (input_shape[0][-1] + input_shape[1][-1],)
# name weights with _lstm suffix so parents with this and other rnns can save weights and not have name collide
self.input_kernel = self.add_weight(
shape=(input_shape[-1], 4 * self.units),
initializer=self.initializer,
name="input_kernel_lstm",
)
self.recurrent_kernel = self.add_weight(
shape=(self.units, 4 * self.units),
initializer=self.recurrent_initializer,
name="recurrent_kernel_lstm",
)
self.bias = self.add_weight(
shape=(4 * self.units),
initializer=tf.keras.initializers.Zeros(),
name="bias_lstm",
)
self.built = True
def call(self, inputs, states):
cell_state, output_state = states
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
if isinstance(elapsed, float):
# tensors should be same shape to concat
elapsed = tf.constant(elapsed)
batch_dim = tf.shape(inputs[0])[0] # can't use .shape, need to use tf.shape()
elapsed = tf.reshape(elapsed, (1, 1))
elapsed = tf.repeat(elapsed, repeats=batch_dim, axis=0)
inputs = tf.concat([inputs[0], elapsed], axis=-1)
z = (
tf.matmul(inputs, self.input_kernel)
+ tf.matmul(output_state, self.recurrent_kernel)
+ self.bias
)
i, ig, fg, og = tf.split(z, 4, axis=-1)
input_activation = tf.nn.tanh(i)
input_gate = tf.nn.sigmoid(ig)
forget_gate = tf.nn.sigmoid(fg + 1.0)
output_gate = tf.nn.sigmoid(og)
new_cell = cell_state * forget_gate + input_activation * input_gate
output_state = tf.nn.tanh(new_cell) * output_gate
return output_state, [new_cell, output_state]
# mmRNN uses a LSTM as memory cell and CT-RNN (= neural ODE) for the time-continuous pathway
class mmRNN(tf.keras.layers.Layer):
def __init__(self, units, **kwargs):
self.units = units
self.state_size = (units, units)
self.initializer = "glorot_uniform"
self.recurrent_initializer = "orthogonal"
self.ctrnn = CTRNNCell(self.units, num_unfolds=4, method="euler")
super(mmRNN, self).__init__(**kwargs)
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
return (
tf.zeros([batch_size, self.units], dtype=tf.float32),
tf.zeros([batch_size, self.units], dtype=tf.float32),
)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self.ctrnn.build([self.units])
# name weights with _mmrnn suffix so don't have same weight names as child CTRNNCell which also has same weights
self.input_kernel = self.add_weight(
shape=(input_dim, 4 * self.units),
initializer=self.initializer,
name="input_kernel_mmrnn",
)
self.recurrent_kernel = self.add_weight(
shape=(self.units, 4 * self.units),
initializer=self.recurrent_initializer,
name="recurrent_kernel_mmrnn",
)
self.bias = self.add_weight(
shape=(4 * self.units),
initializer=tf.keras.initializers.Zeros(),
name="bias_mmrn",
)
self.built = True
def call(self, inputs, states):
cell_state, ode_state = states
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
z = (
tf.matmul(inputs, self.input_kernel)
+ tf.matmul(ode_state, self.recurrent_kernel)
+ self.bias
)
i, ig, fg, og = tf.split(z, 4, axis=-1)
input_activation = tf.nn.tanh(i)
input_gate = tf.nn.sigmoid(ig)
forget_gate = tf.nn.sigmoid(fg + 3.0)
output_gate = tf.nn.sigmoid(og)
new_cell = cell_state * forget_gate + input_activation * input_gate
ode_input = tf.nn.tanh(new_cell) * output_gate
# Implementation choice on how to parametrize ODE component
ode_output, new_ode_state = self.ctrnn.call([ode_input, elapsed], [ode_state])
# ode_output, new_ode_state = self.ctrnn.call([ode_input, elapsed], [ode_input])
return ode_output, [new_cell, new_ode_state[0]]
class CTGRU(tf.keras.layers.Layer):
# https://arxiv.org/abs/1710.04110
def __init__(self, units, M=8, **kwargs):
self.units = units
self.M = M
self.state_size = units * self.M
# Pre-computed tau table (as recommended in paper)
self.ln_tau_table = np.empty(self.M)
self.tau_table = np.empty(self.M)
tau = 1.0
for i in range(self.M):
self.ln_tau_table[i] = np.log(tau)
self.tau_table[i] = tau
tau = tau * (10.0 ** 0.5)
super(CTGRU, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self.retrieval_layer = tf.keras.layers.Dense(
self.units * self.M, activation=None
)
self.detect_layer = tf.keras.layers.Dense(self.units, activation="tanh")
self.update_layer = tf.keras.layers.Dense(self.units * self.M, activation=None)
self.built = True
def call(self, inputs, states):
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1].astype(np.float32)
inputs = inputs[0].astype(np.float32)
batch_dim = tf.shape(inputs)[0]
# States is actually 2D
h_hat = tf.reshape(states[0], [batch_dim, self.units, self.M])
h = tf.reduce_sum(h_hat, axis=2)
states = None # Set state to None, to avoid misuses (bugs) in the code below
# Retrieval
fused_input = tf.concat([inputs, h], axis=-1)
ln_tau_r = self.retrieval_layer(fused_input)
ln_tau_r = tf.reshape(ln_tau_r, shape=[batch_dim, self.units, self.M])
sf_input_r = -tf.square(ln_tau_r - self.ln_tau_table)
rki = tf.nn.softmax(logits=sf_input_r, axis=2)
q_input = tf.reduce_sum(rki * h_hat, axis=2)
reset_value = tf.concat([inputs, q_input], axis=1)
qk = self.detect_layer(reset_value)
qk = tf.reshape(qk, [batch_dim, self.units, 1]) # in order to broadcast
ln_tau_s = self.update_layer(fused_input)
ln_tau_s = tf.reshape(ln_tau_s, shape=[batch_dim, self.units, self.M])
sf_input_s = -tf.square(ln_tau_s - self.ln_tau_table)
ski = tf.nn.softmax(logits=sf_input_s, axis=2)
# Now the elapsed time enters the state update
base_term = (1 - ski) * h_hat + ski * qk
exp_term = tf.exp(-elapsed / self.tau_table)
exp_term = tf.reshape(exp_term, [1, 1, self.M]) # reshape to add batch dim
exp_term = tf.repeat(exp_term, repeats=[batch_dim], axis=0) # repeat for each element of batch
h_hat_next = base_term * tf.cast(exp_term, dtype=tf.float32)
# Compute new state
h_next = tf.reduce_sum(h_hat_next, axis=2)
h_hat_next_flat = tf.reshape(h_hat_next, shape=[batch_dim, self.units * self.M])
return h_next, [h_hat_next_flat]
class VanillaRNN(tf.keras.layers.Layer):
def __init__(self, units, **kwargs):
self.units = units
self.state_size = units
super(VanillaRNN, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self._layer = tf.keras.layers.Dense(self.units, activation="tanh")
self._out_layer = tf.keras.layers.Dense(self.units, activation=None)
self._tau = self.add_weight(
"tau",
shape=(self.units),
dtype=tf.float32,
initializer=tf.keras.initializers.Constant(0.1),
)
self.built = True
def call(self, inputs, states):
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
fused_input = tf.concat([inputs, states[0]], axis=-1)
new_states = self._out_layer(self._layer(fused_input)) - elapsed * self._tau
return new_states, [new_states]
class BidirectionalRNN(tf.keras.layers.Layer):
def __init__(self, units, **kwargs):
self.units = units
self.state_size = (units, units, units)
self.ctrnn = CTRNNCell(self.units, num_unfolds=4, method="euler")
self.lstm = LSTMCell(units=self.units)
super(BidirectionalRNN, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self._out_layer = tf.keras.layers.Dense(self.units, activation=None)
fused_dim = ((input_dim + self.units,), (1,))
self.lstm.build(fused_dim)
self.ctrnn.build(fused_dim)
self.built = True
def call(self, inputs, states):
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
lstm_state = [states[0], states[1]]
lstm_input = [tf.concat([inputs, states[2]], axis=-1), elapsed]
ctrnn_state = [states[2]]
ctrnn_input = [tf.concat([inputs, states[1]], axis=-1), elapsed]
lstm_out, new_lstm_states = self.lstm.call(lstm_input, lstm_state)
ctrnn_out, new_ctrnn_state = self.ctrnn.call(ctrnn_input, ctrnn_state)
fused_output = lstm_out + ctrnn_out
return (
fused_output,
[new_lstm_states[0], new_lstm_states[1], new_ctrnn_state[0]],
)
class GRUD(tf.keras.layers.Layer):
# Implemented according to
# https://www.nature.com/articles/s41598-018-24271-9.pdf
# without the masking
def __init__(self, units, **kwargs):
self.units = units
self.state_size = units
super(GRUD, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self._reset_gate = tf.keras.layers.Dense(
self.units, activation="sigmoid", kernel_initializer="glorot_uniform"
)
self._detect_signal = tf.keras.layers.Dense(
self.units, activation="tanh", kernel_initializer="glorot_uniform"
)
self._update_gate = tf.keras.layers.Dense(
self.units, activation="sigmoid", kernel_initializer="glorot_uniform"
)
self._d_gate = tf.keras.layers.Dense(
self.units, activation="relu", kernel_initializer="glorot_uniform"
)
self.built = True
def call(self, inputs, states):
# d_gate needs elapsed to have 2 dims
batch_dim = tf.shape(inputs)[0]
elapsed = tf.ones((batch_dim, 1))
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
dt = self._d_gate(elapsed)
gamma = tf.exp(-dt)
h_hat = states[0] * gamma
fused_input = tf.concat([inputs, h_hat], axis=-1)
rt = self._reset_gate(fused_input)
zt = self._update_gate(fused_input)
reset_value = tf.concat([inputs, rt * h_hat], axis=-1)
h_tilde = self._detect_signal(reset_value)
# Compute new state
ht = zt * h_hat + (1.0 - zt) * h_tilde
return ht, [ht]
class PhasedLSTM(tf.keras.layers.Layer):
# Implemented according to
# https://papers.nips.cc/paper/6310-phased-lstm-accelerating-recurrent-network-training-for-long-or-event-based-sequences.pdf
def __init__(self, units, **kwargs):
self.units = units
self.state_size = (units, units)
self.initializer = "glorot_uniform"
self.recurrent_initializer = "orthogonal"
super(PhasedLSTM, self).__init__(**kwargs)
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
return (
tf.zeros([batch_size, self.units], dtype=tf.float32),
tf.zeros([batch_size, self.units], dtype=tf.float32),
)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self.input_kernel = self.add_weight(
shape=(input_dim, 4 * self.units),
initializer=self.initializer,
name="input_kernel",
)
self.recurrent_kernel = self.add_weight(
shape=(self.units, 4 * self.units),
initializer=self.recurrent_initializer,
name="recurrent_kernel",
)
self.bias = self.add_weight(
shape=(4 * self.units),
initializer=tf.keras.initializers.Zeros(),
name="bias",
)
self.tau = self.add_weight(
shape=(1,), initializer=tf.keras.initializers.Zeros(), name="tau"
)
self.ron = self.add_weight(
shape=(1,), initializer=tf.keras.initializers.Zeros(), name="ron"
)
self.s = self.add_weight(
shape=(1,), initializer=tf.keras.initializers.Zeros(), name="s"
)
self.built = True
def call(self, inputs, states):
cell_state, hidden_state = states
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
# Leaky constant taken fromt he paper
alpha = 0.001
# Make sure these values are positive
tau = tf.nn.softplus(self.tau)
s = tf.nn.softplus(self.s)
ron = tf.nn.softplus(self.ron)
phit = tf.math.mod(elapsed - s, tau) / tau
kt = tf.where(
tf.less(phit, 0.5 * ron),
2 * phit * ron,
tf.where(tf.less(phit, ron), 2.0 - 2 * phit / ron, alpha * phit),
)
z = (
tf.matmul(inputs, self.input_kernel)
+ tf.matmul(hidden_state, self.recurrent_kernel)
+ self.bias
)
i, ig, fg, og = tf.split(z, 4, axis=-1)
input_activation = tf.nn.tanh(i)
input_gate = tf.nn.sigmoid(ig)
forget_gate = tf.nn.sigmoid(fg + 1.0)
output_gate = tf.nn.sigmoid(og)
c_tilde = cell_state * forget_gate + input_activation * input_gate
c = kt * c_tilde + (1.0 - kt) * cell_state
h_tilde = tf.nn.tanh(c_tilde) * output_gate
h = kt * h_tilde + (1.0 - kt) * hidden_state
return h, [c, h]
class GRUODE(tf.keras.layers.Layer):
# Implemented according to
# https://arxiv.org/pdf/1905.12374.pdf
# without the Bayesian stuff
def __init__(self, units, num_unfolds=4, **kwargs):
self.units = units
self.num_unfolds = num_unfolds
self.state_size = units
super(GRUODE, self).__init__(**kwargs)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self._reset_gate = tf.keras.layers.Dense(
self.units,
activation="sigmoid",
bias_initializer=tf.constant_initializer(1),
)
self._detect_signal = tf.keras.layers.Dense(self.units, activation="tanh")
self._update_gate = tf.keras.layers.Dense(self.units, activation="sigmoid")
self.built = True
def _dh_dt(self, inputs, states):
fused_input = tf.concat([inputs, states], axis=-1)
rt = self._reset_gate(fused_input)
zt = self._update_gate(fused_input)
reset_value = tf.concat([inputs, rt * states], axis=-1)
gt = self._detect_signal(reset_value)
# Compute new state
dhdt = (1.0 - zt) * (gt - states)
return dhdt
def euler(self, inputs, hidden_state, delta_t):
dy = self._dh_dt(inputs, hidden_state)
return hidden_state + delta_t * dy
def call(self, inputs, states):
elapsed = 1.0
if (isinstance(inputs, tuple) or isinstance(inputs, list)) and len(inputs) > 1:
elapsed = inputs[1]
inputs = inputs[0]
delta_t = elapsed / self.num_unfolds
hidden_state = states[0]
for i in range(self.num_unfolds):
hidden_state = self.euler(inputs, hidden_state, delta_t)
return hidden_state, [hidden_state]
return ht, [ht]
class HawkLSTMCell(tf.keras.layers.Layer):
# https://papers.nips.cc/paper/7252-the-neural-hawkes-process-a-neurally-self-modulating-multivariate-point-process.pdf
def __init__(self, units, **kwargs):
self.units = units
self.state_size = (units, units, units) # state is a tripple
self.initializer = "glorot_uniform"
self.recurrent_initializer = "orthogonal"
super(HawkLSTMCell, self).__init__(**kwargs)
def get_initial_state(self, inputs=None, batch_size=None, dtype=None):
return (
tf.zeros([batch_size, self.units], dtype=tf.float32),
tf.zeros([batch_size, self.units], dtype=tf.float32),
tf.zeros([batch_size, self.units], dtype=tf.float32),
)
def build(self, input_shape):
input_dim = input_shape[-1]
if isinstance(input_shape[0], tuple):
# Nested tuple
input_dim = input_shape[0][-1]
self.input_kernel = self.add_weight(
shape=(input_dim, 7 * self.units),
initializer=self.initializer,
name="input_kernel",
)
self.recurrent_kernel = self.add_weight(
shape=(self.units, 7 * self.units),
initializer=self.recurrent_initializer,
name="recurrent_kernel",
)
self.bias = self.add_weight(
shape=(7 * self.units),
initializer=tf.keras.initializers.Zeros(),
name="bias",
)
self.built = True
def call(self, inputs, states):
c, c_bar, h = states
# assume that input is k and that elapsed is always 1
# k = inputs[0] # Is the input
# delta_t = inputs[1] # is the elapsed time
k = inputs
delta_t = 1.0
z = (
tf.matmul(k, self.input_kernel)
+ tf.matmul(h, self.recurrent_kernel)
+ self.bias
)
i, ig, fg, og, ig_bar, fg_bar, d = tf.split(z, 7, axis=-1)
input_activation = tf.nn.tanh(i)
input_gate = tf.nn.sigmoid(ig)
input_gate_bar = tf.nn.sigmoid(ig_bar)
forget_gate = tf.nn.sigmoid(fg)
forget_gate_bar = tf.nn.sigmoid(fg_bar)
output_gate = tf.nn.sigmoid(og)
delta_gate = tf.nn.softplus(d)
new_c = c * forget_gate + input_activation * input_gate
new_c_bar = c_bar * forget_gate_bar + input_activation * input_gate_bar
c_t = new_c_bar + (new_c - new_c_bar) * tf.exp(-delta_gate * delta_t)
output_state = tf.nn.tanh(c_t) * output_gate
return output_state, [new_c, new_c_bar, output_state]