-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1066 lines (958 loc) · 50.1 KB
/
main.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 local_ocpa.ocpa.algo.predictive_monitoring.factory
from gnn_utils import *
from local_ocpa.ocpa.objects.log.importer.csv import factory as csv_import_factory
from local_ocpa.ocpa.objects.log.importer.ocel import factory as ocel_import_factory
from local_ocpa.ocpa.algo.predictive_monitoring import factory as predictive_monitoring
from local_ocpa.ocpa.objects.log.util import misc as log_util
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, mean_squared_error
from sklearn.metrics import accuracy_score
import pandas as pd
from graph_embedding import convert_to_nx_graphs, embed
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.neural_network import MLPRegressor, MLPClassifier
from tqdm import tqdm
params = {"sap": {"batch_size": 4, "lr": 0.001, "epochs": 15}}
NEXT_ACTIVITY = "next_activity"
def next_activity(node, ocel, params):
act = params[0]
e_id = node.event_id
out_edges = ocel.graph.eog.out_edges(e_id)
next_act = 0
for (source, target) in out_edges:
if ocel.get_value(target, "event_activity") == act:
next_act = 1
for (source_, target_) in out_edges:
if ocel.get_value(target_, "event_timestamp") < ocel.get_value(target, "event_timestamp"):
next_act = 0
return next_act
NEXT_TIMESTAMP = "next_timestamp"
def next_timestamp(node, ocel, params):
e_id = node.event_id
out_edges = ocel.graph.eog.out_edges(e_id)
if len(out_edges) == 0:
# placeholder, will not be used for prediction
return 0
return min([ocel.get_value(target, "event_timestamp") for (source, target) in out_edges]).to_pydatetime().timestamp() - ocel.get_value(e_id, "event_timestamp").to_pydatetime().timestamp()
REL_ACTIVITY_OCCURRENCE_PER_TYPE ="act_occurrence_p_type"
def relative_activity_occurence(node,ocel,params):
ots = params[0]
acts = params[1]
results_dict = {(ot,act):0 for (ot,act) in itertools.product(ots, acts)}
e_id = node.event_id
case = ocel.process_executions[node.pexec_id]
pexec_objects = ocel.process_execution_objects[node.pexec_id]
oc_counter = {act:{(ot_,o):False for (ot_,o) in pexec_objects} for act in acts}
this_timestamp = ocel.get_value(e_id,"event_timestamp")
for e in case:
if ocel.get_value(e,"event_timestamp") > this_timestamp:
continue
else:
curr_act = ocel.get_value(e,"event_activity")
ev_ob_dict = {}
for ot_iter in ots:
ev_ob_dict[ot_iter] = [o for o in ocel.get_value(e_id,ot_iter)]
for (ot_,o) in pexec_objects:
if o in ev_ob_dict[ot_]:
oc_counter[curr_act][(ot_,o)] = True
rel_counter = 0
for curr_act in acts:
for curr_ot in ots:
curr_ot_obs = [(ot_,o) for (ot_,o) in pexec_objects if ot_ == curr_ot]
for (ot_,o) in curr_ot_obs:
if oc_counter[curr_act][(ot_,o)]:
rel_counter += 1
results_dict[(curr_ot,curr_act)] = rel_counter/len(curr_ot_obs)
return results_dict
local_ocpa.ocpa.algo.predictive_monitoring.factory.VERSIONS[
local_ocpa.ocpa.algo.predictive_monitoring.factory.EVENT_BASED][REL_ACTIVITY_OCCURRENCE_PER_TYPE] = relative_activity_occurence
local_ocpa.ocpa.algo.predictive_monitoring.factory.VERSIONS[
local_ocpa.ocpa.algo.predictive_monitoring.factory.EVENT_BASED][NEXT_ACTIVITY] = next_activity
local_ocpa.ocpa.algo.predictive_monitoring.factory.VERSIONS[
local_ocpa.ocpa.algo.predictive_monitoring.factory.EVENT_BASED][NEXT_TIMESTAMP] = next_timestamp
def tf_acc_score(test_target,res):
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_target, res)
acc_score = m.result().numpy()
return acc_score
def filter_process_executions(ocel, cases):
events = [e for case in cases for e in case]
new_event_df = ocel.log.log.loc[ocel.log.log["event_id"].isin(
events)].copy()
new_log = log_util.copy_log_from_df(new_event_df, ocel.parameters)
return new_log
def cat_target_to_vector(feature_storage, targets, new_name):
# targets needs to be ordered
for g in feature_storage.feature_graphs:
for node in g.nodes:
vec = [node.attributes[t] for t in targets]
vec = [1 if e == max(vec) else 0 for e in vec]
node.attributes[new_name] = vec
for t in targets:
del node.attributes[t]
return feature_storage
def GNN_prediction(layer_size, x_train, y_train, x_val, y_val, x_test, y_test, batch_size=64, lr=0.01, n_output=1):
# return 0,0,0,0
train_loader = GraphDataLoader(
x_train,
y_train,
batch_size=batch_size,
shuffle=True,
add_self_loop=True,
make_bidirected=False,
on_gpu=False
)
val_loader = GraphDataLoader(
x_val,
y_val,
batch_size=batch_size,
shuffle=True,
add_self_loop=True,
make_bidirected=False,
on_gpu=False
)
test_loader = GraphDataLoader(
x_test,
y_test,
batch_size=128,
shuffle=False,
add_self_loop=True,
make_bidirected=False,
on_gpu=False
)
# define GCN model
tf.keras.backend.clear_session()
model = None
# regression
if n_output == 1:
model = GCN(layer_size, layer_size)
optimizer = tf.keras.optimizers.Adam(lr=lr)
loss_function = tf.keras.losses.MeanSquaredError()
else:
model = ClassificationGCN(layer_size, layer_size, n_output)
optimizer = tf.keras.optimizers.Adam(lr=lr)
loss_function = tf.keras.losses.MeanSquaredError()
# run tensorflow training loop
epochs = 20
iter_idx = np.arange(0, train_loader.__len__())
loss_history = []
val_loss_history = []
step_losses = []
for e in range(epochs):
print('Running epoch:', e)
np.random.shuffle(iter_idx)
current_loss = step = 0
for batch_id in tqdm(iter_idx):
step += 1
dgl_batch, label_batch = train_loader.__getitem__(batch_id)
# if n_output != 1:
# label_batch = tf.reshape(label_batch, (int(label_batch.shape[0] * label_batch.shape[1]),))
with tf.GradientTape() as tape:
pred = model(dgl_batch, dgl_batch.ndata['features'])
# print(pred.shape)
# if n_output != 1:
# pred = tf.reshape(pred, (int(pred.shape[0] * pred.shape[1]),))
loss = loss_function(label_batch, pred)
gradients = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(
zip(gradients, model.trainable_variables))
step_losses.append(loss.numpy())
current_loss += loss.numpy()
# if (step % 100 == 0): print('Loss: %s'%((current_loss / step)))
loss_history.append(current_loss / step)
val_predictions, val_labels = evaluate_gnn(val_loader, model)
val_loss = 0
if n_output == 1:
val_loss = tf.keras.metrics.mean_squared_error(
np.squeeze(val_labels), np.squeeze(val_predictions)).numpy()
#val_loss = tf.keras.metrics.mean_absolute_error(
# np.squeeze(val_labels), np.squeeze(val_predictions)).numpy()
print(' Validation MAE GNN:', val_loss)
if len(val_loss_history) < 1:
model.save_weights('gnn_checkpoint.tf')
print(' GNN checkpoint saved.')
else:
if val_loss < np.min(val_loss_history):
model.save_weights('gnn_checkpoint.tf')
print(' GNN checkpoint saved.')
else:
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(val_labels, val_predictions)
m.result().numpy()
# tf.keras.metrics.categorical_accuracy(val_labels, val_predictions).numpy()
val_loss = m.result().numpy()
print(' Validation Accuracy GNN:', val_loss)
if len(val_loss_history) < 1:
model.save_weights('gnn_checkpoint.tf')
print(' GNN checkpoint saved.')
else:
if val_loss > np.min(val_loss_history):
model.save_weights('gnn_checkpoint.tf')
print(' GNN checkpoint saved.')
val_loss_history.append(val_loss)
# visualize training progress
pd.DataFrame({'loss': loss_history, 'step_losses': step_losses}).plot(
subplots=True, layout=(1, 2), sharey=True)
# restore weights from best epoch
cp_status = model.load_weights('gnn_checkpoint.tf')
cp_status.assert_consumed()
# generate predictions and calculate MAE for train, val & test sets
train_predictions, train_labels = evaluate_gnn(train_loader, model)
val_predictions, val_labels = evaluate_gnn(val_loader, model)
test_predictions, test_labels = evaluate_gnn(test_loader, model)
# regression
if n_output == 1:
mean_prediction = np.mean(np.array(y_train))
print('MAE baseline: ')
baseline = mean_absolute_error(
test_labels, np.repeat(mean_prediction, len(test_labels)))
print(mean_absolute_error(test_labels, np.repeat(
mean_prediction, len(test_labels))))
print('MAE GNN: ')
test_score = mean_absolute_error(test_predictions, test_labels)
print(test_score)
train_score = mean_absolute_error(train_predictions, train_labels)
val_score = mean_absolute_error(val_predictions, val_labels)
# classification
else:
agg_elems = sum(train_labels)
majority = list(agg_elems).index(max(list(agg_elems)))
max_elem_prediction = [
1 if i == majority else 0 for i in range(0, len(agg_elems))]
print("Accuracy baseline: ")
baseline_predictions = [
max_elem_prediction for i in range(0, len(test_labels))]
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_labels, baseline_predictions)
baseline = m.result().numpy()
print(baseline)
print('Accuracy GNN: ')
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_labels, test_predictions)
test_score = m.result().numpy()
print(test_score)
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(train_labels, train_predictions)
train_score = m.result().numpy()
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(val_labels, val_predictions)
val_score = m.result().numpy()
return baseline, train_score, val_score, test_score
def get_dataframe_from_graph(graph):
df = pd.read_csv(filename)
lst_data = {}
for i in range(len(graph)):
lst_index = graph[i].ndata['event_indices'].tolist()
lst_values = graph[i].ndata[predictive_monitoring.EVENT_REMAINING_TIME].tolist()
lst_index_rt = {k: v for k, v in zip(lst_index, lst_values)}
lst_data.update(lst_index_rt)
temp_df = df.loc[df['event_id'].isin(lst_data.keys())]
temp_df[predictive_monitoring.EVENT_REMAINING_TIME] = temp_df['event_id'].map(lst_data)
temp_df = temp_df.dropna()
return temp_df
def Bayesian_nets_prediction(x_train, x_val, x_test):
x_train_df = get_dataframe_from_graph(x_train)
# x_val_df = get_dataframe_from_graph(x_val)
x_test_df = get_dataframe_from_graph(x_test)
numerical_cols = x_train_df.select_dtypes(include=["int64", "float64"]).columns.tolist()
categorical_cols = x_train_df.select_dtypes(include=["object"]).columns.tolist()
# Rergetmove the ta variable from the numerical columns list
numerical_cols.remove(predictive_monitoring.EVENT_REMAINING_TIME)
# Define transformers in the pipeline
numerical_transformer = Pipeline(steps=[("scaler", StandardScaler())])
categorical_transformer = Pipeline(
steps=[("label_encoder", OneHotEncoder(handle_unknown="ignore"))]
)
preprocessor = ColumnTransformer(
transformers=[
("num", numerical_transformer, numerical_cols),
("cat", categorical_transformer, categorical_cols),
]
)
# Final pipeline with adaboost as the estimator
pipeline = Pipeline(
steps=[
("preprocessor", preprocessor),
("regressor", AdaBoostRegressor()),
]
)
X = x_train_df.drop(predictive_monitoring.EVENT_REMAINING_TIME, axis=1)
Y = x_train_df[predictive_monitoring.EVENT_REMAINING_TIME]
# Fitting
pipeline.fit(X, Y)
# Predictions
prediction = pipeline.predict(x_test_df.drop(predictive_monitoring.EVENT_REMAINING_TIME, axis=1))
# Calculate the score
score = mean_absolute_error(x_test_df[predictive_monitoring.EVENT_REMAINING_TIME], prediction)
return score
#
filename = "BPI2017-Final.csv"
lr = 0.01
batch_size = 256
object_types = ["application", "offer"]
parameters = {"obj_names": object_types,
"val_names": [],
"act_name": "event_activity",
"time_name": "event_timestamp",
"sep": ","}
ocel = csv_import_factory.apply(file_path=filename, parameters=parameters)
ks = [2, 3, 4, 5, 6, 7, 8]
# ks = [i for i in range(8,1,-1)]
#ks = [8]
# This is a small test log
# filename = "p2p-normal.jsonocel"
# ocel = ocel_import_factory.apply(filename)
# lr = 0.01
# batch_size = 32
# ks = [4]
# This is the order management event log
# filename = "orders.jsonocel"
# #parameters = {"execution_extraction": "leading_type",
# # "leading_type": "items"}
# ocel = ocel_import_factory.apply(filename)#, parameters=parameters)
# lr = 0.01
# batch_size = 256
# ks = [2,3,4,5,6,7,8]
# ks = [i for i in range(8,1,-1)]
print("Number of process executions: "+str(len(ocel.process_executions)))
print("Average lengths: " +
str(sum([len(e) for e in ocel.process_executions])/len(ocel.process_executions)))
activities = list(set(ocel.log.log["event_activity"].tolist()))
print(str(len(activities))+" actvities")
accuracy_dict = {}
for target in [[(NEXT_ACTIVITY, (act,)) for act in activities]]:
include_last = False
F = target+[(predictive_monitoring.EVENT_SYNCHRONIZATION_TIME, ())]
feature_storage = predictive_monitoring.apply(ocel, F, [])
# replace synchronization time with 0 placeholder for empty feature
for g in feature_storage.feature_graphs:
for n in g.nodes:
n.attributes[('event_synchronization_time', ())] = 1
feature_storage.extract_normalized_train_test_split(0.3, state=3)
for g in feature_storage.feature_graphs:
for n in g.nodes:
n.attributes[('event_synchronization_time', ())] = 1
# replace categorical features with vector
new_target_name = (target[0][0], ())
feature_storage = cat_target_to_vector(
feature_storage, target, new_target_name)
for k in ks:
if True:
print("___________________________")
print("Prediction with Bayesian Networks")
print("___________________________")
layer_size = len(F)-1
# generate training & test datasets
train_idx, val_idx = train_test_split(
feature_storage.training_indices, test_size=0.2)
x_train, y_train = generate_graph_dataset(
feature_storage.feature_graphs, train_idx, ocel, k=k, target=target, include_last=include_last)
x_val, y_val = generate_graph_dataset(
feature_storage.feature_graphs, val_idx, ocel, k=k, target=target, include_last=include_last)
x_test, y_test = generate_graph_dataset(
feature_storage.feature_graphs, feature_storage.test_indices, ocel, k=k, target=target, include_last=include_last)
start_time = time.time()
final_score = Bayesian_nets_prediction(x_train, x_val, x_test)
calc_time = time.time() - start_time
# We save the same score for all the metrics to fit the format of the other methods but only the test_MAE is relevant
accuracy_dict[target[0]+'graph_gnn_k_' + str(k)] = {
'baseline_MAE': final_score,
'train_MAE': final_score,
'val_MAE': final_score,
'test_MAE': final_score,
"time":calc_time
}
print(pd.DataFrame(accuracy_dict))
if True:
print("___________________________")
print("Prediction with Graph Structure and GNN")
print("___________________________")
layer_size = len(F)-len(target)
# generate training & test datasets
train_idx, val_idx = train_test_split(
feature_storage.training_indices, test_size=0.2)
x_train, y_train = generate_graph_dataset(
feature_storage.feature_graphs, train_idx, ocel, k=k, target=new_target_name, include_last=include_last)
x_val, y_val = generate_graph_dataset(
feature_storage.feature_graphs, val_idx, ocel, k=k, target=new_target_name, include_last=include_last)
x_test, y_test = generate_graph_dataset(
feature_storage.feature_graphs, feature_storage.test_indices, ocel, k=k, target=new_target_name, include_last=include_last)
start_time = time.time()
baseline_MAE, train_MAE, val_MAE, test_MAE = GNN_prediction(
layer_size, x_train, y_train, x_val, y_val, x_test, y_test, batch_size=batch_size, lr=lr, n_output=len(activities))
calc_time = time.time() - start_time
# record performance of GNN
accuracy_dict[new_target_name[0]+'_graph_gnn_k_' + str(k)] = {
'baseline_ACC': baseline_MAE,
'train_ACC': train_MAE,
'val_ACC': val_MAE,
'test_ACC': test_MAE,
"time":calc_time
}
print(pd.DataFrame(accuracy_dict))
if True:
print("___________________________")
print("Prediction with Sequential Structure and GNN")
print("___________________________")
layer_size = len(F) - len(target)
train_idx, val_idx = train_test_split(
feature_storage.training_indices, test_size=0.2)
x_train, y_train = generate_sequential_graph_dataset(feature_storage.feature_graphs, train_idx, ocel, k=k,
target=new_target_name, include_last=include_last)
x_val, y_val = generate_sequential_graph_dataset(feature_storage.feature_graphs, val_idx, ocel, k=k,
target=new_target_name, include_last=include_last)
x_test, y_test = generate_sequential_graph_dataset(feature_storage.feature_graphs,
feature_storage.test_indices, ocel, k=k, target=new_target_name,
include_last=include_last)
start_time= time.time()
baseline_MAE, train_MAE, val_MAE, test_MAE = GNN_prediction(layer_size, x_train, y_train, x_val, y_val,
x_test, y_test, batch_size=batch_size, lr=lr,
n_output=len(activities))
calc_time = time.time() - start_time
# record performance of GNN
accuracy_dict[new_target_name[0] + '_flat_gnn_k_' + str(k)] = {
'baseline_ACC': baseline_MAE,
'train_ACC': train_MAE,
'val_ACC': val_MAE,
'test_ACC': test_MAE,
"time":calc_time
}
print(pd.DataFrame(accuracy_dict))
if True:
print("___________________________")
print("Prediction with Graph Embedding")
print("___________________________")
train_nx_feature_graphs = []
test_nx_feature_graphs = []
train_target = []
test_target = []
print("Constructing Subgraphs ")
for i in tqdm(feature_storage.training_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=new_target_name,
from_start=False, include_last=include_last)
train_nx_feature_graphs += converted_subgraphs
train_target += extracted_targets
for i in tqdm(feature_storage.test_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=new_target_name,
from_start=False, include_last=include_last)
test_nx_feature_graphs += converted_subgraphs
test_target += extracted_targets
for embedding_technique in [
'Graph2Vec', 'NetLSD', 'WaveletCharacteristic',
'LDP', 'GL2Vec', 'SF', 'FGSD']:
try:
start_time = time.time()
X_train, X_test = embed(
train_nx_feature_graphs, test_nx_feature_graphs, embedding_technique, size=10*k)
calc_time = time.time() -start_time
print(X_train.shape)
print(X_test.shape)
model = LogisticRegression(multi_class='multinomial')
model.fit(X_train, [ys.index(1) for ys in train_target])
res = model.predict(X_test)
acc_score = accuracy_score(
[ys.index(1) for ys in test_target], res)
print(accuracy_score([ys.index(1)
for ys in test_target], res))
accuracy_dict[new_target_name[0]+'_embed_reg_' + embedding_technique+'_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': acc_score,
'time': calc_time
}
regr = MLPClassifier(random_state=3, max_iter=2000, hidden_layer_sizes=(
5, 5)).fit(X_train, train_target)
res = regr.predict_proba(X_test)
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_target, res)
acc_score = m.result().numpy()
print(acc_score)
accuracy_dict[new_target_name[0]+'_embed_nn_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': acc_score,
'time': calc_time
}
except ValueError:
accuracy_dict[new_target_name[0] + '_embed_reg_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': "NA",
'time': 0
}
accuracy_dict[new_target_name[0] + '_embed_nn_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': "NA",
'time': 0
}
print(pd.DataFrame(accuracy_dict))
for target in [(NEXT_TIMESTAMP, ()), (predictive_monitoring.EVENT_REMAINING_TIME, ())]:
include_last = True
if target == (NEXT_TIMESTAMP, ()):
include_last = False
F = [target,
(predictive_monitoring.EVENT_SYNCHRONIZATION_TIME, ())]
feature_storage = predictive_monitoring.apply(ocel, F, [])
# replace synchronization time with 1 as placeholder for empty feature
for g in feature_storage.feature_graphs:
for n in g.nodes:
n.attributes[('event_synchronization_time', ())] = 1
feature_storage.extract_normalized_train_test_split(0.3, state=3)
for g in feature_storage.feature_graphs:
for n in g.nodes:
n.attributes[('event_synchronization_time', ())] = 1
g_set_list_t = []
g_set_list_te = []
seq_set_list = []
seq_set_list_v = []
seq_set_list_t = []
for k in ks:
if True:
print("___________________________")
print("Prediction with Graph Structure and GNN")
print("___________________________")
layer_size = len(F)-1
# generate training & test datasets
train_idx, val_idx = train_test_split(
feature_storage.training_indices, test_size=0.2)
x_train, y_train = generate_graph_dataset(
feature_storage.feature_graphs, train_idx, ocel, k=k, target=target, include_last=include_last)
x_val, y_val = generate_graph_dataset(
feature_storage.feature_graphs, val_idx, ocel, k=k, target=target, include_last=include_last)
x_test, y_test = generate_graph_dataset(
feature_storage.feature_graphs, feature_storage.test_indices, ocel, k=k, target=target, include_last=include_last)
start_time = time.time()
baseline_MAE, train_MAE, val_MAE, test_MAE = GNN_prediction(
layer_size, x_train, y_train, x_val, y_val, x_test, y_test, batch_size=batch_size, lr=lr)
calc_time = time.time() - start_time
# record performance of GNN
accuracy_dict[target[0]+'graph_gnn_k_' + str(k)] = {
'baseline_MAE': baseline_MAE,
'train_MAE': train_MAE,
'val_MAE': val_MAE,
'test_MAE': test_MAE,
"time":calc_time
}
print(pd.DataFrame(accuracy_dict))
if True:
print("___________________________")
print("Prediction with Sequential Structure and GNN")
print("___________________________")
layer_size = len(F)-1
# generate training & test datasets
train_idx, val_idx = train_test_split(
feature_storage.training_indices, test_size=0.2)
x_train, y_train = generate_sequential_graph_dataset(
feature_storage.feature_graphs, train_idx, ocel, k=k, target=target, include_last=include_last)
x_val, y_val = generate_sequential_graph_dataset(
feature_storage.feature_graphs, val_idx, ocel, k=k, target=target, include_last=include_last)
x_test, y_test = generate_sequential_graph_dataset(
feature_storage.feature_graphs, feature_storage.test_indices, ocel, k=k, target=target, include_last=include_last)
start_time = time.time()
baseline_MAE, train_MAE, val_MAE, test_MAE = GNN_prediction(layer_size, x_train, y_train, x_val, y_val, x_test,
y_test, batch_size=batch_size, lr=lr)
calc_time = time.time() - start_time
# record performance of GNN
accuracy_dict[target[0]+'flat_gnn_k_' + str(k)] = {
'baseline_MAE': baseline_MAE,
'train_MAE': train_MAE,
'val_MAE': val_MAE,
'test_MAE': test_MAE,
"time": calc_time
}
print(pd.DataFrame(accuracy_dict))
if True:
print("___________________________")
print("Prediction with Graph Embedding")
print("___________________________")
train_nx_feature_graphs = []
test_nx_feature_graphs = []
train_target = []
test_target = []
print("Constructing Subgraphs ")
for i in tqdm(feature_storage.training_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=target,
from_start=False, include_last=include_last)
train_nx_feature_graphs += converted_subgraphs
train_target += extracted_targets
for i in tqdm(feature_storage.test_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=target,
from_start=False, include_last=include_last)
test_nx_feature_graphs += converted_subgraphs
test_target += extracted_targets
# IGE has problems with sparseness
for embedding_technique in [ 'Graph2Vec', 'NetLSD', 'WaveletCharacteristic',
'LDP', 'GL2Vec', 'SF', 'FGSD']:
try:
start_time = time.time()
X_train, X_test = embed(
train_nx_feature_graphs, test_nx_feature_graphs, embedding_technique, size=10*k)
calc_time = time.time() - start_time
print(X_train.shape)
print(X_test.shape)
model = LinearRegression()
model.fit(X_train, train_target)
res = model.predict(X_test)
print(mean_absolute_error(test_target, res))
accuracy_dict[target[0]+'embed_reg_' + embedding_technique+'_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=2000,early_stopping=True, hidden_layer_sizes=(
5, 5,)).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
accuracy_dict[target[0]+'embed_nn_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
except ValueError:
accuracy_dict[target[0] + 'embed_nn_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': "NA",
"time":0
}
accuracy_dict[target[0] + 'embed_reg_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': "NA",
"time":0
}
print(pd.DataFrame(accuracy_dict))
#pd.set_option('display.max_columns', None)
print(pd.DataFrame(accuracy_dict))
pd.DataFrame(accuracy_dict).to_csv("metrics.csv")
#############################
#Structural Delta Experiments
#############################
accuracy_dict = {}
if True:
for target in [(predictive_monitoring.EVENT_REMAINING_TIME, ()),(NEXT_TIMESTAMP, ())]:
include_last = True
if target == (NEXT_TIMESTAMP, ()):
include_last = False
F = [target] + [(predictive_monitoring.EVENT_TYPE_COUNT, (ot,)) for ot in ocel.object_types] #+ [(REL_ACTIVITY_OCCURRENCE_PER_TYPE, (ot,act)) for (ot,act) in itertools.product(ocel.object_types, activities)]
feature_storage = predictive_monitoring.apply(ocel, F, [], multi_output_event_features=[(REL_ACTIVITY_OCCURRENCE_PER_TYPE, (ocel.object_types,activities))])
feature_storage.extract_normalized_train_test_split(0.3, state=3)
g_set_list_t = []
g_set_list_te = []
seq_set_list = []
seq_set_list_v = []
seq_set_list_t = []
for k in ks:
if True:
print("___________________________")
print("Prediction with Graph Embedding")
print("___________________________")
train_nx_feature_graphs = []
test_nx_feature_graphs = []
train_target = []
test_target = []
print("Constructing Subgraphs ")
for i in tqdm(feature_storage.training_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=target,
from_start=False,
include_last=include_last)
train_nx_feature_graphs += converted_subgraphs
train_target += extracted_targets
for i in tqdm(feature_storage.test_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=target,
from_start=False,
include_last=include_last)
test_nx_feature_graphs += converted_subgraphs
test_target += extracted_targets
for embedding_technique in ['baseline','manual','delta_manual']:
X_train, X_test = embed(
train_nx_feature_graphs, test_nx_feature_graphs, embedding_technique, size=10 * k)
print(X_train.shape)
print(X_test.shape)
print(X_train)
model = LinearRegression()
model.fit(X_train, train_target)
res = model.predict(X_test)
print(mean_absolute_error(test_target, res))
accuracy_dict[target[0] + 'embed_reg_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
20, 10), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
# print(mean_squared_error(test_target,res))
accuracy_dict[target[0] + 'embed_nn_20_10_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
20,), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
# print(mean_squared_error(test_target,res))
accuracy_dict[target[0] + 'embed_nn_20_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
18,9),early_stopping=True, solver="lbfgs",batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
#print(mean_squared_error(test_target,res))
accuracy_dict[target[0] + 'embed_nn_18_9_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
18,), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
# print(mean_squared_error(test_target,res))
accuracy_dict[target[0] + 'embed_nn_18_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
16, 8), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
# print(mean_squared_error(test_target,res))
accuracy_dict[target[0] + 'embed_nn_16_8_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
16,), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
#print(mean_squared_error(test_target, res))
accuracy_dict[target[0] + 'embed_nn_16_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
14,7), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
#print(mean_squared_error(test_target, res))
accuracy_dict[target[0] + 'embed_nn_14_7_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
regr = MLPRegressor(random_state=3, max_iter=500, hidden_layer_sizes=(
14,), early_stopping=True, solver="lbfgs", batch_size=512).fit(X_train, train_target)
res = regr.predict(X_test)
print(mean_absolute_error(test_target, res))
#print(mean_squared_error(test_target, res))
accuracy_dict[target[0] + 'embed_nn_14_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_MAE': 0,
'train_MAE': 0,
'val_MAE': 0,
'test_MAE': mean_absolute_error(test_target, res)
}
print(pd.DataFrame(accuracy_dict))
for target in [[(NEXT_ACTIVITY, (act,)) for act in activities]]:
include_last = False
#CHANGE FEATURES
F = target + [(predictive_monitoring.EVENT_TYPE_COUNT, (ot,)) for ot in ocel.object_types] #+ [
#(REL_ACTIVITY_OCCURRENCE_PER_TYPE, (ot, act)) for (ot, act) in
#itertools.product(ocel.object_types, activities)]
feature_storage = predictive_monitoring.apply(ocel, F, [],multi_output_event_features=[(REL_ACTIVITY_OCCURRENCE_PER_TYPE, (ocel.object_types,activities))])
# replace synchronization time with 0 placeholder for empty feature
feature_storage.extract_normalized_train_test_split(0.3, state=3)
# replace categorical features with vector
new_target_name = (target[0][0], ())
feature_storage = cat_target_to_vector(
feature_storage, target, new_target_name)
for k in ks:
if True:
print("___________________________")
print("Prediction with Graph Embedding")
print("___________________________")
train_nx_feature_graphs = []
test_nx_feature_graphs = []
train_target = []
test_target = []
print("Constructing Subgraphs ")
for i in tqdm(feature_storage.training_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=new_target_name,
from_start=False,
include_last=include_last)
train_nx_feature_graphs += converted_subgraphs
train_target += extracted_targets
for i in tqdm(feature_storage.test_indices):
g = feature_storage.feature_graphs[i]
converted_subgraphs, extracted_targets = convert_to_nx_graphs(g, ocel, k,
target=new_target_name,
from_start=False,
include_last=include_last)
test_nx_feature_graphs += converted_subgraphs
test_target += extracted_targets
for embedding_technique in ['baseline','manual','delta_manual']:
X_train, X_test = embed(
train_nx_feature_graphs, test_nx_feature_graphs, embedding_technique, size=10 * k)
print(X_train.shape)
print(X_test.shape)
model = LogisticRegression(multi_class='multinomial')
model.fit(X_train, [ys.index(1) for ys in train_target])
res = model.predict(X_test)
acc_score = accuracy_score(
[ys.index(1) for ys in test_target], res)
print(acc_score)
accuracy_dict[new_target_name[0] + '_delta_reg_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': acc_score
}
regr = MLPClassifier(random_state=3, max_iter=500, hidden_layer_sizes=(
20, 10), early_stopping=True, batch_size=512).fit(X_train, train_target)
res = regr.predict_proba(X_test)
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_target, res)
acc_score = m.result().numpy()
print(acc_score)
accuracy_dict[
new_target_name[0] + '_delta_nn_20_10_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': acc_score
}
regr = MLPClassifier(random_state=3, max_iter=500, hidden_layer_sizes=(
20, ), early_stopping=True, batch_size=512).fit(X_train, train_target)
res = regr.predict_proba(X_test)
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_target, res)
acc_score = m.result().numpy()
print(acc_score)
accuracy_dict[
new_target_name[0] + '_delta_nn_20_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': acc_score
}
regr = MLPClassifier(random_state=3, max_iter=500, hidden_layer_sizes=(
18,9),early_stopping=True,batch_size=512).fit(X_train, train_target)
res = regr.predict_proba(X_test)
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_target, res)
acc_score = m.result().numpy()
print(acc_score)
accuracy_dict[new_target_name[0] + '_delta_nn_18_9_FGSD_' + embedding_technique + '_k_' + str(k)] = {
'baseline_ACC': 0,
'train_ACC': 0,
'val_ACC': 0,
'test_ACC': acc_score
}
regr = MLPClassifier(random_state=3, max_iter=500, hidden_layer_sizes=(
18,), early_stopping=True, batch_size=512).fit(X_train, train_target)
res = regr.predict_proba(X_test)
m = tf.keras.metrics.CategoricalAccuracy()
m.update_state(test_target, res)