-
Notifications
You must be signed in to change notification settings - Fork 0
/
Models.py
1451 lines (1379 loc) · 77.7 KB
/
Models.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 torch # PyTorch to create and apply deep learning models
from torch import nn # nn for neural network layers
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import math # Useful package for logarithm operations
import numpy as np # Mathematical operations package, allowing also for missing values representation
from functools import partial # Fix some parameters of a function
import data_utils as du # Data science and machine learning relevant methods
class BaseRNN(nn.Module):
def __init__(self, rnn_module, n_inputs, n_hidden, n_outputs, n_rnn_layers=1,
p_dropout=0, embed_features=None, n_embeddings=None,
embedding_dim=None, bidir=False, is_lstm=True,
padding_value=999999):
'''A base RNN model, to use custom TorchScript modules, with
the option to include embedding layers.
nn.Parameters
----------
rnn_module : nn.Module
Recurrent neural network module to be used in this model.
n_inputs : int
Number of input features.
n_hidden : int
Number of hidden units.
n_outputs : int
Number of outputs.
n_rnn_layers : int, default 1
Number of RNN layers.
p_dropout : float or int, default 0
Probability of dropout.
embed_features : list of ints or list of list of ints, default None
List of features (refered to by their indices) that need to go
through embedding layers. One list of one hot encoded feature per
embedding layer must be set.
n_embeddings : list of ints, default None
List of the total number of unique categories for the embedding
layers. Needs to be in the same order as the embedding layers are
described in `embed_features`.
embedding_dim : list of ints, default None
List of embedding dimensions. Needs to be in the same order as the
embedding layers are described in `embed_features`.
bidir : bool, default False
If set to True, the RNN model will be bidirectional (have hidden
memory flowing both forward and backwards).
is_lstm : bool, default True
If set to True, it means that the provided model is of type (or at
least a variant of) LSTM. This is important so as to know if the
hidden state has two (h and c) or just one variable (h).
padding_value : int or float, default 999999
Value to use in the padding, to fill the sequences.
'''
super().__init__()
self.rnn_module = rnn_module
self.n_inputs = n_inputs
self.n_hidden = n_hidden
self.n_outputs = n_outputs
self.n_rnn_layers = n_rnn_layers
self.p_dropout = p_dropout
self.embed_features = embed_features
self.n_embeddings = n_embeddings
self.embedding_dim = embedding_dim
self.bidir = bidir
self.is_lstm = is_lstm
self.padding_value = padding_value
# Embedding layers
if self.embed_features is not None:
if not isinstance(self.embed_features, list):
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a list of indices or a list of lists of indices (there are multiple one hot encoded columns for every original categorical feature). The provided argument has type {type(embed_features)}.')
if self.n_embeddings is None:
# Find the number of embeddings based on the number of one hot encoded feature
if all([isinstance(feature, int) for feature in self.embed_features]):
self.n_embeddings = len(self.embed_features) + 1
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
self.n_embeddings = []
[self.n_embeddings.append(len(feat_list) + 1) for feat_list in self.embed_features]
else:
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a single, integer index or a list of indices. The provided argument has type {type(embed_features)}.')
else:
if all([isinstance(feature, int) for feature in self.embed_features]):
if self.n_embeddings != len(self.embed_features)+1:
raise Exception(f'ERROR: The number of embeddings `n_embeddings` must equal the length of its corresponding embedding features `embed_features` + 1 (missing values). The provided `n_embeddings` is {self.n_embeddings} while `embed_features` has length {len(self.embed_features)}.')
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
if len(self.n_embeddings) != len(self.embed_features):
raise Exception(f'ERROR: The list of the number of embeddings `n_embeddings` and the embedding features `embed_features` must have the same length. The provided `n_embeddings` has length {len(self.n_embeddings)} while `embed_features` has length {len(self.embed_features)}.')
for i in range(len(self.n_embeddings)):
if self.n_embeddings[i] != len(self.embed_features[i])+1:
raise Exception(f'ERROR: The number of embeddings `n_embeddings` must equal the length of its corresponding embedding features `embed_features` + 1 (missing values). The provided `n_embeddings` is {self.n_embeddings[i]} while `embed_features` has length {len(self.embed_features[i])}, in embedding features set {i}.')
if all([isinstance(feature, int) for feature in self.embed_features]):
if self.embedding_dim is None:
# Calculate a reasonable embedding dimension for the
# current feature; the formula sets a minimum embedding
# dimension of 3, with above values being calculated as
# the rounded up base 5 logarithm of the number of
# embeddings.
self.embedding_dim = max(3, int(math.ceil(math.log(self.n_embeddings, 5))))
# Create a single embedding layer
self.embed_layers = nn.EmbeddingBag(self.n_embeddings, self.embedding_dim)
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
# Create a modules list of embedding bag layers
self.embed_layers = nn.ModuleList()
if self.embedding_dim is None:
self.embedding_dim = list()
none_embedding_dim = True
else:
none_embedding_dim = False
for i in range(len(self.embed_features)):
if none_embedding_dim is True:
# Calculate a reasonable embedding dimension for the
# current feature; the formula sets a minimum embedding
# dimension of 3, with above values being calculated as
# the rounded up base 5 logarithm of the number of
# embeddings.
embedding_dim_i = max(3, int(math.ceil(math.log(self.n_embeddings[i], 5))))
self.embedding_dim.append(embedding_dim_i)
else:
embedding_dim_i = self.embedding_dim[i]
# Create an embedding layer for the current feature
self.embed_layers.append(nn.EmbeddingBag(self.n_embeddings[i], embedding_dim_i))
else:
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a single, integer index or a list of indices. The provided argument has type {type(embed_features)}.')
# RNN layer(s)
if self.embed_features is None:
self.rnn_n_inputs = self.n_inputs
else:
# Have into account the new embedding columns that will be added, as
# well as the removal of the originating categorical columns
if all([isinstance(feature, int) for feature in self.embed_features]):
self.rnn_n_inputs = self.n_inputs + self.embedding_dim - len(self.embed_features)
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
self.rnn_n_inputs = self.n_inputs
for i in range(len(self.embed_features)):
self.rnn_n_inputs = self.rnn_n_inputs + self.embedding_dim[i] - len(self.embed_features[i])
if self.n_rnn_layers == 1:
# Create a single RNN layer
self.rnn_layer = self.rnn_module(self.rnn_n_inputs, self.n_hidden)
# The output dimension of the last RNN layer
rnn_output_dim = self.n_hidden
else:
# Create a list of multiple, stacked RNN layers
self.rnn_layers = nn.ModuleList()
# Add the first RNN layer
self.rnn_layers.append(self.rnn_module(self.rnn_n_inputs, self.n_hidden))
# Add the remaining RNN layers
for i in range(1, self.n_rnn_layers):
self.rnn_layers.append(self.rnn_module(self.n_hidden, self.n_hidden))
# The output dimension of the last RNN layer
rnn_output_dim = self.n_hidden
# Fully connected layer which takes the RNN's hidden units and
# calculates the output classification
self.fc = nn.Linear(rnn_output_dim, self.n_outputs)
# Dropout used between the last RNN layer and the fully connected layer
self.dropout = nn.Dropout(p=self.p_dropout)
if self.n_outputs == 1:
# Use the sigmoid activation function
self.activation = nn.Sigmoid()
# Use the binary cross entropy function
self.criterion = nn.BCEWithLogitsLoss()
else:
# Use the sigmoid activation function
self.activation = nn.Softmax()
# Use the binary cross entropy function
self.criterion = nn.CrossEntropyLoss()
def forward(self, x, hidden_state=None, get_hidden_state=False,
prob_output=True, already_embedded=False):
if self.embed_features is not None and already_embedded is False:
# Run each embedding layer on each respective feature, adding the
# resulting embedding values to the tensor and removing the original,
# categorical encoded columns
x = du.embedding.embedding_bag_pipeline(x, self.embed_layers, self.embed_features,
model_forward=True, inplace=True)
# Make sure that the input data is of type float
x = x.float()
# Get the batch size (might not be always the same)
batch_size = x.shape[0]
if hidden_state is None:
# Reset the LSTM hidden state. Must be done before you run a new
# batch. Otherwise the LSTM will treat a new batch as a continuation
# of a sequence.
self.hidden = self.init_hidden(batch_size)
else:
# Use the specified hidden state
self.hidden = hidden_state
# Get the outputs and hidden states from the RNN layer(s)
if self.n_rnn_layers == 1:
if self.bidir is False:
# Since there's only one layer and the model is not bidirectional,
# we only need one set of hidden state
if self.is_lstm is True:
hidden_state = (self.hidden[0][0], self.hidden[1][0])
else:
hidden_state = self.hidden[0]
rnn_output, self.hidden = self.rnn_layer(x, hidden_state)
else:
# List[RNNState]: One state per layer
if self.is_lstm is True:
output_states = (torch.zeros(self.hidden[0].shape), torch.zeros(self.hidden[1].shape))
else:
output_states = torch.zeros(self.hidden.shape)
i = 0
# The first RNN layer's input is the original input;
# the following layers will use their respective previous layer's
# output as input
rnn_output = x
for rnn_layer in self.rnn_layers:
if self.is_lstm is True:
hidden_state = (self.hidden[0][i], self.hidden[1][i])
else:
hidden_state = self.hidden[i]
rnn_output, out_state = rnn_layer(rnn_output, hidden_state)
# Apply the dropout layer except the last layer
if i < self.n_rnn_layers - 1:
rnn_output = self.dropout(rnn_output)
if self.is_lstm is True:
output_states[0][i] = out_state[0]
output_states[1][i] = out_state[1]
else:
output_states[i] = [out_state]
i += 1
# Update the hidden states variable
self.hidden = output_states
# Flatten RNN output to fit into the fully connected layer
flat_rnn_output = rnn_output.contiguous().view(-1, self.n_hidden * (1 + self.bidir))
# Apply the final fully connected layer
output = self.fc(flat_rnn_output)
if prob_output is True:
# Get the outputs in the form of probabilities
if self.n_outputs == 1:
output = self.activation(output)
else:
# Normalize outputs on their last dimension
output = self.activation(output, dim=len(output.shape)-1)
if get_hidden_state is True:
return output, self.hidden
else:
return output
def loss(self, y_pred, y_labels):
# Flatten the data
y_pred = y_pred.reshape(-1)
y_labels = y_labels.reshape(-1)
# Find the indices that don't correspond to padding samples
non_pad_idx = y_labels != self.padding_value
# Remove the padding samples
y_labels = y_labels[non_pad_idx]
y_pred = y_pred[non_pad_idx]
# Compute cross entropy loss which ignores all padding values
ce_loss = self.criterion(y_pred, y_labels)
return ce_loss
def init_hidden(self, batch_size):
# Create two new tensors with sizes n_layers x batch_size x n_hidden,
# initialized to zero, for hidden state and cell state of LSTM
weight = next(self.parameters()).data
# Check if GPU is available
train_on_gpu = torch.cuda.is_available()
if train_on_gpu is True:
hidden = (weight.new(self.n_rnn_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_().cuda(),
weight.new(self.n_rnn_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_rnn_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_(),
weight.new(self.n_rnn_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_())
return hidden
class VanillaRNN(nn.Module):
def __init__(self, n_inputs, n_hidden, n_outputs, n_rnn_layers=1, p_dropout=0,
embed_features=None, n_embeddings=None, embedding_dim=None,
bidir=False, padding_value=999999, total_length=None):
'''A vanilla RNN model, using PyTorch's predefined RNN module, with
the option to include embedding layers.
Parameters
----------
n_inputs : int
Number of input features.
n_hidden : int
Number of hidden units.
n_outputs : int
Number of outputs.
n_rnn_layers : int, default 1
Number of RNN layers.
p_dropout : float or int, default 0
Probability of dropout.
embed_features : list of ints or list of list of ints, default None
List of features (refered to by their indices) that need to go
through embedding layers.
n_embeddings : list of ints, default None
List of the total number of unique categories for the embedding
layers. Needs to be in the same order as the embedding layers are
described in `embed_features`.
embedding_dim : list of ints, default None
List of embedding dimensions. Needs to be in the same order as the
embedding layers are described in `embed_features`.
bidir : bool, default False
If set to True, the RNN model will be bidirectional (have hidden
memory flowing both forward and backwards).
padding_value : int or float, default 999999
Value to use in the padding, to fill the sequences.
total_length : int, default None
If not None, the output will be padded to have length total_length.
This method will throw ValueError if total_length is less than the
max sequence length in sequence.
'''
super().__init__()
self.n_inputs = n_inputs
self.n_hidden = n_hidden
self.n_outputs = n_outputs
self.n_rnn_layers = n_rnn_layers
self.p_dropout = p_dropout
self.embed_features = embed_features
self.n_embeddings = n_embeddings
self.embedding_dim = embedding_dim
self.bidir = bidir
self.padding_value = padding_value
self.total_length = total_length
# Embedding layers
if self.embed_features is not None:
if not isinstance(self.embed_features, list):
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a list of indices or a list of lists of indices (there are multiple one hot encoded columns for every original categorical feature). The provided argument has type {type(embed_features)}.')
if self.n_embeddings is None:
# Find the number of embeddings based on the number of one hot encoded feature
if all([isinstance(feature, int) for feature in self.embed_features]):
self.n_embeddings = len(self.embed_features) + 1
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
self.n_embeddings = []
[self.n_embeddings.append(len(feat_list) + 1) for feat_list in self.embed_features]
else:
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a single, integer index or a list of indices. The provided argument has type {type(embed_features)}.')
else:
if all([isinstance(feature, int) for feature in self.embed_features]):
if self.n_embeddings != len(self.embed_features)+1:
raise Exception(f'ERROR: The number of embeddings `n_embeddings` must equal the length of its corresponding embedding features `embed_features` + 1 (missing values). The provided `n_embeddings` is {self.n_embeddings} while `embed_features` has length {len(self.embed_features)}.')
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
if len(self.n_embeddings) != len(self.embed_features):
raise Exception(f'ERROR: The list of the number of embeddings `n_embeddings` and the embedding features `embed_features` must have the same length. The provided `n_embeddings` has length {len(self.n_embeddings)} while `embed_features` has length {len(self.embed_features)}.')
for i in range(len(self.n_embeddings)):
if self.n_embeddings[i] != len(self.embed_features[i])+1:
raise Exception(f'ERROR: The number of embeddings `n_embeddings` must equal the length of its corresponding embedding features `embed_features` + 1 (missing values). The provided `n_embeddings` is {self.n_embeddings[i]} while `embed_features` has length {len(self.embed_features[i])}, in embedding features set {i}.')
if all([isinstance(feature, int) for feature in self.embed_features]):
if self.embedding_dim is None:
# Calculate a reasonable embedding dimension for the
# current feature; the formula sets a minimum embedding
# dimension of 3, with above values being calculated as
# the rounded up base 5 logarithm of the number of
# embeddings.
self.embedding_dim = max(3, int(math.ceil(math.log(self.n_embeddings, 5))))
# Create a single embedding layer
self.embed_layers = nn.EmbeddingBag(self.n_embeddings, self.embedding_dim)
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
# Create a modules list of embedding bag layers
self.embed_layers = nn.ModuleList()
if self.embedding_dim is None:
self.embedding_dim = list()
none_embedding_dim = True
else:
none_embedding_dim = False
for i in range(len(self.embed_features)):
if none_embedding_dim is True:
# Calculate a reasonable embedding dimension for the
# current feature; the formula sets a minimum embedding
# dimension of 3, with above values being calculated as
# the rounded up base 5 logarithm of the number of
# embeddings.
embedding_dim_i = max(3, int(math.ceil(math.log(self.n_embeddings[i], 5))))
self.embedding_dim.append(embedding_dim_i)
else:
embedding_dim_i = self.embedding_dim[i]
# Create an embedding layer for the current feature
self.embed_layers.append(nn.EmbeddingBag(self.n_embeddings[i], embedding_dim_i))
else:
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a single, integer index or a list of indices. The provided argument has type {type(embed_features)}.')
# RNN layer(s)
if self.embed_features is None:
self.rnn_n_inputs = self.n_inputs
else:
# Have into account the new embedding columns that will be added, as
# well as the removal of the originating categorical columns
if all([isinstance(feature, int) for feature in self.embed_features]):
self.rnn_n_inputs = self.n_inputs + self.embedding_dim - len(self.embed_features)
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
self.rnn_n_inputs = self.n_inputs
for i in range(len(self.embed_features)):
self.rnn_n_inputs = self.rnn_n_inputs + self.embedding_dim[i] - len(self.embed_features[i])
self.rnn = nn.RNN(self.rnn_n_inputs, self.n_hidden, self.n_rnn_layers,
batch_first=True, dropout=self.p_dropout,
bidirectional=self.bidir)
# Fully connected layer which takes the RNN's hidden units and
# calculates the output classification
self.fc = nn.Linear(self.n_hidden * (1 + self.bidir), self.n_outputs)
# Dropout used between the last RNN layer and the fully connected layer
self.dropout = nn.Dropout(p=self.p_dropout)
if self.n_outputs == 1:
# Use the sigmoid activation function
self.activation = nn.Sigmoid()
# Use the binary cross entropy function
self.criterion = nn.BCEWithLogitsLoss()
else:
# Use the sigmoid activation function
self.activation = nn.Softmax()
# Use the binary cross entropy function
self.criterion = nn.CrossEntropyLoss()
def forward(self, x, hidden_state=None, seq_lengths=None,
total_length=None, get_hidden_state=False,
prob_output=True, already_embedded=False):
if self.embed_features is not None and already_embedded is False:
# Run each embedding layer on each respective feature, adding the
# resulting embedding values to the tensor and removing the original,
# categorical encoded columns
x = du.embedding.embedding_bag_pipeline(x, self.embed_layers, self.embed_features,
model_forward=True, inplace=True)
# Make sure that the input data is of type float
x = x.float()
# Get the batch size (might not be always the same)
batch_size = x.shape[0]
if hidden_state is None:
# Reset the RNN hidden state. Must be done before you run a new
# batch. Otherwise the RNN will treat a new batch as a continuation
# of a sequence.
self.hidden = self.init_hidden(batch_size)
else:
# Use the specified hidden state
self.hidden = hidden_state
if seq_lengths is not None:
# pack_padded_sequence so that padded items in the sequence won't be
# shown to the RNN
x = pack_padded_sequence(x, seq_lengths, batch_first=True, enforce_sorted=False)
# Get the outputs and hidden states from the RNN layer(s)
rnn_output, self.hidden = self.rnn(x, self.hidden)
if seq_lengths is not None:
# [TODO] Use a dynamically defined total_length
# if total_length is None:
# # Get the model's predefined total sequence length
# total_length = self.total_length
# Undo the packing operation
rnn_output, _ = pad_packed_sequence(rnn_output, batch_first=True,
total_length=self.total_length)
# Apply dropout to the last RNN layer
rnn_output = self.dropout(rnn_output)
# Flatten RNN output to fit into the fully connected layer
flat_rnn_output = rnn_output.contiguous().view(-1, self.n_hidden * (1 + self.bidir))
# Apply the final fully connected layer
output = self.fc(flat_rnn_output)
if prob_output is True:
# Get the outputs in the form of probabilities
if self.n_outputs == 1:
output = self.activation(output)
else:
# Normalize outputs on their last dimension
output = self.activation(output, dim=len(output.shape)-1)
if get_hidden_state is True:
return output, self.hidden
else:
return output
def loss(self, y_pred, y_labels):
# Flatten the data
y_pred = y_pred.reshape(-1)
y_labels = y_labels.reshape(-1)
# Find the indices that don't correspond to padding samples
non_pad_idx = y_labels != self.padding_value
# Remove the padding samples
y_labels = y_labels[non_pad_idx]
y_pred = y_pred[non_pad_idx]
# Compute cross entropy loss which ignores all padding values
ce_loss = self.criterion(y_pred, y_labels)
return ce_loss
def init_hidden(self, batch_size):
# Create two new tensors with sizes n_layers x batch_size x n_hidden,
# initialized to zero, for hidden state and cell state of RNN
weight = next(self.parameters()).data
# Check if GPU is available
train_on_gpu = torch.cuda.is_available()
hidden = weight.new(self.n_rnn_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_()
if train_on_gpu is True:
hidden = hidden.cuda()
return hidden
class VanillaLSTM(nn.Module):
def __init__(self, n_inputs, n_hidden, n_outputs, n_lstm_layers=1, p_dropout=0,
embed_features=None, n_embeddings=None, embedding_dim=None,
bidir=False, padding_value=999999, total_length=None):
'''A vanilla LSTM model, using PyTorch's predefined LSTM module, with
the option to include embedding layers.
Parameters
----------
n_inputs : int
Number of input features.
n_hidden : int
Number of hidden units.
n_outputs : int
Number of outputs.
n_lstm_layers : int, default 1
Number of LSTM layers.
p_dropout : float or int, default 0
Probability of dropout.
embed_features : list of ints or list of list of ints, default None
List of features (refered to by their indices) that need to go
through embedding layers.
n_embeddings : list of ints, default None
List of the total number of unique categories for the embedding
layers. Needs to be in the same order as the embedding layers are
described in `embed_features`.
embedding_dim : list of ints, default None
List of embedding dimensions. Needs to be in the same order as the
embedding layers are described in `embed_features`.
bidir : bool, default False
If set to True, the LSTM model will be bidirectional (have hidden
memory flowing both forward and backwards).
padding_value : int or float, default 999999
Value to use in the padding, to fill the sequences.
total_length : int, default None
If not None, the output will be padded to have length total_length.
This method will throw ValueError if total_length is less than the
max sequence length in sequence.
'''
super().__init__()
self.n_inputs = n_inputs
self.n_hidden = n_hidden
self.n_outputs = n_outputs
self.n_lstm_layers = n_lstm_layers
self.p_dropout = p_dropout
self.embed_features = embed_features
self.n_embeddings = n_embeddings
self.embedding_dim = embedding_dim
self.bidir = bidir
self.padding_value = padding_value
self.total_length = total_length
# Embedding layers
if self.embed_features is not None:
if not isinstance(self.embed_features, list):
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a list of indices or a list of lists of indices (there are multiple one hot encoded columns for every original categorical feature). The provided argument has type {type(embed_features)}.')
if self.n_embeddings is None:
# Find the number of embeddings based on the number of one hot encoded feature
if all([isinstance(feature, int) for feature in self.embed_features]):
self.n_embeddings = len(self.embed_features) + 1
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
self.n_embeddings = []
[self.n_embeddings.append(len(feat_list) + 1) for feat_list in self.embed_features]
else:
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a single, integer index or a list of indices. The provided argument has type {type(embed_features)}.')
else:
if all([isinstance(feature, int) for feature in self.embed_features]):
if self.n_embeddings != len(self.embed_features)+1:
raise Exception(f'ERROR: The number of embeddings `n_embeddings` must equal the length of its corresponding embedding features `embed_features` + 1 (missing values). The provided `n_embeddings` is {self.n_embeddings} while `embed_features` has length {len(self.embed_features)}.')
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
if len(self.n_embeddings) != len(self.embed_features):
raise Exception(f'ERROR: The list of the number of embeddings `n_embeddings` and the embedding features `embed_features` must have the same length. The provided `n_embeddings` has length {len(self.n_embeddings)} while `embed_features` has length {len(self.embed_features)}.')
for i in range(len(self.n_embeddings)):
if self.n_embeddings[i] != len(self.embed_features[i])+1:
raise Exception(f'ERROR: The number of embeddings `n_embeddings` must equal the length of its corresponding embedding features `embed_features` + 1 (missing values). The provided `n_embeddings` is {self.n_embeddings[i]} while `embed_features` has length {len(self.embed_features[i])}, in embedding features set {i}.')
if all([isinstance(feature, int) for feature in self.embed_features]):
if self.embedding_dim is None:
# Calculate a reasonable embedding dimension for the
# current feature; the formula sets a minimum embedding
# dimension of 3, with above values being calculated as
# the rounded up base 5 logarithm of the number of
# embeddings.
self.embedding_dim = max(3, int(math.ceil(math.log(self.n_embeddings, 5))))
# Create a single embedding layer
self.embed_layers = nn.EmbeddingBag(self.n_embeddings, embedding_dim)
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
# Create a modules list of embedding bag layers
self.embed_layers = nn.ModuleList()
if self.embedding_dim is None:
self.embedding_dim = list()
none_embedding_dim = True
else:
none_embedding_dim = False
for i in range(len(self.embed_features)):
if none_embedding_dim is True:
# Calculate a reasonable embedding dimension for the
# current feature; the formula sets a minimum embedding
# dimension of 3, with above values being calculated as
# the rounded up base 5 logarithm of the number of
# embeddings.
embedding_dim_i = max(3, int(math.ceil(math.log(self.n_embeddings[i], 5))))
self.embedding_dim.append(embedding_dim_i)
else:
embedding_dim_i = self.embedding_dim[i]
# Create an embedding layer for the current feature
self.embed_layers.append(nn.EmbeddingBag(self.n_embeddings[i], embedding_dim_i))
else:
raise Exception(f'ERROR: The embedding features must be indicated in `embed_features` as either a single, integer index or a list of indices. The provided argument has type {type(embed_features)}.')
# LSTM layer(s)
if self.embed_features is None:
self.lstm_n_inputs = self.n_inputs
else:
# Have into account the new embedding columns that will be added, as
# well as the removal of the originating categorical columns
if all([isinstance(feature, int) for feature in self.embed_features]):
self.lstm_n_inputs = self.n_inputs + self.embedding_dim - len(self.embed_features)
elif (all([isinstance(feat_list, list) for feat_list in self.embed_features])
and all([isinstance(feature, int) for feat_list in self.embed_features
for feature in feat_list])):
self.lstm_n_inputs = self.n_inputs
for i in range(len(self.embed_features)):
self.lstm_n_inputs = self.lstm_n_inputs + self.embedding_dim[i] - len(self.embed_features[i])
self.lstm = nn.LSTM(self.lstm_n_inputs, self.n_hidden, self.n_lstm_layers,
batch_first=True, dropout=self.p_dropout,
bidirectional=self.bidir)
# Fully connected layer which takes the LSTM's hidden units and
# calculates the output classification
self.fc = nn.Linear(self.n_hidden * (1 + self.bidir), self.n_outputs)
# Dropout used between the last LSTM layer and the fully connected layer
self.dropout = nn.Dropout(p=self.p_dropout)
if self.n_outputs == 1:
# Use the sigmoid activation function
self.activation = nn.Sigmoid()
# Use the binary cross entropy function
self.criterion = nn.BCEWithLogitsLoss()
else:
# Use the sigmoid activation function
self.activation = nn.Softmax()
# Use the binary cross entropy function
self.criterion = nn.CrossEntropyLoss()
def forward(self, x, hidden_state=None, seq_lengths=None,
total_length=None, get_hidden_state=False,
prob_output=True, already_embedded=False):
if self.embed_features is not None and already_embedded is False:
# Run each embedding layer on each respective feature, adding the
# resulting embedding values to the tensor and removing the original,
# categorical encoded columns
x = du.embedding.embedding_bag_pipeline(x, self.embed_layers, self.embed_features,
model_forward=True, inplace=True)
# Make sure that the input data is of type float
x = x.float()
# Get the batch size (might not be always the same)
batch_size = x.shape[0]
if hidden_state is None:
# Reset the LSTM hidden state. Must be done before you run a new
# batch. Otherwise the LSTM will treat a new batch as a continuation
# of a sequence.
self.hidden = self.init_hidden(batch_size)
else:
# Use the specified hidden state
self.hidden = hidden_state
if seq_lengths is not None:
# pack_padded_sequence so that padded items in the sequence won't be
# shown to the LSTM
x = pack_padded_sequence(x, seq_lengths, batch_first=True, enforce_sorted=False)
# Get the outputs and hidden states from the LSTM layer(s)
lstm_output, self.hidden = self.lstm(x, self.hidden)
if seq_lengths is not None:
# Undo the packing operation
lstm_output, _ = pad_packed_sequence(lstm_output, batch_first=True,
total_length=self.total_length)
# Apply dropout to the last LSTM layer
lstm_output = self.dropout(lstm_output)
# Flatten LSTM output to fit into the fully connected layer
flat_lstm_output = lstm_output.contiguous().view(-1, self.n_hidden * (1 + self.bidir))
# Apply the final fully connected layer
output = self.fc(flat_lstm_output)
if prob_output is True:
# Get the outputs in the form of probabilities
if self.n_outputs == 1:
output = self.activation(output)
else:
# Normalize outputs on their last dimension
output = self.activation(output, dim=len(output.shape)-1)
if get_hidden_state is True:
return output, self.hidden
else:
return output
def loss(self, y_pred, y_labels):
# Flatten the data
y_pred = y_pred.reshape(-1)
y_labels = y_labels.reshape(-1)
# Find the indices that don't correspond to padding samples
non_pad_idx = y_labels != self.padding_value
# Remove the padding samples
y_labels = y_labels[non_pad_idx]
y_pred = y_pred[non_pad_idx]
# Compute cross entropy loss which ignores all padding values
ce_loss = self.criterion(y_pred, y_labels)
return ce_loss
def init_hidden(self, batch_size):
# Create two new tensors with sizes n_layers x batch_size x n_hidden,
# initialized to zero, for hidden state and cell state of LSTM
weight = next(self.parameters()).data
# Check if GPU is available
train_on_gpu = torch.cuda.is_available()
if train_on_gpu is True:
hidden = (weight.new(self.n_lstm_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_().cuda(),
weight.new(self.n_lstm_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_().cuda())
else:
hidden = (weight.new(self.n_lstm_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_(),
weight.new(self.n_lstm_layers * (1 + self.bidir), batch_size, self.n_hidden).zero_())
return hidden
class CustomLSTM(BaseRNN):
def __init__(self, n_inputs, n_hidden, n_outputs, n_lstm_layers=1, p_dropout=0,
embed_features=None, n_embeddings=None, embedding_dim=None,
bidir=False, padding_value=999999):
if bidir is True:
rnn_module = lambda *cell_args: BidirLSTMLayer(LSTMCell, *cell_args)
else:
rnn_module = lambda *cell_args: LSTMLayer(LSTMCell, *cell_args)
super(CustomLSTM, self).__init__(rnn_module=rnn_module, n_inputs=n_inputs,
n_hidden=n_hidden, n_outputs=n_outputs,
n_lstm_layers=n_lstm_layers, p_dropout=p_dropout,
embed_features=embed_features,
n_embeddings=n_embeddings,
embedding_dim=embedding_dim,
bidir=bidir, is_lstm=True,
padding_value=padding_value)
class TLSTM(BaseRNN):
def __init__(self, n_inputs, n_hidden, n_outputs, n_rnn_layers=1, p_dropout=0,
embed_features=None, n_embeddings=None, embedding_dim=None,
bidir=False, padding_value=999999,
delta_ts_col=None, elapsed_time='small', no_small_delta=True):
if delta_ts_col is None:
if embed_features is None:
self.delta_ts_col = n_inputs
else:
# Have into account the new embedding columns that will be added,
# as well as the removal of the originating categorical columns
# NOTE: This only works assuming that the delta_ts column is the
# last one on the dataframe, standing to the left of all the
# embedding features
if all([isinstance(feature, int) for feature in embed_features]):
self.delta_ts_col = n_inputs - len(embed_features)
elif (all([isinstance(feat_list, list) for feat_list in embed_features])
and all([isinstance(feature, int) for feat_list in embed_features
for feature in feat_list])):
self.delta_ts_col = n_inputs
for i in range(len(embed_features)):
self.delta_ts_col = self.delta_ts_col - len(embed_features[i])
else:
self.delta_ts_col = delta_ts_col
self.elapsed_time = elapsed_time
self.no_small_delta = no_small_delta
TLSTMCell_prtl = partial(TLSTMCell, delta_ts_col=self.delta_ts_col,
elapsed_time=self.elapsed_time,
no_small_delta=self.no_small_delta)
if bidir is True:
rnn_module = lambda *cell_args: BidirTLSTMLayer(TLSTMCell_prtl, *cell_args)
else:
rnn_module = lambda *cell_args: TLSTMLayer(TLSTMCell_prtl, *cell_args)
super(TLSTM, self).__init__(rnn_module=rnn_module, n_inputs=n_inputs,
n_hidden=n_hidden, n_outputs=n_outputs,
n_rnn_layers=n_rnn_layers,
p_dropout=p_dropout,
embed_features=embed_features,
n_embeddings=n_embeddings,
embedding_dim=embedding_dim,
bidir=bidir, is_lstm=True,
padding_value=padding_value)
def forward(self, x, hidden_state=None, get_hidden_state=False,
prob_output=True, already_embedded=False):
if self.embed_features is not None and already_embedded is False:
# Run each embedding layer on each respective feature, adding the
# resulting embedding values to the tensor and removing the original,
# categorical encoded columns
x = du.embedding.embedding_bag_pipeline(x, self.embed_layers, self.embed_features,
model_forward=True, inplace=True)
# Make sure that the input data is of type float
x = x.float()
# Get the batch size (might not be always the same)
batch_size = x.shape[0]
# Isolate the delta_ts feature
delta_ts = x[:, :, self.delta_ts_col].clone()
left_to_delta = x[:, :, :self.delta_ts_col]
right_to_delta = x[:, :, self.delta_ts_col+1:]
x = torch.cat([left_to_delta, right_to_delta], 2)
if hidden_state is None:
# Reset the LSTM hidden state. Must be done before you run a new
# batch. Otherwise the LSTM will treat a new batch as a continuation
# of a sequence.
self.hidden = self.init_hidden(batch_size)
else:
# Use the specified hidden state
self.hidden = hidden_state
# Make sure that the data is input in the format of (timestamp x sample x features)
x = x.permute(1, 0, 2)
# Get the outputs and hidden states from the RNN layer(s)
if self.n_rnn_layers == 1:
if self.bidir is False:
# Since there's only one layer and the model is not bidirectional,
# we only need one set of hidden state
hidden_state = (self.hidden[0][0], self.hidden[1][0])
# Run the RNN layer on the data
rnn_output, self.hidden = self.rnn_layer(x, hidden_state, delta_ts=delta_ts)
else:
# List[RNNState]: One state per layer
output_states = (torch.zeros(self.hidden[0].shape), torch.zeros(self.hidden[1].shape))
i = 0
# The first RNN layer's input is the original input;
# the following layers will use their respective previous layer's
# output as input
rnn_output = x
for rnn_layer in self.rnn_layers:
hidden_state = (self.hidden[0][i], self.hidden[1][i])
# Run the RNN layer on the data
rnn_output, out_state = rnn_layer(rnn_output, hidden_state, delta_ts=delta_ts)
# Apply the dropout layer except the last layer
if i < self.n_rnn_layers - 1:
rnn_output = self.dropout(rnn_output)
output_states[0][i] = out_state[0]
output_states[1][i] = out_state[1]
i += 1
# Update the hidden states variable
self.hidden = output_states
# Reconvert the data to the format of (sample x timestamp x features)
rnn_output = rnn_output.permute(1, 0, 2)
# Flatten RNN output to fit into the fully connected layer
flat_rnn_output = rnn_output.contiguous().view(-1, self.n_hidden * (1 + self.bidir))
# Apply the final fully connected layer
output = self.fc(flat_rnn_output)
if prob_output is True:
# Get the outputs in the form of probabilities
if self.n_outputs == 1:
output = self.activation(output)
else:
# Normalize outputs on their last dimension
output = self.activation(output, dim=len(output.shape)-1)
if get_hidden_state is True:
return output, self.hidden
else:
return output
class MF1LSTM(BaseRNN):
def __init__(self, n_inputs, n_hidden, n_outputs, n_rnn_layers=1, p_dropout=0,
embed_features=None, n_embeddings=None, embedding_dim=None,
bidir=False, padding_value=999999,
delta_ts_col=None, elapsed_time='small', no_small_delta=True):
if delta_ts_col is None:
if embed_features is None:
self.delta_ts_col = n_inputs
else:
# Have into account the new embedding columns that will be added,
# as well as the removal of the originating categorical columns
# NOTE: This only works assuming that the delta_ts column is the
# last one on the dataframe, standing to the left of all the
# embedding features
if all([isinstance(feature, int) for feature in embed_features]):
self.delta_ts_col = n_inputs - len(embed_features)
elif (all([isinstance(feat_list, list) for feat_list in embed_features])
and all([isinstance(feature, int) for feat_list in embed_features
for feature in feat_list])):
self.delta_ts_col = n_inputs
for i in range(len(embed_features)):
self.delta_ts_col = self.delta_ts_col - len(embed_features[i])
else:
self.delta_ts_col = delta_ts_col
self.elapsed_time = elapsed_time
self.no_small_delta = no_small_delta
MF1LSTMCell_prtl = partial(MF1LSTMCell, delta_ts_col=self.delta_ts_col,
elapsed_time=self.elapsed_time,
no_small_delta=self.no_small_delta)
if bidir is True:
rnn_module = lambda *cell_args: BidirTLSTMLayer(MF1LSTMCell_prtl, *cell_args)
else:
rnn_module = lambda *cell_args: TLSTMLayer(MF1LSTMCell_prtl, *cell_args)
super(MF1LSTM, self).__init__(rnn_module=rnn_module, n_inputs=n_inputs,
n_hidden=n_hidden, n_outputs=n_outputs,
n_rnn_layers=n_rnn_layers,
p_dropout=p_dropout,
embed_features=embed_features,
n_embeddings=n_embeddings,
embedding_dim=embedding_dim,
bidir=bidir, is_lstm=True,
padding_value=padding_value)
def forward(self, x, hidden_state=None, get_hidden_state=False,
prob_output=True, already_embedded=False):
if self.embed_features is not None and already_embedded is False:
# Run each embedding layer on each respective feature, adding the
# resulting embedding values to the tensor and removing the original,
# categorical encoded columns
x = du.embedding.embedding_bag_pipeline(x, self.embed_layers, self.embed_features,
model_forward=True, inplace=True)
# Make sure that the input data is of type float
x = x.float()
# Get the batch size (might not be always the same)
batch_size = x.shape[0]
# Isolate the delta_ts feature
delta_ts = x[:, :, self.delta_ts_col].clone()
left_to_delta = x[:, :, :self.delta_ts_col]
right_to_delta = x[:, :, self.delta_ts_col+1:]
x = torch.cat([left_to_delta, right_to_delta], 2)
if hidden_state is None:
# Reset the LSTM hidden state. Must be done before you run a new
# batch. Otherwise the LSTM will treat a new batch as a continuation
# of a sequence.
self.hidden = self.init_hidden(batch_size)
else:
# Use the specified hidden state
self.hidden = hidden_state
# Make sure that the data is input in the format of (timestamp x sample x features)
x = x.permute(1, 0, 2)
# Get the outputs and hidden states from the RNN layer(s)
if self.n_rnn_layers == 1:
if self.bidir is False:
# Since there's only one layer and the model is not bidirectional,
# we only need one set of hidden state
hidden_state = (self.hidden[0][0], self.hidden[1][0])
# Run the RNN layer on the data
rnn_output, self.hidden = self.rnn_layer(x, hidden_state, delta_ts=delta_ts)
else:
# List[RNNState]: One state per layer
output_states = (torch.zeros(self.hidden[0].shape), torch.zeros(self.hidden[1].shape))
i = 0
# The first RNN layer's input is the original input;
# the following layers will use their respective previous layer's
# output as input
rnn_output = x
for rnn_layer in self.rnn_layers:
hidden_state = (self.hidden[0][i], self.hidden[1][i])
# Run the RNN layer on the data
rnn_output, out_state = rnn_layer(rnn_output, hidden_state, delta_ts=delta_ts)
# Apply the dropout layer except the last layer
if i < self.n_rnn_layers - 1:
rnn_output = self.dropout(rnn_output)
output_states[0][i] = out_state[0]
output_states[1][i] = out_state[1]
i += 1
# Update the hidden states variable
self.hidden = output_states
# Reconvert the data to the format of (sample x timestamp x features)
rnn_output = rnn_output.permute(1, 0, 2)
# Flatten RNN output to fit into the fully connected layer
flat_rnn_output = rnn_output.contiguous().view(-1, self.n_hidden * (1 + self.bidir))
# Apply the final fully connected layer
output = self.fc(flat_rnn_output)
if prob_output is True:
# Get the outputs in the form of probabilities
if self.n_outputs == 1:
output = self.activation(output)
else:
# Normalize outputs on their last dimension
output = self.activation(output, dim=len(output.shape)-1)
if get_hidden_state is True:
return output, self.hidden
else:
return output
class MF2LSTM(BaseRNN):
def __init__(self, n_inputs, n_hidden, n_outputs, n_rnn_layers=1, p_dropout=0,
embed_features=None, n_embeddings=None, embedding_dim=None,
bidir=False, padding_value=999999,
delta_ts_col=None, elapsed_time='small', no_small_delta=True):
# NOTE: In the case of MF2-LSTM models, delta_ts must be in an unormalized
# version, with each value representing time in minutes
if delta_ts_col is None:
if embed_features is None:
self.delta_ts_col = n_inputs
else:
# Have into account the new embedding columns that will be added,
# as well as the removal of the originating categorical columns
# NOTE: This only works assuming that the delta_ts column is the
# last one on the dataframe, standing to the left of all the
# embedding features
if all([isinstance(feature, int) for feature in embed_features]):
self.delta_ts_col = n_inputs - len(embed_features)
elif (all([isinstance(feat_list, list) for feat_list in embed_features])
and all([isinstance(feature, int) for feat_list in embed_features
for feature in feat_list])):
self.delta_ts_col = n_inputs
for i in range(len(embed_features)):
self.delta_ts_col = self.delta_ts_col - len(embed_features[i])
else:
self.delta_ts_col = delta_ts_col
self.elapsed_time = elapsed_time