-
Notifications
You must be signed in to change notification settings - Fork 0
/
classification.py
1180 lines (1104 loc) · 45.9 KB
/
classification.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 argparse
import copy
import pickle
import random
from typing import Optional
import networkx as nx
import numpy as np
import pandas as pd
import torch
import torch.nn.functional as F # noqa
from torch.nn import Embedding, init
from torch_geometric.nn import GAE # noqa Graph Autoencoder
from torch_geometric.nn import GCNConv # noqa
from torch_geometric.nn import Node2Vec # noqa
from torch_geometric.nn import SAGEConv # noqa
from torch_geometric.utils import to_networkx
from dataset.load_datasets import load_dataset
from models.GAE import train_gae
from models.GCN import GCNEmb, GCNTask
from models.GRAPH_SAGE import GraphSAGEEmb, GraphSAGETask
from models.ML import GraphMLTrain
from utils import (
convert_networkx_to_torch_graph_with_centrality_features,
evaluate_model,
plot_metrics,
)
from utils.constants import (
DataSetEnum,
DataSetModel,
GAEEncoderEnum,
GAEFeatureEnum,
MLDefaultSettings,
ModelsEnum,
NNTypeEnum,
Node2VecParamModeEnum,
)
from utils.split_data import split_data
from utils.constants import DATA_DIR, REPORT_DIR
from utils.logger import get_logger
from utils.plt_tsne import plot_tsne
from utils.timer import timer
from utils.to_json_file import to_json_file
# set seed
seed = 42
random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
logger = get_logger()
def process(arguments: argparse.Namespace):
# initialize
data_dir, report_dir, device, ml_default_settings = init_setup(arguments)
# load dataset and preprocess
(
dataset,
dataset_with_centrality,
label_list,
label_dict,
) = load_and_preprocess_data(data_dir, arguments.dataset, arguments)
if arguments.model == ModelsEnum.feature_centrality.value:
metrics = handle_feature_centrality_model(
arguments,
ml_default_settings=ml_default_settings,
dataset_with_centrality=dataset_with_centrality,
report_dir=report_dir,
label_list=label_list,
)
elif arguments.model == ModelsEnum.feature_1433.value:
metrics = handle_feature_1433_model(
arguments,
ml_default_settings=ml_default_settings,
dataset=dataset,
report_dir=report_dir,
label_list=label_list,
)
elif arguments.model == ModelsEnum.random_input.value:
metrics = handle_random_input_model(
arguments,
ml_default_settings=ml_default_settings,
dataset=dataset,
report_dir=report_dir,
label_list=label_list,
)
elif arguments.model == ModelsEnum.graph_sage.value:
metrics = handle_graph_sage_model(
arguments,
ml_default_settings=ml_default_settings,
dataset=dataset,
dataset_with_centrality=dataset_with_centrality,
report_dir=report_dir,
label_list=label_list,
label_dict=label_dict,
device=device,
)
elif arguments.model == ModelsEnum.gcn.value:
metrics = handle_gcn_model(
arguments,
ml_default_settings=ml_default_settings,
dataset=dataset,
dataset_with_centrality=dataset_with_centrality,
report_dir=report_dir,
label_list=label_list,
label_dict=label_dict,
device=device,
)
elif arguments.model == ModelsEnum.node2vec.value:
metrics = handle_node2vec_model(
arguments,
ml_default_settings=ml_default_settings,
dataset=dataset,
report_dir=report_dir,
label_list=label_list,
label_dict=label_dict,
device=device,
)
elif arguments.model == ModelsEnum.gae.value:
metrics = handle_gae_model(
arguments,
ml_default_settings=ml_default_settings,
dataset=dataset,
dataset_with_centrality=dataset_with_centrality,
report_dir=report_dir,
label_list=label_list,
label_dict=label_dict,
device=device,
)
else:
raise ValueError(f"Unknown model: {arguments.model}")
return metrics
def init_setup(arguments: argparse.Namespace):
DataSetModel(
dataset=arguments.dataset,
)
data_dir = DATA_DIR / arguments.dataset
report_dir = REPORT_DIR / arguments.dataset
if not data_dir.exists():
data_dir.mkdir(parents=True)
if not report_dir.exists():
report_dir.mkdir(parents=True)
# if it is travel, then report should be added: / dataset.name
if arguments.dataset.lower() == DataSetEnum.Travel.value.lower():
report_dir = report_dir / arguments.travel_dataset
if not report_dir.exists():
report_dir.mkdir(parents=True)
device = torch.device(
"cuda" if (torch.cuda.is_available() and arguments.device == "cuda") else "cpu"
)
logger.info(f"Device: {device}")
# params
ml_default_settings = MLDefaultSettings()
return data_dir, report_dir, device, ml_default_settings
def load_and_preprocess_data(data_dir, dataset_name, arguments): # noqa
if dataset_name.lower() == DataSetEnum.AttributedGraphDataset_PPI.value.lower():
dataset = load_dataset(dataset_name)
# TODO: this is a multi-class task
dataset.data.labels = {i: str(i) for i in enumerate(dataset.data.y.tolist())}
else:
dataset = load_dataset(dataset_name)
if (
arguments.dataset.lower()
== DataSetEnum.AttributedGraphDataset_Flickr.value.lower()
):
dataset.data.x = dataset.data.x.to_dense()
# for the dataset with test/validation/train split
if dataset_name.lower() in [
DataSetEnum.KarateClub.value.lower(),
DataSetEnum.AMAZON_COMPUTERS.value.lower(),
DataSetEnum.AMAZON_PHOTO.value.lower(),
DataSetEnum.TWITCH_DE.value.lower(),
DataSetEnum.TWITCH_EN.value.lower(),
DataSetEnum.TWITCH_ES.value.lower(),
DataSetEnum.TWITCH_FR.value.lower(),
DataSetEnum.TWITCH_PT.value.lower(),
DataSetEnum.TWITCH_RU.value.lower(),
DataSetEnum.GitHub.value.lower(),
DataSetEnum.Coauthor_CS.value.lower(),
DataSetEnum.Coauthor_Physics.value.lower(),
DataSetEnum.CitationsFull_Cora.value.lower(),
DataSetEnum.CitationsFull_CiteSeer.value.lower(),
DataSetEnum.CitationsFull_PubMed.value.lower(),
DataSetEnum.CitationsFull_Cora_ML.value.lower(),
DataSetEnum.CitationsFull_DBLP.value.lower(),
DataSetEnum.Cora_Full.value.lower(),
DataSetEnum.WEBKB_Cornell.value.lower(),
DataSetEnum.WEBKB_Texas.value.lower(),
DataSetEnum.WEBKB_Wisconsin.value.lower(),
DataSetEnum.PolBlogs.value.lower(),
DataSetEnum.EllipticBitcoinDataset.value.lower(),
DataSetEnum.AttributedGraphDataset_Cora.value.lower(),
DataSetEnum.TWITCH_FR.value.lower(),
DataSetEnum.AttributedGraphDataset_CiteSeer.value.lower(),
DataSetEnum.AttributedGraphDataset_Pubmed.value.lower(),
DataSetEnum.AttributedGraphDataset_BlogCatalog.value.lower(),
DataSetEnum.Actor.value.lower(),
DataSetEnum.AttributedGraphDataset_PPI.value.lower(),
DataSetEnum.AttributedGraphDataset_Wiki.value.lower(),
DataSetEnum.AttributedGraphDataset_Flickr.value.lower(),
DataSetEnum.HeterophilousGraphDataset_Amazon_ratings.value.lower(),
DataSetEnum.HeterophilousGraphDataset_Questions.value.lower(),
DataSetEnum.HeterophilousGraphDataset_Tolokers.value.lower(),
DataSetEnum.HeterophilousGraphDataset_Roman_empire.value.lower(),
DataSetEnum.HeterophilousGraphDataset_Minesweeper.value.lower(),
]:
dataset = split_data(dataset)
dataset.name = dataset_name
label_dict = dataset.data.labels
label_list = [value for key, value in label_dict.items()]
logger.info(f"Label list: {label_list}")
dataset_graph = to_networkx(
dataset.data,
to_undirected=True,
node_attrs=["y", "train_mask", "val_mask", "test_mask"],
)
# preprocess the graph to generate a data with centrality features
with timer(
logger, "Preprocess the graph to generate a data with centrality features"
):
graph_metrics_dir = data_dir / dataset.name / "graph_metrics"
if not graph_metrics_dir.exists():
graph_metrics_dir.mkdir(parents=True, exist_ok=True)
with timer(logger, "Degree centrality"):
if not (graph_metrics_dir / "degree.pickle").exists():
degree = nx.degree_centrality(dataset_graph)
# Normalize the degree centrality values
max_degree = max(degree.values())
min_degree = min(degree.values())
for node, value in degree.items():
degree[node] = (value - min_degree) / (max_degree - min_degree)
with open(graph_metrics_dir / "degree.pickle", "wb") as handle:
pickle.dump(degree, handle, protocol=pickle.HIGHEST_PROTOCOL)
else:
with open(graph_metrics_dir / "degree.pickle", "rb") as handle:
degree = pickle.load(handle)
with timer(logger, "Betweenness centrality"):
if not (graph_metrics_dir / "betweenness.pickle").exists():
betweenness = nx.betweenness_centrality(dataset_graph, k=5)
# Normalize the betweenness centrality values
max_betweenness = max(betweenness.values())
min_betweenness = min(betweenness.values())
for node, value in betweenness.items():
if max_betweenness == min_betweenness:
betweenness[node] = 0
else:
betweenness[node] = (value - min_betweenness) / (
max_betweenness - min_betweenness
)
with open(graph_metrics_dir / "betweenness.pickle", "wb") as handle:
pickle.dump(betweenness, handle, protocol=pickle.HIGHEST_PROTOCOL)
else:
with open(graph_metrics_dir / "betweenness.pickle", "rb") as handle:
betweenness = pickle.load(handle)
data_with_centrality = convert_networkx_to_torch_graph_with_centrality_features(
nx_graph=dataset_graph,
degree_df=degree,
betweenness_df=betweenness,
y_field="y",
)
dataset_with_centrality = copy.deepcopy(dataset)
dataset_with_centrality.data = data_with_centrality
return dataset, dataset_with_centrality, label_list, label_dict
def handle_feature_centrality_model(
arguments,
ml_default_settings,
dataset_with_centrality,
report_dir,
label_list,
):
logger.info("Feature centrality model")
feature_centrality_df = pd.DataFrame(dataset_with_centrality.data.x.numpy())
feature_centrality_df["y"] = dataset_with_centrality.data.y.numpy()
feature_centrality_model = GraphMLTrain(
feature_centrality_df,
y_field_name="y",
svm_best_param=ml_default_settings.pretrain_svm_best_param,
knn_best_param=ml_default_settings.pretrain_knn_best_param,
rf_best_param=ml_default_settings.pretrain_rf_best_param,
oversampling=arguments.oversampling,
plot_it=arguments.plot_it,
risk_labels=label_list,
)
feature_centrality_ml_models = feature_centrality_model.train(
grid_search=arguments.grid_search
)
feature_centrality_model_metrics = feature_centrality_model.plt_3_confusion_matrix(
feature_centrality_ml_models,
f"{arguments.model.upper()} Confusion Matrix",
report_dir / f"{arguments.model}.png",
plot_it=arguments.plot_it,
balanced_ac=arguments.balanced_ac,
)
logger.critical(feature_centrality_model_metrics)
to_json_file(
feature_centrality_model_metrics,
report_dir / f"{arguments.model}_metrics.json",
)
return feature_centrality_model_metrics
def handle_feature_1433_model(
arguments, ml_default_settings, dataset, report_dir, label_list
):
logger.info("Feature 1433 model")
try:
feature_1433_df = pd.DataFrame(dataset.data.x.numpy())
except Exception as e:
logger.warning(e)
feature_1433_df = pd.DataFrame(dataset.data.x.to_dense().numpy())
feature_1433_df["y"] = dataset.data.y.numpy()
feature_1433_model = GraphMLTrain(
feature_1433_df,
y_field_name="y",
svm_best_param=ml_default_settings.pretrain_svm_best_param,
knn_best_param=ml_default_settings.pretrain_knn_best_param,
rf_best_param=ml_default_settings.pretrain_rf_best_param,
oversampling=arguments.oversampling,
plot_it=arguments.plot_it,
risk_labels=label_list,
)
feature_1433_ml_models = feature_1433_model.train(grid_search=arguments.grid_search)
feature_1433_model_metrics = feature_1433_model.plt_3_confusion_matrix(
feature_1433_ml_models,
f"{arguments.model.upper()} Confusion Matrix",
report_dir / f"{arguments.model}.png",
plot_it=arguments.plot_it,
balanced_ac=arguments.balanced_ac,
)
logger.critical(feature_1433_model_metrics)
to_json_file(
feature_1433_model_metrics, report_dir / f"{arguments.model}_metrics.json"
)
return feature_1433_model_metrics
def handle_random_input_model(
arguments, ml_default_settings, dataset, report_dir, label_list
):
logger.info("Random input model")
if arguments.start_dim > arguments.end_dim:
raise ValueError(
"Start dimensionality cannot be greater than end dimensionality"
)
random_input_model_performances = {}
for random_dim in range(arguments.start_dim, arguments.end_dim + 1):
random_embeddings = Embedding(dataset.data.y.shape[0], random_dim)
# Initialize the embedding with random values
init.xavier_uniform_(random_embeddings.weight.data)
dataset.data.x = torch.tensor(random_embeddings.weight.data)
x_df = pd.DataFrame(
dataset.data.x.detach().cpu().numpy(), columns=list(range(random_dim))
)
x_df["y"] = dataset.data.y.detach().cpu().numpy()
random_model = GraphMLTrain(
x_df,
y_field_name="y",
svm_best_param=ml_default_settings.pretrain_svm_best_param,
knn_best_param=ml_default_settings.pretrain_knn_best_param,
rf_best_param=ml_default_settings.pretrain_rf_best_param,
oversampling=arguments.oversampling,
plot_it=arguments.plot_it,
risk_labels=label_list,
)
random_train_models = random_model.train(grid_search=arguments.grid_search)
random_model_metrics = random_model.plt_3_confusion_matrix(
random_train_models,
f"{arguments.model.upper()} Confusion Matrix",
plot_it=arguments.plot_it,
balanced_ac=arguments.balanced_ac,
)
random_input_model_performances[random_dim] = random_model_metrics
for metric_name in [
"accuracy_score",
"macro_precision",
"macro_recall",
"macro_f_beta_score",
"micro_precision",
"micro_recall",
"micro_f_beta_score",
"roc_auc",
]:
plot_metrics(
metrics=random_input_model_performances,
title="Random Input Model Performance vs Dimensionality",
x_title="Dimensionality",
y_title=metric_name.upper(),
metric_name=metric_name,
filename=report_dir
/ arguments.model
/ f"{arguments.model}-dim-{metric_name}.png",
)
to_json_file(
random_input_model_performances,
report_dir / arguments.model / f"{arguments.model}_metrics.json",
)
return random_input_model_performances
def handle_graph_sage_model(
arguments,
ml_default_settings,
dataset,
dataset_with_centrality,
report_dir,
label_list,
label_dict,
device,
):
"""
We will have three different models for GraphSAGE:
- supervised learning: centrality as features
- supervised learning: 1433 features
- unsupervised learning: reconstruct the graph as loss function
"""
logger.info("GraphSAGE model")
# supervised learning: centrality as features
graph_sage_hidden_dim = [
int(dim) for dim in arguments.graph_sage_hidden_dim.split(",")
]
if arguments.graph_sage_type == NNTypeEnum.supervised_centrality.value:
logger.info("GraphSAGE Classification with betweenness and degree")
graph_sage_with_centrality_model = GraphSAGETask(
dataset_with_centrality.num_node_features,
graph_sage_hidden_dim,
dataset_with_centrality.num_classes,
aggr=arguments.graph_sage_aggr,
).to(device)
dataset_with_centrality.data.to(device)
graph_sage_with_centrality_model.fit(
dataset_with_centrality.data, arguments.epochs
)
graph_sage_with_centrality_metrics = evaluate_model(
graph_sage_with_centrality_model,
dataset_with_centrality,
title="GraphSAGE Classification with betweenness and degree",
label_dict=label_dict,
plot_it=arguments.plot_it,
filename=report_dir / arguments.model / f"{arguments.model}-centrality.png",
)
to_json_file(
graph_sage_with_centrality_metrics,
report_dir / arguments.model / f"{arguments.model}-centrality-metrics.json",
)
return graph_sage_with_centrality_metrics
# supervised learning: 1433 features
if arguments.graph_sage_type == NNTypeEnum.supervised_feature.value:
logger.info("GraphSAGE Classification with 1433 features")
graph_sage_with_feature_model = GraphSAGETask(
dataset.num_node_features,
graph_sage_hidden_dim,
dataset.num_classes,
aggr=arguments.graph_sage_aggr,
).to(device)
dataset.data.to(device)
graph_sage_with_feature_model.fit(dataset.data, arguments.epochs)
graph_sage_with_feature_metrics = evaluate_model(
graph_sage_with_feature_model,
dataset,
title="GraphSAGE Classification with 1433 features",
label_dict=label_dict,
plot_it=arguments.plot_it,
filename=report_dir / arguments.model / f"{arguments.model}-feature.png",
)
to_json_file(
graph_sage_with_feature_metrics,
report_dir / arguments.model / f"{arguments.model}-feature-metrics.json",
)
return graph_sage_with_feature_metrics
# unsupervised learning: reconstruct the graph as loss function
if arguments.graph_sage_type == NNTypeEnum.unsupervised.value:
"""
Adjustable parameters:
- dataset
- dim: start_dim, end_dim
- hidden_dim and layers
"""
logger.info(
f"GraphSAGE Unsupervised Learning with hidden_layers: {graph_sage_hidden_dim}"
)
# determine which dataset to use
if arguments.graph_sage_dataset_type == GAEFeatureEnum.feature_1433.value:
logger.info("Using 1433 features")
graph_sage_dataset = dataset
elif arguments.graph_sage_dataset_type == GAEFeatureEnum.centrality.value:
logger.info("Using centrality features")
graph_sage_dataset = dataset_with_centrality
else:
raise ValueError(
f"Invalid graph_sage_dataset_type: {arguments.graph_sage_dataset_type}"
)
graph_sage_unsupervised_performance = {}
for emb_dim in range(arguments.start_dim, arguments.end_dim + 1):
graph_sage_emb_params = dict(
in_channels=graph_sage_dataset.num_node_features,
hidden_channels=graph_sage_hidden_dim,
out_channels=emb_dim,
aggr=arguments.graph_sage_aggr,
)
graph_sage_emb_model = GraphSAGEEmb(**graph_sage_emb_params)
logger.info(graph_sage_emb_params)
graph_sage_dataset.data.to(device)
graph_sage_emb_model.to(device)
graph_sage_emb_df = graph_sage_emb_model.fit(
graph_sage_dataset.data, arguments.epochs
)
plot_tsne(
graph_sage_emb_df,
title=f"GraphSAGE Unsupervised Learning with {emb_dim} dimensions",
filename=report_dir
/ arguments.model
/ arguments.graph_sage_dataset_type
/ str(len(graph_sage_hidden_dim))
/ f"{arguments.model}-dim-{emb_dim}.png",
)
graph_sage_emb_model = GraphMLTrain(
graph_sage_emb_df,
y_field_name="y",
svm_best_param=ml_default_settings.pretrain_svm_best_param,
knn_best_param=ml_default_settings.pretrain_knn_best_param,
rf_best_param=ml_default_settings.pretrain_rf_best_param,
oversampling=arguments.oversampling,
plot_it=arguments.plot_it,
risk_labels=label_list,
)
graph_sage_emb_train_models = graph_sage_emb_model.train(
grid_search=arguments.grid_search
)
graph_sage_emb_model_metrics = graph_sage_emb_model.plt_3_confusion_matrix(
graph_sage_emb_train_models,
f"{arguments.model.upper()} Confusion Matrix",
plot_it=arguments.plot_it,
balanced_ac=arguments.balanced_ac,
)
graph_sage_unsupervised_performance[emb_dim] = graph_sage_emb_model_metrics
graph_title = f"GraphSAGE Model: {arguments.graph_sage_dataset_type.upper()}/Hidden:{len(graph_sage_hidden_dim)} Performance vs Dimensionality" # noqa
for metric_name in [
"accuracy_score",
"macro_precision",
"macro_recall",
"macro_f_beta_score",
"micro_precision",
"micro_recall",
"micro_f_beta_score",
"roc_auc",
]:
plot_metrics(
metrics=graph_sage_unsupervised_performance,
title=graph_title,
x_title="Dimensionality",
y_title=metric_name.upper(),
metric_name=metric_name,
filename=report_dir
/ arguments.model
/ arguments.graph_sage_dataset_type
/ str(len(graph_sage_hidden_dim))
/ f"{arguments.model}-dim-{metric_name}.png",
)
to_json_file(
graph_sage_unsupervised_performance,
report_dir
/ arguments.model
/ arguments.graph_sage_dataset_type
/ str(len(graph_sage_hidden_dim))
/ f"{arguments.model}_metrics.json",
)
return graph_sage_unsupervised_performance
def handle_gcn_model(
arguments: argparse.Namespace,
ml_default_settings,
dataset,
dataset_with_centrality,
report_dir,
label_list,
label_dict,
device,
):
"""
GCN Classification
- supervised learning: centrality as features
- supervised learning: 1433 features
- unsupervised learning: reconstruct the graph as loss function
"""
logger.info(f"GCN Model: {arguments.gcn_type}")
gcn_hidden_dim = [int(x) for x in arguments.gcn_hidden_dim.split(",")]
if arguments.gcn_type == NNTypeEnum.supervised_centrality.value:
logger.info("GCN Classification with centrality as features")
gcn_centrality_model = GCNTask(
dataset_with_centrality.num_node_features,
gcn_hidden_dim,
dataset_with_centrality.num_classes,
).to(device)
dataset_with_centrality.data.to(device)
gcn_centrality_model.fit(dataset_with_centrality.data, arguments.epochs)
gcn_centrality_metrics = evaluate_model(
gcn_centrality_model,
dataset_with_centrality,
title="GCN Classification",
label_dict=label_dict,
plot_it=arguments.plot_it,
filename=report_dir / arguments.model / f"{arguments.model}-centrality.png",
)
to_json_file(
gcn_centrality_metrics,
report_dir / arguments.model / f"{arguments.model}-centrality-metrics.json",
)
return gcn_centrality_metrics
if arguments.gcn_type == NNTypeEnum.supervised_feature.value:
logger.info("GCN Classification with 1433 features")
gcn_feature_model = GCNTask(
dataset.num_node_features, gcn_hidden_dim, dataset.num_classes
).to(device)
dataset.data.to(device)
gcn_feature_model.fit(dataset.data, arguments.epochs)
gcn_feature_metrics = evaluate_model(
gcn_feature_model,
dataset,
title="GCN Classification",
label_dict=label_dict,
plot_it=arguments.plot_it,
filename=report_dir / arguments.model / f"{arguments.model}-feature.png",
)
to_json_file(
gcn_feature_metrics,
report_dir / arguments.model / f"{arguments.model}-feature-metrics.json",
)
return gcn_feature_metrics
if arguments.gcn_type == NNTypeEnum.unsupervised.value:
"""
Same here as GraphSAGE
adjustable parameters:
- dataset
- hidden_dim and layers
- dim: dimensionality of the embedding
"""
logger.info("GCN Unsupervised Learning")
if arguments.gcn_dataset_type == GAEFeatureEnum.feature_1433.value:
logger.info("GCN Unsupervised Learning with 1433 features")
gcn_dataset = dataset
elif arguments.gcn_dataset_type == GAEFeatureEnum.centrality.value:
logger.info("GCN Unsupervised Learning with centrality as features")
gcn_dataset = dataset_with_centrality
else:
raise ValueError("Invalid GCN Dataset Type")
gcn_unsupervised_performance = {}
for emb_dim in range(arguments.start_dim, arguments.end_dim + 1):
gcn_emb_model = GCNEmb(
gcn_dataset.num_node_features, gcn_hidden_dim, emb_dim
)
gcn_dataset.data.to(device)
gcn_emb_model.to(device)
gcn_emb_df = gcn_emb_model.fit(gcn_dataset.data, arguments.epochs)
# plot tsne
plot_tsne(
gcn_emb_df,
title=f"GCN Unsupervised Learning with {emb_dim} dimensions",
filename=report_dir
/ arguments.model
/ arguments.gcn_dataset_type
/ str(len(gcn_hidden_dim))
/ f"{arguments.model}-dim-{emb_dim}.png",
)
gcn_emb_model = GraphMLTrain(
gcn_emb_df,
y_field_name="y",
svm_best_param=ml_default_settings.pretrain_svm_best_param,
knn_best_param=ml_default_settings.pretrain_knn_best_param,
rf_best_param=ml_default_settings.pretrain_rf_best_param,
oversampling=arguments.oversampling,
plot_it=arguments.plot_it,
risk_labels=label_list,
)
gcn_emb_train_models = gcn_emb_model.train(
grid_search=arguments.grid_search
)
gcn_emb_model_metrics = gcn_emb_model.plt_3_confusion_matrix(
gcn_emb_train_models,
f"{arguments.model.upper()} Confusion Matrix",
plot_it=arguments.plot_it,
balanced_ac=arguments.balanced_ac,
)
gcn_unsupervised_performance[emb_dim] = gcn_emb_model_metrics
graph_title = f"GCN Model: {arguments.gcn_dataset_type.upper()}/Hidden:{len(gcn_hidden_dim)} Performance vs Dimensionality" # noqa
for metric_name in [
"accuracy_score",
"macro_precision",
"macro_recall",
"macro_f_beta_score",
"micro_precision",
"micro_recall",
"micro_f_beta_score",
"roc_auc",
]:
plot_metrics(
metrics=gcn_unsupervised_performance,
title=graph_title,
x_title="Dimensionality",
y_title=metric_name.upper(),
metric_name=metric_name,
filename=report_dir
/ arguments.model
/ arguments.gcn_dataset_type
/ str(len(gcn_hidden_dim))
/ f"{arguments.model}-dim-{metric_name}.png",
)
to_json_file(
gcn_unsupervised_performance,
report_dir
/ arguments.model
/ arguments.gcn_dataset_type
/ str(len(gcn_hidden_dim))
/ f"{arguments.model}-dim-metrics.json",
)
return gcn_unsupervised_performance
def handle_node2vec_model(
arguments: argparse.Namespace,
ml_default_settings,
dataset,
report_dir,
label_list,
label_dict: dict,
device: torch.device = torch.device("cpu"),
):
# DISCUSS: why is this one so good?
"""
Node2vec
For some reason, this one performs really before, and now is very good now.
It does not make sense to me, as this one is not include the 1433 features.
My understanding is that, the graph already have the structure to make this 7 classifications into
different clusters, so the random walk will gather this group information, and then transform that
into the embedding space
"""
if arguments.start_dim > arguments.end_dim:
raise ValueError("Start dimensionality must be less than end dimensionality")
node2vec_unsupervised_performance = {}
node2vec_params = []
param_mapping = {
Node2VecParamModeEnum.dim.value: (
"embedding_dim",
range(arguments.start_dim, arguments.end_dim + 1),
),
Node2VecParamModeEnum.walk_length.value: (
"walk_length",
range(2, arguments.node2vec_walk_length + 1),
),
Node2VecParamModeEnum.walk_per_node.value: (
"walks_per_node",
range(1, arguments.node2vec_walks_per_node + 1),
),
Node2VecParamModeEnum.num_negative_samples.value: (
"num_negative_samples",
range(1, arguments.node2vec_num_negative_samples + 1, 30),
),
Node2VecParamModeEnum.p.value: (
"p",
np.array(
range(1, int((arguments.node2vec_p + 1) / arguments.node2vec_pq_step))
)
* arguments.node2vec_pq_step,
),
Node2VecParamModeEnum.q.value: (
"q",
np.array(
range(1, int((arguments.node2vec_q + 1) / arguments.node2vec_pq_step))
)
* arguments.node2vec_pq_step,
),
}
if arguments.node2vec_params_mode not in param_mapping:
raise ValueError(
f"Invalid node2vec params mode: {arguments.node2vec_params_mode}"
)
node2vec_performance_key, param_range = param_mapping[
arguments.node2vec_params_mode
]
raw_params = dict(
edge_index=dataset.data.edge_index,
embedding_dim=arguments.start_dim,
walk_length=arguments.node2vec_walk_length,
context_size=arguments.node2vec_context_size,
num_negative_samples=arguments.node2vec_num_negative_samples,
p=arguments.node2vec_p,
q=arguments.node2vec_q,
)
for param_value in param_range:
generated_params = {
**raw_params,
node2vec_performance_key: param_value,
}
if arguments.node2vec_params_mode == Node2VecParamModeEnum.walk_length.value:
generated_params["context_size"] = param_value
node2vec_params.append(generated_params)
for params in node2vec_params:
logger.info(params)
node2vec_model = Node2Vec(
**params,
)
performance_key_value = params[node2vec_performance_key]
node2vec_model.reset_parameters()
node2vec_model.to(device)
node2vec_optimizer = torch.optim.Adam(
list(node2vec_model.parameters()), lr=0.01
)
node2vec_loader = node2vec_model.loader(
batch_size=128, shuffle=True, num_workers=4
)
# training the node2vec
for epoch in range(arguments.epochs + 1):
node2vec_model.train()
total_loss = 0
for pos_rw, neg_rw in node2vec_loader:
node2vec_optimizer.zero_grad()
loss = node2vec_model.loss(pos_rw.to(device), neg_rw.to(device))
loss.backward()
node2vec_optimizer.step()
total_loss += loss.item()
with torch.no_grad():
node2vec_model.eval()
z = node2vec_model()
# logger.info(z.shape)
# logger.info(dataset.data.train_mask.shape)
# the test is multiclass classification following ML tasks
# but this does not affect the loss function and the training
# so actually the logistic regression is already with good performance
test_acc = node2vec_model.test(
z[dataset.data.train_mask],
dataset.data.y[dataset.data.train_mask],
z[dataset.data.test_mask],
dataset.data.y[dataset.data.test_mask],
)
if epoch % 10 == 0:
logger.info(
f"Epoch: {epoch:03d}, Loss: {total_loss:.4f}, Test: {test_acc:.4f}"
)
node2vec_embeddings = node2vec_model.embedding.weight.cpu().detach().numpy()
node2vec_embeddings_df = pd.DataFrame(node2vec_embeddings)
node2vec_embeddings_df["y"] = dataset.data.y.cpu().detach().numpy()
plot_tsne(
emb_df=node2vec_embeddings_df,
title=f"{arguments.model.upper()}/{node2vec_performance_key.upper()}/{performance_key_value}",
filename=report_dir
/ arguments.model
/ node2vec_performance_key
/ f"{arguments.model}-{node2vec_performance_key}-{performance_key_value}.png",
label_int_2_str=label_dict,
)
# train classification
node2vec_ml_model = GraphMLTrain(
node2vec_embeddings_df,
y_field_name="y",
svm_best_param=ml_default_settings.pretrain_svm_best_param,
knn_best_param=ml_default_settings.pretrain_knn_best_param,
rf_best_param=ml_default_settings.pretrain_rf_best_param,
oversampling=arguments.oversampling,
plot_it=arguments.plot_it,
risk_labels=label_list,
)
node2vec_ml_models = node2vec_ml_model.train(grid_search=arguments.grid_search)
node2vec_ml_model_metrics = node2vec_ml_model.plt_3_confusion_matrix(
node2vec_ml_models,
f"{arguments.model.upper()} Confusion Matrix",
plot_it=arguments.plot_it,
balanced_ac=arguments.balanced_ac,
)
node2vec_unsupervised_performance[
performance_key_value
] = node2vec_ml_model_metrics
for metric_name in [
"accuracy_score",
"macro_precision",
"macro_recall",
"macro_f_beta_score",
"micro_precision",
"micro_recall",
"micro_f_beta_score",
"roc_auc",
]:
plot_metrics(
metrics=node2vec_unsupervised_performance,
title=f"Node2vec Embedding Model Performance vs {node2vec_performance_key.upper()}",
x_title=node2vec_performance_key.upper(),
y_title=metric_name.upper(),
metric_name=metric_name,
filename=report_dir
/ arguments.model
/ node2vec_performance_key
/ f"{arguments.model}-{node2vec_performance_key}-{metric_name}.png",
)
to_json_file(
node2vec_unsupervised_performance,
report_dir
/ arguments.model
/ node2vec_performance_key
/ f"{arguments.model}-{node2vec_performance_key}-metrics.json",
)
return node2vec_unsupervised_performance
def handle_gae_model(
arguments: argparse.Namespace,
ml_default_settings,
dataset,
dataset_with_centrality,
report_dir,
label_list,
label_dict: Optional[dict] = None,
device: torch.device = torch.device("cpu"),
):
logger.info("GAE Training")
if arguments.start_dim > arguments.end_dim:
raise ValueError("Start dimensionality must be less than end dimensionality")
if arguments.gae_encoder == GAEEncoderEnum.gcn.value:
gcn_hidden_channels = [int(dim) for dim in arguments.gcn_hidden_dim.split(",")]
gae_gcn_unsupervised_performance = {}
logger.info("GAE Encoder: GCN")
for emb_dim in range(arguments.start_dim, arguments.end_dim + 1):
if arguments.gae_feature == GAEFeatureEnum.centrality.value:
input_dataset = dataset_with_centrality
elif arguments.gae_feature == GAEFeatureEnum.feature_1433.value:
input_dataset = dataset
else:
raise ValueError("Invalid GAE Feature")
gae_gcn_model = GCNEmb(
in_channels=input_dataset.data.num_features,
hidden_layer_dim=gcn_hidden_channels,
out_channels=emb_dim,
)
gae_gcn_model.to(device)
logger.info(device)
input_dataset.data.to(device)
gae_gcn_embeddings = train_gae(
data=input_dataset.data,
encoder=gae_gcn_model,
device=device,
epochs=arguments.epochs,
)
tsne_title = f"TSNE of {arguments.model.upper()}-{arguments.gae_encoder.upper()}-{arguments.gae_feature.upper()}-{emb_dim}" # noqa