-
Notifications
You must be signed in to change notification settings - Fork 2
/
pipeline.py
1581 lines (1368 loc) · 54.1 KB
/
pipeline.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import os
import json
import logging
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn import svm
from sklearn.base import clone
from sklearn.decomposition import PCA
from sklearn.impute import KNNImputer
from sklearn.linear_model import SGDClassifier
from sklearn.naive_bayes import GaussianNB
from menelaus import *
from menelaus.concept_drift import ADWINAccuracy, DDM, EDDM
from menelaus.data_drift import HDDDM, KdqTreeBatch, CDBD, PCACD
from menelaus.ensemble.election import SimpleMajorityElection
from menelaus.ensemble.ensemble import BatchEnsemble
from statistics import mean
from scipy import stats
from sklearn.preprocessing import OneHotEncoder
from skmultiflow.data import (
SEAGenerator,
HyperplaneGenerator,
STAGGERGenerator,
RandomRBFGeneratorDrift,
LEDGeneratorDrift,
WaveformGenerator,
)
def mkdirs(dirpath):
try:
os.makedirs(dirpath)
except Exception as e:
logging.error(f"Failed to create directory {dirpath}")
raise e
def schema_parser(path):
# info path
info_path = path + "/info.json"
logging.info(f"Start to read data info from {info_path}")
with open(info_path, "r") as f:
info = json.load(f)
schema_path = path + "/" + info["schema"]
data_path = info["data"]
task = info["task"]
return data_path, schema_path, task
def data_preprocessing(
dataset_path_prefix: str,
data_path: str,
schema_path: str,
task: str,
delete_null_target=False,
return_info=False,
):
# open the schema.json file
with open(schema_path, "r") as f:
schema: dict = json.load(f)
# numerical = schema["numerical"]
categorical = schema["categorical"]
target = schema["target"]
timestamp = schema["timestamp"]
unnecessary = schema["unnecessary"]
window_size = schema["window size"]
replace_with_null = schema.get("replace_with_null", [])
# use pandas to read the data (extension name will be judged)
if data_path.endswith(".csv"):
data = pd.read_csv(data_path)
elif data_path.endswith(".xlsx") or data_path.endswith(".xls"):
data = pd.read_excel(data_path)
else:
logging.error(f'The format of data file "{data_path}" is not supported')
raise ValueError(f"{data_path}: data format not supported")
total_columns = data.columns
original_column_count = data.shape[1]
original_data = data
# replace some values with null
logging.info("Start to replace some values with null")
for value in replace_with_null:
data = data.replace(value, np.nan)
data = data.dropna(subset=target)
logging.info(f"These values have been replaced with null: {replace_with_null}")
# sort the data by timestamp
logging.info("Start to sort the data by timestamp")
if not pd.api.types.is_datetime64_any_dtype(data[timestamp]):
for col in timestamp:
data[col] = pd.to_datetime(data[col], errors="ignore")
data = data.sort_values(timestamp, ascending=True)
logging.info("Sorting finished")
original_data = data
target_data = data[target]
data = data.drop(unnecessary, axis=1)
data = data.drop(timestamp, axis=1)
data_one_hot = data.drop(target, axis=1) # data without target
data_one_hot = pd.get_dummies(data_one_hot, columns=categorical) # no target
new_columns = data_one_hot.columns
new_column_count = new_columns.shape[0]
logging.info(f"Columns after one hot encoding: {new_columns.tolist()}")
# one hot encoding for different tasks
if task == "classification":
# factorize the target data
target_data[target[0]] = pd.factorize(target_data[target[0]])[0]
# define one hot encoder
one_hot_encoder = OneHotEncoder(sparse_output=False)
y_one_hot = one_hot_encoder.fit_transform(target_data[[target[0]]])
# update the output dimension
output_dim = y_one_hot.shape[1]
target = [f"{target[0]}_{i}" for i in range(output_dim)]
target_data = pd.DataFrame(y_one_hot, columns=target)
elif task == "regression":
output_dim = 1
else:
logging.error(f"Task {task} is not supported")
raise ValueError(f"{task}: task not supported")
# # TODO: the codes below are not all-around?
# if delete_null_target:
# return (
# pd.DataFrame(data_one_hot),
# pd.DataFrame(target_data),
# window_size,
# task,
# new_column_count,
# output_dim,
# )
# check for the existence of the file
logging.info("Start null values processing")
# if os.path.exists(dataset_path_prefix + "/onehot_nonnull.csv"):
# data_onehot_nonnull_path = dataset_path_prefix + "/onehot_nonnull.csv"
# data_onehot_nonnull = pd.read_csv(data_onehot_nonnull_path)
# else:
if data.isna().values.any():
# join target columns to the one hot data
logging.info("The dataset has null values")
temp_columns = new_columns.copy()
temp_columns.append(pd.Index(target))
data_one_hot[target] = target_data # add target to one hot data
# use KNNImputer to fill the null values
imp = KNNImputer(n_neighbors=2, weights="uniform")
# drop the rows with null target
data_one_hot = data_one_hot.dropna(subset=target)
target_data = data_one_hot[target]
data_one_hot = data_one_hot.drop(target, axis=1)
# convert all columns to numeric
non_numeric_columns = data_one_hot.select_dtypes(exclude=[np.number]).columns
for col in non_numeric_columns:
data_one_hot[col] = pd.to_numeric(data_one_hot[col], errors="coerce")
# inpute the null values
data_onehot_nonnull = imp.fit_transform(data_one_hot)
data_onehot_nonnull = pd.DataFrame(data_onehot_nonnull)
assert not data_onehot_nonnull.isnull().values.any()
else:
logging.info("The dataset has no null values")
data_onehot_nonnull = data_one_hot
logging.info("Null values processing finished")
# add the target back to the data
concat_data = [
data_onehot_nonnull.reset_index(drop=True),
target_data.reset_index(drop=True),
]
whole_data_one_hot = pd.concat(concat_data, axis=1)
# output the data without null values to a csv file
whole_data_one_hot_path = dataset_path_prefix + "/onehot_nonnull.csv"
whole_data_one_hot.to_csv(whole_data_one_hot_path, mode="w")
return (
pd.DataFrame(target_data),
pd.DataFrame(original_data),
pd.DataFrame(data_onehot_nonnull),
total_columns,
window_size,
data_onehot_nonnull.shape[0],
original_column_count,
new_columns,
new_column_count,
pd.DataFrame(data_one_hot) if return_info else None,
)
def missing_value_processor(data, window_size, total_columns, window_count, row_count):
missing_value_stats_by_window = pd.DataFrame(
index=list(range(window_count)),
columns=[
"columns_with_null",
"col_null_dict",
"empty_cells_num",
"ave_null_columns",
"ave_null_columns_ratio",
"missing_value_ratio",
],
)
column_count = len(total_columns)
ave_null_columns_ratio_list = []
missing_value_ratio_list = []
rows_with_missing_values_ratio_list = []
for n in range(window_count):
rows_with_missing_values = window_size - len(
data[n * window_size : (n + 1) * window_size].dropna()
)
current_rows_with_missing_values_ratio = rows_with_missing_values / window_size
rows_with_missing_values_ratio_list.append(
current_rows_with_missing_values_ratio
)
columns_with_null = []
col_null_dict = {}
empty_cells_num = 0
ave_null_columns = 0
for col in total_columns:
if data[n * window_size : (n + 1) * window_size][col].isnull().values.any():
columns_with_null.append(col)
current = (
data[n * window_size : (n + 1) * window_size][col].isnull().sum()
)
col_null_dict[col] = current
empty_cells_num = empty_cells_num + current
if len(columns_with_null) != 0:
ave_null_columns = empty_cells_num / window_size
ave_null_columns_ratio = ave_null_columns / column_count
missing_value_ratio = empty_cells_num / (column_count * window_size)
missing_value_stats_by_window.at[n, "columns_with_null"] = columns_with_null
missing_value_stats_by_window.at[n, "col_null_dict"] = col_null_dict
missing_value_stats_by_window.at[n, "empty_cells_num"] = empty_cells_num
missing_value_stats_by_window.at[n, "ave_null_columns"] = ave_null_columns
missing_value_stats_by_window.at[n, "ave_null_columns_ratio"] = (
ave_null_columns_ratio
)
missing_value_stats_by_window.at[n, "missing_value_ratio"] = (
missing_value_ratio
)
ave_null_columns_ratio_list.append(ave_null_columns_ratio)
missing_value_ratio_list.append(missing_value_ratio)
# 1 2 3 4
# 0 n 0 0
# 0 n n 0
# 0 n n n
try:
ave_ave_null_columns_ratio = mean(ave_null_columns_ratio_list)
max_ave_null_columns_ratio = max(ave_null_columns_ratio_list)
ave_missing_value_ratio = mean(missing_value_ratio_list)
max_missing_value_ratio = max(missing_value_ratio_list)
except:
ave_ave_null_columns_ratio = None
max_ave_null_columns_ratio = None
ave_missing_value_ratio = None
max_missing_value_ratio = None
ave_rows_with_missing_values_ratio_per_window = mean(
rows_with_missing_values_ratio_list
)
max_rows_with_missing_values_ratio_per_window = max(
rows_with_missing_values_ratio_list
)
total_rows_with_missing_value = len(data) - len(data.dropna())
total_rows_with_missing_values_ratio = total_rows_with_missing_value / len(data)
missing_value_stats_overall = pd.DataFrame(
index=[
"columns_with_null",
"col_null_dict",
"empty_cells_num",
"ave_null_columns",
],
columns=["overall"],
)
print("overall stats")
columns_with_null = []
col_null_dict = {}
empty_cells_num = 0
ave_null_columns = 0
for col in total_columns:
if data[col].isnull().values.any():
columns_with_null.append(col)
current = data[col].isnull().sum()
col_null_dict[col] = current
empty_cells_num += current
ave_null_columns = empty_cells_num / row_count
missing_value_stats_overall.at["columns_with_null", "overall"] = columns_with_null
missing_value_stats_overall.at["col_null_dict", "overall"] = col_null_dict
missing_value_stats_overall.at["empty_cells_num", "overall"] = empty_cells_num
missing_value_stats_overall.at["ave_null_columns", "overall"] = ave_null_columns
overall_ave_null_columns_ratio = ave_null_columns / column_count
overall_missing_value_ratio = empty_cells_num / (row_count * column_count)
return (
ave_rows_with_missing_values_ratio_per_window,
max_rows_with_missing_values_ratio_per_window,
total_rows_with_missing_values_ratio,
ave_ave_null_columns_ratio,
max_ave_null_columns_ratio,
ave_missing_value_ratio,
max_missing_value_ratio,
overall_ave_null_columns_ratio,
overall_missing_value_ratio,
)
# return missing_value_stats_overall, missing_value_stats_by_window
def data_drift_detector_multi_dimensional(data, window_size, window_num):
# print(data)
detectors_dict = {
"kdq": KdqTreeBatch(bootstrap_samples=500),
"hdddm": HDDDM(),
"cdbd": CDBD(),
"pcacd": PCACD(window_size=window_size),
}
training_size = window_size
reference = data.iloc[0:training_size]
# ensemble.set_reference(reference)
# print(f"Batch #{0} | Ensemble reference set")
drift_detector_list = ["hdddm", "kdq"]
drift_stats = pd.DataFrame([])
hdddm_drift_percentage = 0
kdq_drift_percentage = 0
hdddm_warning_percentage = 0
kdq_warning_percentage = 0
for algo in drift_detector_list:
# print(algo)
drift_count = 0
drift_percentage = 0
detected_drift = []
warning_count = 0
warning_percentage = 0
detected_warning = []
detectors = {algo: detectors_dict[algo]}
election = SimpleMajorityElection()
ensemble = BatchEnsemble(detectors, election)
# print("start reference")
# print(reference)
ensemble.set_reference(reference)
# print("start updating")
# print(window_num)
for n in range(1, window_num):
# print(n)
ensemble.update(data[n * window_size : (n + 1) * window_size])
detected_drift.append(ensemble.drift_state)
if ensemble.drift_state == "drift":
drift_count += 1
elif ensemble.drift_state == "warning":
warning_count += 1
# print(detected_drift)
drift_percentage = drift_count / (window_num - 1)
warning_percentage = warning_count / (window_num - 1)
drift_stats[algo] = [drift_percentage]
if algo == "hdddm":
hdddm_drift_percentage = drift_percentage
hdddm_warning_percentage = warning_percentage
else:
kdq_drift_percentage = drift_percentage
kdq_warning_percentage = warning_percentage
# print(drift_percentage)
ave_drift_percentage = (hdddm_drift_percentage + kdq_drift_percentage) / 2
ave_warning_percentage = (hdddm_warning_percentage + kdq_warning_percentage) / 2
print(drift_stats)
return (
hdddm_drift_percentage,
kdq_drift_percentage,
ave_drift_percentage,
hdddm_warning_percentage,
kdq_warning_percentage,
ave_warning_percentage,
)
# return drift_stats
def data_drift_detector_one_dimensional(data, window_size, window_num, columns):
detectors_dict = {
"kdq": KdqTreeBatch(bootstrap_samples=500),
"hdddm": HDDDM(),
"cdbd": CDBD(),
}
training_size = window_size
drift_stats_each_column = pd.DataFrame(
columns=columns, index=["hdddm", "kdq", "cdbd"]
)
drift_detector_list = ["hdddm", "kdq", "cdbd"]
# print(data)
hdddm_ave_drift_percentage = 0
hdddm_max_drift_percentage = 0
kdq_ave_drift_percentage = 0
kdq_max_drift_percentage = 0
cbdb_ave_drift_percentage = 0
cbdb_max_drift_percentage = 0
ks_ave_drift_percentage = 0
ks_max_drift_percentage = 0
ave_drift_percentage = 0
max_drift_percentage = 0
hdddm_ave_warning_percentage = 0
hdddm_max_warning_percentage = 0
kdq_ave_warning_percentage = 0
kdq_max_warning_percentage = 0
cbdb_ave_warning_percentage = 0
cbdb_max_warning_percentage = 0
ks_ave_warning_percentage = 0
ks_max_warning_percentage = 0
ks_drift_percentage_list = []
ks_warning_percentage_list = []
for col in columns:
reference = data[col].iloc[0:training_size]
pvalue = 0.05
ks_detected_drift = []
ks_drift_count = 0
ks_drift_percentage = 0
ks_warning_count = 0
ks_warning_percentage = 0
for n in range(1, window_num):
current_data = data[col].iloc[n * window_size : (n + 1) * window_size]
test = stats.ks_2samp(reference, current_data)
if test[1] < pvalue: # drift
ks_drift_count += 1
ks_detected_drift.append("drift")
elif test[1] < pvalue * 2: # warning
ks_warning_count += 1
ks_detected_drift.append("warning")
else:
ks_detected_drift.append(None)
ks_drift_percentage = ks_drift_count / (window_num - 1)
ks_drift_percentage_list.append(ks_drift_percentage)
ks_warning_percentage = ks_warning_count / (window_num - 1)
ks_warning_percentage_list.append(ks_warning_percentage)
ks_ave_drift_percentage = mean(ks_drift_percentage_list)
ks_max_drift_percentage = max(ks_drift_percentage_list)
print("ks warning")
print(ks_warning_percentage_list)
ks_ave_warning_percentage = mean(ks_warning_percentage_list)
ks_max_warning_percentage = max(ks_warning_percentage_list)
print(ks_ave_warning_percentage)
print(ks_max_warning_percentage)
ave_warning_percentage = 0
max_warning_percentage = 0
for algo in drift_detector_list:
current_detector = detectors_dict[algo]
drift_percentage_list = []
warning_percentage_list = []
for col in columns:
# print("column: "+col)
reference = data[col].iloc[0:training_size]
# print(reference)
current_detector.set_reference(reference)
detected_drift = []
drift_count = 0
drift_percentage = 0
warning_count = 0
warning_percentage = 0
for n in range(1, window_num):
# print(n)
curr = data[col].iloc[n * window_size : (n + 1) * window_size]
# print(curr)
try:
current_detector.update(curr)
detected_drift.append(current_detector.drift_state)
if current_detector.drift_state == "drift":
drift_count += 1
elif current_detector.drift_state == "warning":
warning_count += 1
except:
continue
drift_percentage = drift_count / (window_num - 1)
drift_stats_each_column.loc[algo][col] = drift_percentage
drift_percentage_list.append(drift_percentage)
warning_percentage = warning_count / (window_num - 1)
warning_percentage_list.append(warning_percentage)
ave = mean(drift_percentage_list)
maximum = max(drift_percentage_list)
# print(algo)
# print("warning")
# print(warning_percentage_list)
warning_ave = mean(warning_percentage_list)
warning_maximum = max(warning_percentage_list)
# print(warning_ave)
# print(warning_maximum)
if algo == "hdddm":
hdddm_ave_drift_percentage = ave
hdddm_max_drift_percentage = maximum
hdddm_ave_warning_percentage = warning_ave
hdddm_max_warning_percentage = warning_maximum
elif algo == "kdq":
kdq_ave_drift_percentage = ave
kdq_max_drift_percentage = maximum
kdq_ave_warning_percentage = warning_ave
kdq_max_warning_percentage = warning_maximum
else:
cbdb_ave_drift_percentage = ave
cbdb_max_drift_percentage = maximum
cbdb_ave_warning_percentage = warning_ave
cbdb_max_warning_percentage = warning_maximum
ave_drift_percentage = mean(
[
ks_ave_drift_percentage,
hdddm_ave_drift_percentage,
kdq_ave_drift_percentage,
cbdb_ave_drift_percentage,
]
)
max_drift_percentage = max(
[
ks_max_drift_percentage,
hdddm_ave_drift_percentage,
kdq_ave_drift_percentage,
cbdb_ave_drift_percentage,
]
)
ave_warning_percentage = mean(
[
ks_ave_warning_percentage,
hdddm_ave_warning_percentage,
kdq_ave_warning_percentage,
cbdb_ave_warning_percentage,
]
)
max_warning_percentage = max(
[
ks_max_warning_percentage,
hdddm_ave_warning_percentage,
kdq_ave_warning_percentage,
cbdb_ave_warning_percentage,
]
)
# status = pd.DataFrame(columns=["index", "var1", "var2", "drift_detected"])
pca_cd = PCACD(window_size=window_size, divergence_metric="intersection")
pca = PCA(n_components=2)
pca_features = pca.fit_transform(data)
pca_df = pd.DataFrame(data=pca_features, columns=["var1", "var2"])
print("pca df:")
print(pca_df)
drift_stats_pca = pd.DataFrame(columns=["var1", "var2"])
var1_drift_percentage = 0
var2_drift_percentage = 0
pca_ave_drift_percentage = 0
pca_max_drift_percentage = 0
var1_warning_percentage = 0
var2_warning_percentage = 0
pca_ave_warning_percentage = 0
pca_max_warning_percentage = 0
for col in ["var1", "var2"]:
detected_drift = []
drift_count = 0
drift_percentage = 0
for n in range(0, window_num):
# print(n)
# print(pca_df[n*window_size:(n+1)*window_size, col])
pca_cd.update(pca_df[col].iloc[n * window_size : (n + 1) * window_size])
detected_drift.append(pca_cd.drift_state)
if pca_cd.drift_state == "drift":
drift_count += 1
elif pca_cd.drift_state == "warning":
warning_count += 1
drift_percentage = drift_count / (window_num)
if col == "var1":
var1_drift_percentage = drift_percentage
var1_warning_percentage = warning_percentage
else:
var2_drift_percentage = drift_percentage
var2_warning_percentage = warning_percentage
drift_stats_pca.loc[col] = drift_percentage
pca_ave_drift_percentage = (var1_drift_percentage + var2_drift_percentage) / 2
pca_max_drift_percentage = max([var1_drift_percentage, var2_drift_percentage])
pca_ave_warning_percentage = (var1_warning_percentage + var2_warning_percentage) / 2
pca_max_warning_percentage = max([var1_warning_percentage, var2_warning_percentage])
return (
ks_ave_drift_percentage,
ks_max_drift_percentage,
hdddm_ave_drift_percentage,
hdddm_max_drift_percentage,
kdq_ave_drift_percentage,
kdq_max_drift_percentage,
cbdb_ave_drift_percentage,
cbdb_max_drift_percentage,
pca_ave_drift_percentage,
pca_max_drift_percentage,
ave_drift_percentage,
max_drift_percentage,
hdddm_ave_warning_percentage,
hdddm_max_warning_percentage,
kdq_ave_warning_percentage,
kdq_max_warning_percentage,
cbdb_ave_warning_percentage,
cbdb_max_warning_percentage,
pca_ave_warning_percentage,
pca_max_warning_percentage,
ks_ave_warning_percentage,
ks_max_warning_percentage,
ave_warning_percentage,
max_warning_percentage,
)
# return drift_stats_each_column, drift_stats_pca
from menelaus.ensemble import BatchEnsemble, StreamingEnsemble
from menelaus.concept_drift import LinearFourRates, ADWINAccuracy, DDM, EDDM, STEPD, MD3
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import log_loss
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from sklearn.metrics import r2_score
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import SGDRegressor, SGDClassifier
def PERM(
task,
data,
target,
window_size,
window_count,
number_of_permutation,
sensitivity,
significance_rate,
):
t = 0
k = window_size
# drift_percentage = 0
# drift_detected_list = []
drift_count = 0
while k < len(data):
reference = data[t:k]
reference_target = target[t:k]
current = data[k : k + window_size]
current_target = target[k : k + window_size]
detected = perm_detect(
task,
reference,
current,
reference_target,
current_target,
number_of_permutation,
sensitivity,
significance_rate,
)
if detected == True:
drift_count += 1
t = k
k = k + window_size
drift_percentage = drift_count / (window_count - 1)
print("perm")
print(drift_percentage)
return drift_percentage
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import log_loss
from sklearn.metrics import mean_squared_error
from sklearn.metrics import accuracy_score
from sklearn.metrics import r2_score, mean_absolute_error
from sklearn.linear_model import SGDRegressor, SGDClassifier, LinearRegression
def perm_detect(
task,
reference,
current,
reference_target,
current_target,
number_of_permutation,
sensitivity,
significance_rate,
):
reference_size = len(reference)
current_size = len(current)
total_size = reference_size + current_size
data = pd.concat([reference, current])
target = pd.concat([reference_target, current_target])
test_size_ratio = current_size / total_size
ordered_loss = 1
if task == "regression":
rf = LinearRegression()
try:
rf.fit(reference, reference_target)
except:
return False
ordered_y_pred = rf.predict(current)
ordered_y_pred = pd.DataFrame(ordered_y_pred)
# print("reference")
# print(reference)
# print("reference target")
# print(reference_target)
# print("current")
# print(current)
# print("current target")
# print(current_target)
# print("predicted")
# print(ordered_y_pred)
# print("regression")
ordered_loss = mean_absolute_error(
np.array(current_target), np.array(ordered_y_pred)
)
# print(ordered_loss)
y_range = np.max(np.array(current_target)) - np.min(np.array(current_target))
ordered_loss = ordered_loss / y_range
else:
# print("reference")
# print(reference)
# print("reference target")
# print(reference_target)
# rf = SGDClassifier(random_state = 42)
try:
rf.fit(reference, reference_target)
except:
return False
rf.fit(reference, reference_target)
ordered_y_pred = rf.predict(current)
ordered_y_pred = pd.DataFrame(ordered_y_pred)
# ordered_y_pred = ordered_y_pred.reshape()
# print("classification")
# ordered_loss = log_loss(current_target, ordered_y_pred)
ordered_loss = 1 - accuracy_score(current_target, ordered_y_pred)
# print("ordered loss")
# print(ordered_loss)
count = 0
for i in range(number_of_permutation):
X_train, X_test, y_train, y_test = train_test_split(
data, target, test_size=test_size_ratio, random_state=None, shuffle=True
)
if task == "regression":
rf = LinearRegression()
rf.fit(X_train, y_train)
current_y_pred = rf.predict(X_test)
# print("regression")
current_y_pred = pd.DataFrame(current_y_pred)
current_loss = mean_absolute_error(
np.array(y_test), np.array(current_y_pred)
)
y_range = np.max(np.array(y_test)) - np.min(np.array(y_test))
current_loss = current_loss / y_range
# print(current_loss)
else:
rf = SGDClassifier(random_state=42)
rf.fit(X_train, y_train)
try:
rf.fit(X_train, y_train)
except:
return False
current_y_pred = rf.predict(X_test)
current_y_pred = pd.DataFrame(current_y_pred)
# current_y_pred=current_y_pred.reshape(-1,1)
# print("classification")
# current_loss = log_loss(y_test, current_y_pred)
current_loss = 1 - accuracy_score(y_test, current_y_pred)
# print(current_loss)
if abs(ordered_loss - current_loss) <= sensitivity:
count += 1
# print("count")
# print(count)
value = (1 + count) / (1 + number_of_permutation)
if value <= significance_rate:
return True
else:
return False
import warnings
from ADBench.baseline.PyOD import PYOD
warnings.filterwarnings("ignore")
def outlier_detector(data, window_size, window_count):
seed = 42
model_dict = {
"ECOD": PYOD,
"IForest": PYOD,
}
outlier_stats_each_window = pd.DataFrame(
index=["ECOD", "IForest", "mean"], columns=list(range(1, window_count))
)
# outlier_stats_overall = pd.DataFrame(columns = ['ECOD', 'IForest', "mean"])
outlier_stats_overall = {}
anomaly_count_list = []
anomaly_index = []
anomaly_sum = 0
IForest_ave_anomaly_ratio_list = []
ECOD_ave_anomaly_ratio_list = []
IForest_overall_anomaly_ratio = 0
ECOD_overall_anomaly_ratio = 0
for name, clf in model_dict.items():
# print(name)
clf = clf(seed=seed, model_name=name)
clf = clf.fit(data, [])
# output predicted anomaly score on testing set
score = clf.predict_score(data)
# print(score)
t = score.mean() + 3 * score.std()
# print(t)
anomaly_index = np.where(score > t)[0]
# print(anomaly_index)
anomaly_count = len(anomaly_index)
anomaly_sum = anomaly_sum + anomaly_count
anomaly_count_list.append(anomaly_count)
# print(anomaly_count)
outlier_stats_overall[name] = anomaly_count
anomaly_ratio = anomaly_count / (len(data))
if name == "ECOD":
ECOD_overall_anomaly_ratio = anomaly_ratio
else:
IForest_overall_anomaly_ratio = anomaly_ratio
for n in range(window_count):
anomaly_count_current_window = 0
for pos in anomaly_index:
start = n * window_size
end = (n + 1) * window_size
if pos >= start and pos < end:
anomaly_count_current_window += 1
# print(anomaly_count_current_window)
outlier_stats_each_window.loc[name][n] = anomaly_count_current_window
anomaly_ratio_current_window = anomaly_count_current_window / window_size
if name == "IForest":
IForest_ave_anomaly_ratio_list.append(anomaly_ratio_current_window)
else:
ECOD_ave_anomaly_ratio_list.append(anomaly_ratio_current_window)
IForest_ave_anomaly_ratio = mean(IForest_ave_anomaly_ratio_list)
IForest_max_anomaly_ratio = max(IForest_ave_anomaly_ratio_list)
ECOD_ave_anomaly_ratio = mean(ECOD_ave_anomaly_ratio_list)
ECOD_max_anomaly_ratio = max(ECOD_ave_anomaly_ratio_list)
ave = anomaly_sum / 2
ave_overall_anomaly_ratio = ave / (len(data))
outlier_stats_overall["mean"] = ave
ave_anomaly_ratio_list = []
for n in range(1, window_count):
outlier_stats_each_window.loc["mean"][n] = (
outlier_stats_each_window.loc["IForest"][n]
+ outlier_stats_each_window.loc["ECOD"][n]
) / 2
ave_anomaly_ratio_list.append(
(outlier_stats_each_window.loc["mean"][n]) / window_size
)
mean_ave_anomaly_ratio = mean(ave_anomaly_ratio_list)
max_ave_anomaly_ratio = max(ave_anomaly_ratio_list)
# print(outlier_stats_overall)
return (
IForest_ave_anomaly_ratio,
IForest_max_anomaly_ratio,
ECOD_ave_anomaly_ratio,
ECOD_max_anomaly_ratio,
mean_ave_anomaly_ratio,
max_ave_anomaly_ratio,
ECOD_overall_anomaly_ratio,
IForest_overall_anomaly_ratio,
ave_overall_anomaly_ratio,
)
# return outlier_stats_each_window, outlier_stats_overall
from sklearn.naive_bayes import GaussianNB
def concept_drift(task, data, target, window_size, window_count):
training_size = window_size
# X_test = data.iloc[training_size:len(data)]
# y_true = target.iloc[training_size:len(data)]
start = 0
end = training_size
if task == "regression":
clf = LinearRegression()
X_train = data.iloc[start:end]
y_train = target.iloc[start:end]
clf.fit(X_train, y_train)
else:
clf = GaussianNB()
for i in range(1, window_count):
end = end * i
X_train = data.iloc[start:end]
y_train = target.iloc[start:end]
try:
clf.fit(X_train, y_train)
break
except:
continue
adwin = ADWINAccuracy()
ddm = DDM(n_threshold=100, warning_scale=7, drift_scale=10)
eddm = EDDM(n_threshold=30, warning_thresh=0.7, drift_thresh=0.5)
adwin_count = 0
ddm_count = 0
eddm_count = 0
adwin_warning_count = 0
ddm_warning_count = 0
eddm_warning_count = 0
for i in range(end, len(data)):
X_test = data.iloc[i]
X_test = np.array(X_test).reshape(1, -1)
# print(X_test)
y_pred = clf.predict(X_test)
# if(task=="classification"):