-
Notifications
You must be signed in to change notification settings - Fork 149
/
Copy pathautoencoder.py
1732 lines (1479 loc) · 67.5 KB
/
autoencoder.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
# SPDX-FileCopyrightText: Copyright (c) 2022-2023, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Original Source: https:#github.com/AlliedToasters/dfencoder
#
# Original License: BSD-3-Clause license, included below
# Copyright (c) 2019, Michael Klear.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# * Neither the name of the dfencoder Developers nor the names of any
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import gc
import logging
from collections import OrderedDict
from collections import defaultdict
import numpy as np
import pandas as pd
import torch
import tqdm
from .ae_module import AEModule
from .dataframe import EncoderDataFrame
from .dataloader import DatasetFromDataframe
from .distributed_ae import DistributedAutoEncoder
from .logging import BasicLogger
from .logging import IpynbLogger
from .logging import TensorboardXLogger
from .scalers import GaussRankScaler
from .scalers import ModifiedScaler
from .scalers import NullScaler
from .scalers import StandardScaler
LOG = logging.getLogger('autoencoder')
def _ohe(input_vector, dim, device="cpu"):
"""Does one-hot encoding of input vector.
Parameters
----------
input_vector : torch.Tensor
The input tensor to be one-hot encoded.
dim : int
The dimension of the one-hot encoded output.
device : str, optional
The device on which to place the output tensor, by default "cpu".
Returns
-------
torch.Tensor
The one-hot encoded output tensor of shape (batch_size, dim).
"""
batch_size = len(input_vector)
nb_digits = dim
y = input_vector.reshape(-1, 1)
y_onehot = torch.FloatTensor(batch_size, nb_digits).to(device)
y_onehot.zero_()
y_onehot.scatter_(1, y, 1)
return y_onehot
class AutoEncoder(torch.nn.Module):
def __init__(
self,
*,
encoder_layers=None,
decoder_layers=None,
encoder_dropout=None,
decoder_dropout=None,
encoder_activations=None,
decoder_activations=None,
activation='relu',
min_cats=10,
swap_p=.15,
lr=0.01,
batch_size=256,
eval_batch_size=1024,
optimizer='adam',
amsgrad=False,
momentum=0,
betas=(0.9, 0.999),
dampening=0,
weight_decay=0,
lr_decay=None,
nesterov=False,
verbose=False,
device=None,
distributed_training=False,
logger='basic',
logdir='logdir/',
project_embeddings=True,
run=None,
progress_bar=True,
n_megabatches=1,
scaler='standard',
patience=5,
preset_cats=None,
preset_numerical_scaler_params=None,
binary_feature_list=None,
loss_scaler='standard', # scaler for the losses (z score)
**kwargs):
super().__init__(**kwargs)
self.numeric_fts = OrderedDict()
self.binary_fts = OrderedDict()
self.categorical_fts = OrderedDict()
self.cyclical_fts = OrderedDict()
self.feature_loss_stats = dict()
if device is None:
self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
else:
self.device = device
self.distributed_training = distributed_training
self.model = AEModule(
verbose=verbose,
encoder_layers=encoder_layers,
decoder_layers=decoder_layers,
encoder_dropout=encoder_dropout,
decoder_dropout=decoder_dropout,
encoder_activations=encoder_activations,
decoder_activations=decoder_activations,
activation=activation,
device=self.device,
**kwargs,
)
self.optimizer = optimizer
self.optim = None
self.lr = lr
self.lr_decay = lr_decay
self.min_cats = min_cats
self.preset_cats = preset_cats
self.preset_numerical_scaler_params = preset_numerical_scaler_params
self.swap_p = swap_p
self.batch_size = batch_size
self.eval_batch_size = eval_batch_size
self.numeric_output = None
self.binary_output = None
# `num_names` is a list of column names that contain numeric data (int & float fields).
self.num_names = []
self.bin_names = binary_feature_list
self.amsgrad = amsgrad
self.momentum = momentum
self.betas = betas
self.dampening = dampening
self.weight_decay = weight_decay
self.nesterov = nesterov
self.progress_bar = progress_bar
self.mse = torch.nn.modules.loss.MSELoss(reduction='none')
self.bce = torch.nn.modules.loss.BCELoss(reduction='none')
self.cce = torch.nn.modules.loss.CrossEntropyLoss(reduction='none')
self.verbose = verbose
if self.verbose:
LOG.setLevel(logging.DEBUG)
else:
LOG.setLevel(logging.INFO)
self.logger = logger
self.logdir = logdir
self.run = run
self.project_embeddings = project_embeddings
self.scaler = scaler
self.patience = patience
# scaler class used to scale losses and collect loss stats
self.loss_scaler_str = loss_scaler
self.loss_scaler = self.get_scaler(loss_scaler)
self.n_megabatches = n_megabatches
def get_scaler(self, name):
scalers = {
'standard': StandardScaler,
'gauss_rank': GaussRankScaler,
'modified': ModifiedScaler,
None: NullScaler,
'none': NullScaler
}
return scalers[name]
def _init_numeric(self, df=None):
"""Initializes the numerical features of the model by either using preset numerical scaler parameters
or by using the input data.
Parameters
----------
df : pandas DataFrame, optional
The input data to be used to initialize the numerical features, by default None.
If not provided, self.preset_numerical_scaler_params must be provided.
Raises
------
ValueError
If both df and self.preset_numerical_scaler_params are not provided.
"""
if df is None and self.preset_numerical_scaler_params is None:
raise ValueError("Either `df` or `self.preset_numerical_scaler_params` needs to be provided.")
if self.preset_numerical_scaler_params:
LOG.debug("Using self.preset_numerical_scaler_params to override the numerical scalers...")
for ft, scaler_params in self.preset_numerical_scaler_params.items():
# scaler_params should include the following keys: scaler_type, scaler_attr_dict, mean, std
scaler = self.get_scaler(scaler_params.get("scaler_type", "gauss_rank"))()
for k, v in scaler_params["scaler_attr_dict"].items():
# scaler_params['scaler_attr_dict'] should be a dict including all the class attributes of a fitted scaler class
setattr(scaler, k, v)
feature = {
"mean": scaler_params["mean"],
"std": scaler_params["std"],
"scaler": scaler,
}
self.numeric_fts[ft] = feature
else:
# initialize using a dataframe
numeric = list(df.select_dtypes(include=[int, float]).columns)
if isinstance(self.scaler, str):
scalers = {ft: self.scaler for ft in numeric}
elif isinstance(self.scaler, dict):
scalers = self.scaler
for ft in numeric:
Scaler = self.get_scaler(scalers.get(ft, "gauss_rank"))
feature = {
"mean": df[ft].mean(),
"std": df[ft].std(),
"scaler": Scaler(),
}
feature["scaler"].fit(df[ft][~df[ft].isna()].values)
self.numeric_fts[ft] = feature
self.num_names = list(self.numeric_fts.keys())
def create_numerical_col_max(self, num_names, mse_loss):
if num_names:
num_df = pd.DataFrame(num_names)
num_df.columns = ['num_col_max_loss']
num_df.reset_index(inplace=True)
argmax_df = pd.DataFrame(torch.argmax(mse_loss.cpu(), dim=1).numpy())
argmax_df.columns = ['index']
num_df = num_df.merge(argmax_df, on='index', how='left')
num_df.drop('index', axis=1, inplace=True)
else:
num_df = pd.DataFrame()
return num_df
def create_binary_col_max(self, bin_names, bce_loss):
if bin_names:
bool_df = pd.DataFrame(bin_names)
bool_df.columns = ['bin_col_max_loss']
bool_df.reset_index(inplace=True)
argmax_df = pd.DataFrame(torch.argmax(bce_loss.cpu(), dim=1).numpy())
argmax_df.columns = ['index']
bool_df = bool_df.merge(argmax_df, on='index', how='left')
bool_df.drop('index', axis=1, inplace=True)
else:
bool_df = pd.DataFrame()
return bool_df
def create_categorical_col_max(self, cat_names, cce_loss):
final_list = []
if cat_names:
for index, val in enumerate(cce_loss):
val = pd.DataFrame(val.cpu().numpy())
val.columns = [cat_names[index]]
final_list.append(val)
cat_df = pd.DataFrame(pd.concat(final_list, axis=1).idxmax(axis=1))
cat_df.columns = ['cat_col_max_loss']
else:
cat_df = pd.DataFrame()
return cat_df
def get_variable_importance(self, num_names, cat_names, bin_names, mse_loss, bce_loss, cce_loss, cloudtrail_df):
# Get data in the right format
num_df = self.create_numerical_col_max(num_names, mse_loss)
bool_df = self.create_binary_col_max(bin_names, bce_loss)
cat_df = self.create_categorical_col_max(cat_names, cce_loss)
variable_importance_df = pd.concat([num_df, bool_df, cat_df], axis=1)
return variable_importance_df
def return_feature_names(self):
bin_names = list(self.binary_fts.keys())
num_names = list(self.numeric_fts.keys())
cat_names = list(self.categorical_fts.keys())
return num_names, cat_names, bin_names
def _init_cats(self, df):
objects = list(df.select_dtypes(include=object).columns)
for ft in objects:
feature = {}
vl = df[ft].value_counts()
cats = list(vl[vl >= self.min_cats].index)
feature['cats'] = cats
self.categorical_fts[ft] = feature
def _init_binary(self, df=None):
"""Initializes the binary features of the model.
Parameters
----------
df : pandas.DataFrame, optional
The input data to be used to initialize the binary features, by default None.
Raises
------
ValueError
If both df and self.bin_names are not provided.
"""
if df is None and self.bin_names is None:
raise ValueError(
"Need to provide one of the two params (df or binary_features). "
"If there is no binary feartures, try providing the parameter `binary_feature_list=[]` during class init."
)
if self.bin_names is not None:
LOG.debug("Using the preset binary feature list `self.bin_names` to initialize the binary features...")
binaries = self.bin_names
else:
binaries = list(df.select_dtypes(include=bool).columns)
self.bin_names = binaries
for ft in self.binary_fts:
feature = self.binary_fts[ft]
for i, cat in enumerate(feature['cats']):
feature[cat] = bool(i)
for ft in binaries:
feature = dict()
feature['cats'] = [True, False]
feature[True] = True
feature[False] = False
self.binary_fts[ft] = feature
def _init_features(self, df=None):
"""Initializea the features of different types.
`df` is required if any of `preset_cats`, `preset_numerical_scaler_params`, and `binary_feature_list` are not provided
at model initialization.
Parameters
----------
df : pandas.DataFrame, optional
dataframe used to compute and extract feature information, by default None
Raises
------
ValueError
if any of `preset_cats`, `preset_numerical_scaler_params`, and `binary_feature_list` are not provided at model initialization
"""
if df is None:
# all feature information needs to be fed into the model at initialization in order to build the
# model without `df` as an input
if self.preset_cats is None or self.bin_names is None or self.preset_numerical_scaler_params is None:
raise ValueError(
'Fail to intitialize the features without an input dataframe. '
'All of `preset_cats`, `preset_numerical_scaler_params`, and `binary_feature_list` need to be provided during model '
'initialization for this function to work without an input `df`.')
if self.preset_cats is not None:
LOG.debug('Using the preset categories `self.preset_cats` to initialize the categories features...')
self.categorical_fts = self.preset_cats
else:
self._init_cats(df)
self._init_numeric(df)
self._init_binary(df)
def prepare_df(self, df):
"""Does data preparation on copy of input dataframe.
Parameters
----------
df : pandas.DataFrame
The pandas dataframe to process
Returns
-------
pandas.DataFrame
A processed copy of df.
"""
output_df = EncoderDataFrame()
for ft in self.numeric_fts:
feature = self.numeric_fts[ft]
col = df[ft].fillna(feature['mean'])
trans_col = feature['scaler'].transform(col.values)
trans_col = pd.Series(index=df.index, data=trans_col)
output_df[ft] = trans_col
for ft in self.binary_fts:
feature = self.binary_fts[ft]
output_df[ft] = df[ft].apply(lambda x: feature.get(x, False))
for ft in self.categorical_fts:
feature = self.categorical_fts[ft]
col = pd.Categorical(df[ft], categories=feature['cats'] + ['_other'])
col = col.fillna('_other')
output_df[ft] = col
return output_df
def _build_model(self, df=None, rank=None):
"""Builds the autoencoder model using either the given dataframe or the preset feature information for metadata.
If distributed training is enabled (self.distributed_training is True), wraps the pytorch module with DDP.
User should not need to call this function directly as it's called before training in the fit() functions.
Parameters
----------
df : pandas.DataFrame, optional
The input dataframe to be used to infer metadata, by default None.
rank : int, optional
Rank of the process being used for distributed training. Used only if self.distributed_training is True, by default None.
Raises
------
ValueError
If rank is nor provided in distributed training mode.
"""
LOG.debug('Building model...')
# get metadata from features
self._init_features(df)
self.model.build(self.numeric_fts, self.binary_fts, self.categorical_fts)
if self.distributed_training:
if rank is None:
raise ValueError('`rank` missing. `rank` is required for distributed training.')
self.model._ddp_params_and_buffers_to_ignore = []
if len(self.numeric_fts) == 0:
# if there is no numeric feature, ignore this layer to avoid errors while syncing parameters across gpus
self.model._ddp_params_and_buffers_to_ignore.append('numeric_output.weight')
if len(self.binary_fts) == 0:
# if there is no binary feature, ignore this layer to avoid errors while syncing parameters across gpus
self.model._ddp_params_and_buffers_to_ignore.append('binary_output.weight')
self.model = DistributedAutoEncoder(self.model, device_ids=[rank], output_device=rank)
self._build_optimizer()
if self.lr_decay is not None:
self.lr_decay = torch.optim.lr_scheduler.ExponentialLR(self.optim, self.lr_decay)
self._build_logger()
LOG.debug('done!')
def _build_optimizer(self):
lr = self.lr
params = self.model.parameters()
if self.optimizer == 'adam':
optim = torch.optim.Adam(params,
lr=self.lr,
amsgrad=self.amsgrad,
weight_decay=self.weight_decay,
betas=self.betas)
elif self.optimizer == 'sgd':
optim = torch.optim.SGD(
params,
lr,
momentum=self.momentum,
nesterov=self.nesterov,
dampening=self.dampening,
weight_decay=self.weight_decay,
)
else:
raise ValueError('Provided optimizer unsupported. Supported optimizers include: [adam, sgd].')
self.optim = optim
def _build_logger(self):
""" Initializes the logger to be used for training the model."""
cat_names = list(self.categorical_fts.keys())
fts = self.num_names + self.bin_names + cat_names
if self.logger == 'basic':
self.logger = BasicLogger(fts=fts)
elif self.logger == 'ipynb':
self.logger = IpynbLogger(fts=fts)
elif self.logger == 'tensorboard':
self.logger = TensorboardXLogger(logdir=self.logdir, run=self.run, fts=fts)
def compute_targets(self, df):
num = torch.tensor(df[self.num_names].values).float().to(self.device)
bin = torch.tensor(df[self.bin_names].astype(int).values).float().to(self.device)
codes = []
for ft in self.categorical_fts:
code = torch.tensor(df[ft].cat.codes.astype(int).values).to(self.device)
codes.append(code)
return num, bin, codes
def encode_input(self, df):
"""
Handles raw df inputs.
Passes categories through embedding layers.
"""
num, bin, codes = self.compute_targets(df)
embeddings = []
for i, embedding_layer in enumerate(self.model.categorical_embedding.values()):
emb = embedding_layer(codes[i])
embeddings.append(emb)
return [num], [bin], embeddings
def build_input_tensor(self, df):
num, bin, embeddings = self.encode_input(df)
x = torch.cat(num + bin + embeddings, dim=1)
return x
def preprocess_train_data(self, df, shuffle_rows_in_batch=True):
""" Wrapper function round `self.preprocess_data` feeding in the args suitable for a training set."""
return self.preprocess_data(
df,
shuffle_rows_in_batch=shuffle_rows_in_batch,
include_original_input_tensor=False,
include_swapped_input_by_feature_type=False,
)
def preprocess_validation_data(self, df, shuffle_rows_in_batch=False):
""" Wrapper function round `self.preprocess_data` feeding in the args suitable for a validation set."""
return self.preprocess_data(
df,
shuffle_rows_in_batch=shuffle_rows_in_batch,
include_original_input_tensor=True,
include_swapped_input_by_feature_type=True,
)
def preprocess_data(
self,
df,
shuffle_rows_in_batch,
include_original_input_tensor,
include_swapped_input_by_feature_type,
):
"""Preprocesses a pandas dataframe `df` for input into the autoencoder model.
Parameters
----------
df : pandas.DataFrame
The input dataframe to preprocess.
shuffle_rows_in_batch : bool
Whether to shuffle the rows of the dataframe before processing.
include_original_input_tensor : bool
Whether to process the df into an input tensor without swapping and include it in the returned data dict.
Note. Training required only the swapped input tensor while validation can use both.
include_swapped_input_by_feature_type : bool
Whether to process the swapped df into num/bin/cat feature tensors and include them in the returned data dict.
This is useful for baseline performance evaluation for validation.
Returns
-------
Dict[str, Union[int, torch.Tensor]]
A dict containing the preprocessed input data and targets by feature type.
"""
df = self.prepare_df(df)
if shuffle_rows_in_batch:
df = df.sample(frac=1.0)
df = EncoderDataFrame(df)
swapped_df = df.swap(likelihood=self.swap_p)
swapped_input_tensor = self.build_input_tensor(swapped_df)
num_target, bin_target, codes = self.compute_targets(df)
preprocessed_data = {
'input_swapped': swapped_input_tensor,
'num_target': num_target,
'bin_target': bin_target,
'cat_target': codes,
'size': len(df),
}
if include_original_input_tensor:
preprocessed_data['input_original'] = self.build_input_tensor(df)
if include_swapped_input_by_feature_type:
num_swapped, bin_swapped, codes_swapped = self.compute_targets(swapped_df)
preprocessed_data['num_swapped'] = num_swapped
preprocessed_data['bin_swapped'] = bin_swapped
preprocessed_data['cat_swapped'] = codes_swapped
return preprocessed_data
def compute_loss(self, num, bin, cat, target_df, should_log=True, _id=False):
num_target, bin_target, codes = self.compute_targets(target_df)
return self.compute_loss_from_targets(
num=num,
bin=bin,
cat=cat,
num_target=num_target,
bin_target=bin_target,
cat_target=codes,
should_log=should_log,
_id=_id,
)
def compute_loss_from_targets(self, num, bin, cat, num_target, bin_target, cat_target, should_log=True, _id=False):
"""Computes the loss from targets.
Parameters
----------
num : torch.Tensor
numerical data tensor
bin : torch.Tensor
binary data tensor
cat : List[torch.Tensor]
list of categorical data tensors
num_target : torch.Tensor
target numerical data tensor
bin_target : torch.Tensor
target binary data tensor
cat_target : List[torch.Tensor]
list of target categorical data tensors
should_log : bool, optional
whether to log the loss in self.logger, by default True
_id : bool, optional
whether the current step is an id validation step (for logging), by default False
Returns
-------
Tuple[Union[float, List[float]]]
A tuple containing the mean mse/bce losses, list of mean cce losses, and mean net loss
"""
if should_log:
if self.logger is not None:
should_log = True
else:
should_log = False
net_loss = []
mse_loss = self.mse(num, num_target)
net_loss += list(mse_loss.mean(dim=0).cpu().detach().numpy())
mse_loss = mse_loss.mean()
bce_loss = self.bce(bin, bin_target)
net_loss += list(bce_loss.mean(dim=0).cpu().detach().numpy())
bce_loss = bce_loss.mean()
cce_loss = []
for i, ft in enumerate(self.categorical_fts):
loss = self.cce(cat[i], cat_target[i])
loss = loss.mean()
cce_loss.append(loss)
val = loss.cpu().item()
net_loss += [val]
if should_log:
if self.training:
self.logger.training_step(net_loss)
elif _id:
self.logger.id_val_step(net_loss)
elif not self.training:
self.logger.val_step(net_loss)
net_loss = np.array(net_loss).mean()
return mse_loss, bce_loss, cce_loss, net_loss
def do_backward(self, mse, bce, cce):
# running `backward()` seperately on mse/bce/cce is equivalent to summing them up and run `backward()` once
loss_fn = mse + bce
for ls in cce:
loss_fn += ls
loss_fn.backward()
def compute_baseline_performance(self, in_, out_):
"""
Baseline performance is computed by generating a strong
prediction for the identity function (predicting input==output)
with a swapped (noisy) input,
and computing the loss against the unaltered original data.
This should be roughly the loss we expect when the encoder degenerates
into the identity function solution.
Returns net loss on baseline performance computation
(sum of all losses)
"""
self.eval()
num_pred, bin_pred, codes = self.compute_targets(in_)
bin_pred += ((bin_pred == 0).float() * 0.05)
bin_pred -= ((bin_pred == 1).float() * 0.05)
codes_pred = []
for i, cd in enumerate(codes):
feature = list(self.categorical_fts.items())[i][1]
dim = len(feature['cats']) + 1
pred = _ohe(cd, dim, device=self.device) * 5
codes_pred.append(pred)
mse_loss, bce_loss, cce_loss, net_loss = self.compute_loss(num_pred, bin_pred, codes_pred, out_, should_log=False)
if isinstance(self.logger, BasicLogger):
self.logger.baseline_loss = net_loss
return net_loss
def _create_stat_dict(self, a):
scaler = self.loss_scaler()
scaler.fit(a)
return {'scaler': scaler}
def fit(
self,
train_data,
epochs=1,
val_data=None,
run_validation=False,
use_val_for_loss_stats=False,
rank=None,
world_size=None,
):
""" Does training in the specified mode (indicated by self.distrivuted_training).
Parameters
----------
train_data : pandas.DataFrame (centralized) or torch.utils.data.DataLoader (distributed)
Data for training.
epochs : int, optional
Number of epochs to run training, by default 1.
val_data : pandas.DataFrame (centralized) or torch.utils.data.DataLoader (distributed), optional
Data for validation and computing loss stats, by default None.
run_validation : bool, optional
Whether to collect validation loss for each epoch during training, by default False.
use_val_for_loss_stats : bool, optional
whether to use the validation set for loss statistics collection (for z score calculation), by default False.
rank : int, optional
The rank of the current process, by default None. Required for distributed training.
world_size : int, optional
The total number of processes, by default None. Required for distributed training.
Raises
------
TypeError
If train_data is not a pandas dataframe in centralized training mode.
ValueError
If rank and world_size not provided in distributed training mode.
TypeError
If train_data is not a pandas dataframe or a torch.utils.data.DataLoader or a torch.utils.data.Dataset in distributed training mode.
"""
if not self.distributed_training:
if not isinstance(train_data, pd.DataFrame):
raise TypeError("`train_data` needs to be a pandas dataframe in centralized training mode."
f" `train_data` is currently of type: {type(train_data)}")
self._fit_centralized(
df=train_data,
epochs=epochs,
val=val_data,
run_validation=run_validation,
use_val_for_loss_stats=use_val_for_loss_stats,
)
else:
# distributed training requires rank and world_size
if rank is None or world_size is None:
raise ValueError('`rank` and `world_size` must be provided for distributed training.')
if not isinstance(train_data, (pd.DataFrame, torch.utils.data.DataLoader, torch.utils.data.Dataset)):
raise TypeError(
"`train_data` needs to be a pandas DataFrame, a DataLoader, or a Dataset in distributed training mode."
f" `train_data` is currently of type: {type(train_data)}")
self._fit_distributed(
train_data=train_data,
epochs=epochs,
val_data=val_data,
run_validation=run_validation,
use_val_for_loss_stats=use_val_for_loss_stats,
rank=rank,
world_size=world_size,
)
def _fit_centralized(self, df, epochs=1, val=None, run_validation=False, use_val_for_loss_stats=False):
"""Does training in a single process on a single GPU.
Parameters
----------
df : pandas.DataFrame
Data used for training.
epochs : int, optional
Number of epochs to run training, by default 1.
val : pandas.DataFrame, optional
Optional pandas dataframe for validation or loss stats, by default None.
run_validation : bool, optional
Whether to collect validation loss for each epoch during training, by default False.
use_val_for_loss_stats : bool, optional
Whether to use the validation set for loss statistics collection (for z score calculation), by default False.
Raises
------
ValueError
If run_validation or use_val_for_loss_stats is True but val is not provided.
"""
if (run_validation or use_val_for_loss_stats) and val is None:
raise ValueError("Validation set is required if either run_validation or \
use_val_for_loss_stats is set to True.")
if use_val_for_loss_stats:
df_for_loss_stats = val.copy()
else:
# use train loss
df_for_loss_stats = df.copy()
if run_validation and val is not None:
val = val.copy()
if self.optim is None:
self._build_model(df)
if self.n_megabatches == 1:
df = self.prepare_df(df)
if run_validation and val is not None:
val_df = self.prepare_df(val)
val_in = val_df.swap(likelihood=self.swap_p)
msg = "Validating during training.\n"
msg += "Computing baseline performance..."
baseline = self.compute_baseline_performance(val_in, val_df)
LOG.debug(msg)
val_batches = len(val_df) // self.eval_batch_size
if len(val_df) % self.eval_batch_size != 0:
val_batches += 1
n_updates = len(df) // self.batch_size
if len(df) % self.batch_size > 0:
n_updates += 1
last_loss = 5000
count_es = 0
for i in range(epochs):
self.train()
LOG.debug(f'training epoch {i + 1}...')
df = df.sample(frac=1.0)
df = EncoderDataFrame(df)
if self.n_megabatches > 1:
self.train_megabatch_epoch(n_updates, df)
else:
input_df = df.swap(likelihood=self.swap_p)
self.train_epoch(n_updates, input_df, df)
if self.lr_decay is not None:
self.lr_decay.step()
if run_validation and val is not None:
self.eval()
with torch.no_grad():
swapped_loss = []
id_loss = []
for i in range(val_batches):
start = i * self.eval_batch_size
stop = (i + 1) * self.eval_batch_size
slc_in = val_in.iloc[start:stop]
slc_in_tensor = self.build_input_tensor(slc_in)
slc_out = val_df.iloc[start:stop]
slc_out_tensor = self.build_input_tensor(slc_out)
num, bin, cat = self.model(slc_in_tensor)
_, _, _, net_loss = self.compute_loss(num, bin, cat, slc_out)
swapped_loss.append(net_loss)
num, bin, cat = self.model(slc_out_tensor)
_, _, _, net_loss = self.compute_loss(num, bin, cat, slc_out, _id=True)
id_loss.append(net_loss)
# Early stopping
current_net_loss = net_loss
LOG.debug('The Current Net Loss:', current_net_loss)
if current_net_loss > last_loss:
count_es += 1
LOG.debug('Early stop count:', count_es)
if count_es >= self.patience:
LOG.debug('Early stopping: early stop count({}) >= patience({})'.format(
count_es, self.patience))
break
else:
LOG.debug('Set count for earlystop: 0')
count_es = 0
last_loss = current_net_loss
self.logger.end_epoch()
if self.verbose:
swapped_loss = np.array(swapped_loss).mean()
id_loss = np.array(id_loss).mean()
msg = '\n'
msg += 'net validation loss, swapped input: \n'
msg += f"{round(swapped_loss, 4)} \n\n"
msg += 'baseline validation loss: '
msg += f"{round(baseline, 4)} \n\n"
msg += 'net validation loss, unaltered input: \n'
msg += f"{round(id_loss, 4)} \n\n\n"
LOG.debug(msg)
#Getting training loss statistics
# mse_loss, bce_loss, cce_loss, _ = self.get_anomaly_score(pdf) if pdf_val is None else self.get_anomaly_score(pd.concat([pdf, pdf_val]))
mse_loss, bce_loss, cce_loss, _ = self.get_anomaly_score_with_losses(df_for_loss_stats)
for i, ft in enumerate(self.numeric_fts):
i_loss = mse_loss[:, i]
self.feature_loss_stats[ft] = self._create_stat_dict(i_loss)
for i, ft in enumerate(self.binary_fts):
i_loss = bce_loss[:, i]
self.feature_loss_stats[ft] = self._create_stat_dict(i_loss)
for i, ft in enumerate(self.categorical_fts):
i_loss = cce_loss[:, i]
self.feature_loss_stats[ft] = self._create_stat_dict(i_loss)
def _fit_distributed(
self,
train_data,
rank,
world_size,
epochs=1,
val_data=None,
run_validation=False,
use_val_for_loss_stats=False,
):
"""Fit the model in the distributed fashion with early stopping based on validation loss.
If run_validation is True, the val_dataset will be used for validation during training and early stopping
will be applied based on patience argument.
Parameters
----------
train_data : pandas.DataFrame or torch.utils.data.Dataset or torch.utils.data.DataLoader
data object of training data
rank : int
the rank of the current process
world_size : int
the total number of processes
epochs : int, optional
the number of epochs to train for, by default 1
val_data : torch.utils.data.Dataset or torch.utils.data.DataLoader, optional
the validation data object (with __iter__() that yields a batch at a time), by default None
run_validation : bool, optional
whether to perform validation during training, by default False
use_val_for_loss_stats : bool, optional
whether to populate loss stats in the main process (rank 0) for z-score calculation using the validation set.
If set to False, loss stats would be populated using the train_dataloader, which can be slow due to data size.
By default False, but using the validation set to populate loss stats is strongly recommended (for both efficiency
and model efficacy).
Raises
------
ValueError
If run_validation or use_val_for_loss_stats is True but val is not provided.
"""
if run_validation and val_data is None:
raise ValueError("`run_validation` is set to True but the validation set (val_dataset) is not provided.")
if use_val_for_loss_stats and val_data is None:
raise ValueError("Validation set is required if either run_validation or \
use_val_for_loss_stats is set to True.")
# If train_data is in the format of a pandas df, wrap it by a dataset
train_df = None