forked from wassimj/topologicpy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDGL.py
2688 lines (2373 loc) · 113 KB
/
DGL.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 topologicpy
import topologic
from topologicpy.Dictionary import Dictionary
import os
import random
import time
from datetime import datetime
import copy
import sys
import subprocess
try:
import numpy as np
except:
call = [sys.executable, '-m', 'pip', 'install', 'numpy', '-t', sys.path[0]]
subprocess.run(call)
try:
import numpy as np
except:
print("DGL - Error: Could not import numpy.")
try:
import pandas as pd
except:
call = [sys.executable, '-m', 'pip', 'install', 'pandas', '-t', sys.path[0]]
subprocess.run(call)
try:
import pandas as pd
except:
print("DGL - Error: Could not import pandas")
try:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import DataLoader, ConcatDataset
except:
call = [sys.executable, '-m', 'pip', 'install', 'torch', '-t', sys.path[0]]
subprocess.run(call)
try:
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data import DataLoader, ConcatDataset
except:
print("DGL - Error: Could not import torch")
try:
import dgl
from dgl.data import DGLDataset
from dgl.dataloading import GraphDataLoader
from dgl.nn import GINConv, GraphConv, SAGEConv, TAGConv
from dgl import save_graphs, load_graphs
except:
call = [sys.executable, '-m', 'pip', 'install', 'dgl', 'dglgo', '-f', 'https://data.dgl.ai/wheels/repo.html', '--upgrade', '-t', sys.path[0]]
subprocess.run(call)
try:
import dgl
from dgl.data import DGLDataset
from dgl.nn import GraphConv
from dgl import save_graphs, load_graphs
except:
print("DGL - Error: Could not import dgl")
try:
import sklearn
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
except:
call = [sys.executable, '-m', 'pip', 'install', 'scikit-learn', '-t', sys.path[0]]
subprocess.run(call)
try:
import sklearn
from sklearn.model_selection import KFold
from sklearn.metrics import accuracy_score
except:
print("DGL - Error: Could not import sklearn")
try:
from tqdm.auto import tqdm
except:
call = [sys.executable, '-m', 'pip', 'install', 'tqdm', '-t', sys.path[0]]
subprocess.run(call)
try:
from tqdm.auto import tqdm
except:
print("DGL - Error: Could not import tqdm")
class _Dataset(DGLDataset):
def __init__(self, graphs, labels, node_attr_key):
super().__init__(name='GraphDGL')
self.graphs = graphs
self.labels = torch.LongTensor(labels)
self.node_attr_key = node_attr_key
# as all graphs have same length of node features then we get dim_nfeats from first graph in the list
self.dim_nfeats = graphs[0].ndata[node_attr_key].shape[1]
# to get the number of classes for graphs
self.gclasses = len(set(labels))
def __getitem__(self, i):
return self.graphs[i], self.labels[i]
def __len__(self):
return len(self.graphs)
class _Hparams:
def __init__(self, model_type="ClassifierHoldout", optimizer_str="Adam", amsgrad=False, betas=(0.9, 0.999), eps=1e-6, lr=0.001, lr_decay= 0, maximize=False, rho=0.9, weight_decay=0, cv_type="Holdout", split=[0.8,0.1, 0.1], k_folds=5, hl_widths=[32], conv_layer_type='SAGEConv', pooling="AvgPooling", batch_size=32, epochs=1,
use_gpu=False, loss_function="Cross Entropy"):
"""
Parameters
----------
cv : str
A string to define the method of cross-validation
"Holdout": Holdout
"K-Fold": K-Fold cross validation
k_folds : int
An int value in the range of 2 to X to define the number of k-folds for cross-validation. Default is 5.
split : list
A list of three item in the range of 0 to 1 to define the split of train,
validate, and test data. A default value of [0.8,0.1,0.1] means 80% of data will be
used for training, 10% will be used for validation, and the remaining 10% will be used for training
hl_widths : list
List of hidden neurons for each layer such as [32] will mean
that there is one hidden layers in the network with 32 neurons
optimizer : torch.optim object
This will be the selected optimizer from torch.optim package. By
default, torch.optim.Adam is selected
learning_rate : float
a step value to be used to apply the gradients by optimizer
batch_size : int
to define a set of samples to be used for training and testing in
each step of an epoch
epochs : int
An epoch means training the neural network with all the training data for one cycle. In an epoch, we use all of the data exactly once. A forward pass and a backward pass together are counted as one pass
use_GPU : use the GPU. Otherwise, use the CPU
Returns
-------
None
"""
self.model_type = model_type
self.optimizer_str = optimizer_str
self.amsgrad = amsgrad
self.betas = betas
self.eps = eps
self.lr = lr
self.lr_decay = lr_decay
self.maximize = maximize
self.rho = rho
self.weight_decay = weight_decay
self.cv_type = cv_type
self.split = split
self.k_folds = k_folds
self.hl_widths = hl_widths
self.conv_layer_type = conv_layer_type
self.pooling = pooling
self.batch_size = batch_size
self.epochs = epochs
self.use_gpu = use_gpu
self.loss_function = loss_function
class _Classic(nn.Module):
def __init__(self, in_feats, h_feats, num_classes):
"""
Parameters
----------
in_feats : int
Input dimension in the form of integer
h_feats : list
List of hidden neurons for each hidden layer
num_classes : int
Number of output classes
Returns
-------
None.
"""
super(_Classic, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
for i in range(1, len(dim)):
self.list_of_layers.append(GraphConv(dim[i-1], dim[i]))
self.final = GraphConv(dim[-1], num_classes)
def forward(self, g, in_feat):
h = in_feat
for i in range(len(self.list_of_layers)):
h = self.list_of_layers[i](g, h)
h = F.relu(h)
h = self.final(g, h)
g.ndata['h'] = h
return dgl.mean_nodes(g, 'h')
class _ClassicReg(nn.Module):
def __init__(self, in_feats, h_feats):
super(_ClassicReg, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
for i in range(1, len(dim)):
self.list_of_layers.append(GraphConv(dim[i-1], dim[i]))
self.final = nn.Linear(dim[-1], 1)
def forward(self, g, in_feat):
h = in_feat
for i in range(len(self.list_of_layers)):
h = self.list_of_layers[i](g, h)
h = F.relu(h)
h = self.final(h)
g.ndata['h'] = h
return dgl.mean_nodes(g, 'h')
class _GINConv(nn.Module):
def __init__(self, in_feats, h_feats, num_classes, pooling):
super(_GINConv, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
# Convolution (Hidden) Layers
for i in range(1, len(dim)):
lin = nn.Linear(dim[i-1], dim[i])
self.list_of_layers.append(GINConv(lin, 'sum'))
# Final Layer
self.final = nn.Linear(dim[-1], num_classes)
# Pooling layer
if pooling.lower() == "avgpooling":
self.pooling_layer = dgl.nn.AvgPooling()
elif pooling.lower() == "maxpooling":
self.pooling_layer = dgl.nn.MaxPooling()
elif pooling.lower() == "sumpooling":
self.pooling_layer = dgl.nn.SumPooling()
else:
raise NotImplementedError
def forward(self, g, in_feat):
h = in_feat
# Generate node features
for i in range(len(self.list_of_layers)): # Aim for 2 about 3 layers
h = self.list_of_layers[i](g, h)
h = F.relu(h)
# h will now be matrix of dimension num_nodes by h_feats[-1]
h = self.final(h)
g.ndata['h'] = h
# Go from node level features to graph level features by pooling
h = self.pooling_layer(g, h)
# h will now be vector of dimension num_classes
return h
class _GraphConv(nn.Module):
def __init__(self, in_feats, h_feats, num_classes, pooling):
super(_GraphConv, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
# Convolution (Hidden) Layers
for i in range(1, len(dim)):
self.list_of_layers.append(GraphConv(dim[i-1], dim[i]))
# Final Layer
# Followed example at: https://docs.dgl.ai/tutorials/blitz/5_graph_classification.html#sphx-glr-tutorials-blitz-5-graph-classification-py
self.final = GraphConv(dim[-1], num_classes)
# Pooling layer
if pooling.lower() == "avgpooling":
self.pooling_layer = dgl.nn.AvgPooling()
elif pooling.lower() == "maxpooling":
self.pooling_layer = dgl.nn.MaxPooling()
elif pooling.lower() == "sumpooling":
self.pooling_layer = dgl.nn.SumPooling()
else:
raise NotImplementedError
def forward(self, g, in_feat):
h = in_feat
# Generate node features
for i in range(len(self.list_of_layers)): # Aim for 2 about 3 layers
h = self.list_of_layers[i](g, h)
h = F.relu(h)
# h will now be matrix of dimension num_nodes by h_feats[-1]
h = self.final(g,h)
g.ndata['h'] = h
# Go from node level features to graph level features by pooling
h = self.pooling_layer(g, h)
# h will now be vector of dimension num_classes
return h
class _SAGEConv(nn.Module):
def __init__(self, in_feats, h_feats, num_classes, pooling):
super(_SAGEConv, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
# Convolution (Hidden) Layers
for i in range(1, len(dim)):
self.list_of_layers.append(SAGEConv(dim[i-1], dim[i], aggregator_type='pool'))
# Final Layer
self.final = nn.Linear(dim[-1], num_classes)
# Pooling layer
if pooling.lower() == "avgpooling":
self.pooling_layer = dgl.nn.AvgPooling()
elif pooling.lower() == "maxpooling":
self.pooling_layer = dgl.nn.MaxPooling()
elif pooling.lower() == "sumpooling":
self.pooling_layer = dgl.nn.SumPooling()
else:
raise NotImplementedError
def forward(self, g, in_feat):
h = in_feat
# Generate node features
for i in range(len(self.list_of_layers)): # Aim for 2 about 3 layers
h = self.list_of_layers[i](g, h)
h = F.relu(h)
# h will now be matrix of dimension num_nodes by h_feats[-1]
h = self.final(h)
g.ndata['h'] = h
# Go from node level features to graph level features by pooling
h = self.pooling_layer(g, h)
# h will now be vector of dimension num_classes
return h
class _TAGConv(nn.Module):
def __init__(self, in_feats, h_feats, num_classes, pooling):
super(_TAGConv, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
# Convolution (Hidden) Layers
for i in range(1, len(dim)):
self.list_of_layers.append(TAGConv(dim[i-1], dim[i], k=2))
# Final Layer
self.final = nn.Linear(dim[-1], num_classes)
# Pooling layer
if pooling.lower() == "avgpooling":
self.pooling_layer = dgl.nn.AvgPooling()
elif pooling.lower() == "maxpooling":
self.pooling_layer = dgl.nn.MaxPooling()
elif pooling.lower() == "sumpooling":
self.pooling_layer = dgl.nn.SumPooling()
else:
raise NotImplementedError
def forward(self, g, in_feat):
h = in_feat
# Generate node features
for i in range(len(self.list_of_layers)): # Aim for 2 about 3 layers
h = self.list_of_layers[i](g, h)
h = F.relu(h)
# h will now be matrix of dimension num_nodes by h_feats[-1]
h = self.final(h)
g.ndata['h'] = h
# Go from node level features to graph level features by pooling
h = self.pooling_layer(g, h)
# h will now be vector of dimension num_classes
return h
class _GraphConvReg(nn.Module):
def __init__(self, in_feats, h_feats, pooling):
super(_GraphConvReg, self).__init__()
assert isinstance(h_feats, list), "h_feats must be a list"
h_feats = [x for x in h_feats if x is not None]
assert len(h_feats) !=0, "h_feats is empty. unable to add hidden layers"
self.list_of_layers = nn.ModuleList()
dim = [in_feats] + h_feats
# Convolution (Hidden) Layers
for i in range(1, len(dim)):
self.list_of_layers.append(GraphConv(dim[i-1], dim[i]))
# Final Layer
self.final = nn.Linear(dim[-1], 1)
# Pooling layer
if pooling.lower() == "avgpooling":
self.pooling_layer = dgl.nn.AvgPooling()
elif pooling.lower() == "maxpooling":
self.pooling_layer = dgl.nn.MaxPooling()
elif pooling.lower() == "sumpooling":
self.pooling_layer = dgl.nn.SumPooling()
else:
raise NotImplementedError
def forward(self, g, in_feat):
h = in_feat
# Generate node features
for i in range(len(self.list_of_layers)): # Aim for 2 about 3 layers
h = self.list_of_layers[i](g, h)
h = F.relu(h)
# h will now be matrix of dimension num_nodes by h_feats[-1]
h = self.final(h)
g.ndata['h'] = h
# Go from node level features to graph level features by pooling
h = self.pooling_layer(g, h)
# h will now be vector of dimension num_classes
return h
class _RegressorHoldout:
def __init__(self, hparams, trainingDataset, validationDataset=None, testingDataset=None):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
self.trainingDataset = trainingDataset
self.validationDataset = validationDataset
self.testingDataset = testingDataset
self.hparams = hparams
if hparams.conv_layer_type.lower() == 'classic':
self.model = _ClassicReg(trainingDataset.dim_nfeats, hparams.hl_widths).to(device)
elif hparams.conv_layer_type.lower() == 'ginconv':
self.model = _GINConv(trainingDataset.dim_nfeats, hparams.hl_widths,
1, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'graphconv':
self.model = _GraphConvReg(trainingDataset.dim_nfeats, hparams.hl_widths, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'sageconv':
self.model = _SAGEConv(trainingDataset.dim_nfeats, hparams.hl_widths,
1, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'tagconv':
self.model = _TAGConv(trainingDataset.dim_nfeats, hparams.hl_widths,
1, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'gcn':
self.model = _ClassicReg(trainingDataset.dim_nfeats, hparams.hl_widths).to(device)
else:
raise NotImplementedError
if hparams.optimizer_str.lower() == "adadelta":
self.optimizer = torch.optim.Adadelta(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, rho=hparams.rho, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adagrad":
self.optimizer = torch.optim.Adagrad(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, lr_decay=hparams.lr_decay, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adam":
self.optimizer = torch.optim.Adam(self.model.parameters(), amsgrad=hparams.amsgrad, betas=hparams.betas, eps=hparams.eps,
lr=hparams.lr, maximize=hparams.maximize, weight_decay=hparams.weight_decay)
self.use_gpu = hparams.use_gpu
self.training_loss_list = []
self.validation_loss_list = []
self.node_attr_key = trainingDataset.node_attr_key
# train, validate, test split
num_train = int(len(trainingDataset) * (hparams.split[0]))
num_validate = int(len(trainingDataset) * (hparams.split[1]))
num_test = len(trainingDataset) - num_train - num_validate
idx = torch.randperm(len(trainingDataset))
train_sampler = SubsetRandomSampler(idx[:num_train])
validate_sampler = SubsetRandomSampler(idx[num_train:num_train+num_validate])
test_sampler = SubsetRandomSampler(idx[num_train+num_validate:num_train+num_validate+num_test])
if validationDataset:
self.train_dataloader = GraphDataLoader(trainingDataset,
batch_size=hparams.batch_size,
drop_last=False)
self.validate_dataloader = GraphDataLoader(validationDataset,
batch_size=hparams.batch_size,
drop_last=False)
else:
self.train_dataloader = GraphDataLoader(trainingDataset, sampler=train_sampler,
batch_size=hparams.batch_size,
drop_last=False)
self.validate_dataloader = GraphDataLoader(trainingDataset, sampler=validate_sampler,
batch_size=hparams.batch_size,
drop_last=False)
if testingDataset:
self.test_dataloader = GraphDataLoader(testingDataset,
batch_size=len(testingDataset),
drop_last=False)
else:
self.test_dataloader = GraphDataLoader(trainingDataset, sampler=test_sampler,
batch_size=hparams.batch_size,
drop_last=False)
def train(self):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
# Init the loss and accuracy reporting lists
self.training_loss_list = []
self.validation_loss_list = []
# Run the training loop for defined number of epochs
for _ in tqdm(range(self.hparams.epochs), desc='Epochs', total=self.hparams.epochs, leave=False):
# Iterate over the DataLoader for training data
for batched_graph, labels in tqdm(self.train_dataloader, desc='Training', leave=False):
# Make sure the model is in training mode
self.model.train()
# Zero the gradients
self.optimizer.zero_grad()
# Perform forward pass
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
# Compute loss
loss = F.mse_loss(torch.flatten(pred), labels.float())
# Perform backward pass
loss.backward()
# Perform optimization
self.optimizer.step()
self.training_loss_list.append(torch.sqrt(loss).item())
self.validate()
self.validation_loss_list.append(torch.sqrt(self.validation_loss).item())
def validate(self):
device = torch.device("cpu")
self.model.eval()
for batched_graph, labels in tqdm(self.validate_dataloader, desc='Validating', leave=False):
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
loss = F.mse_loss(torch.flatten(pred), labels.float())
self.validation_loss = loss
def test(self):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
self.model.eval()
for batched_graph, labels in tqdm(self.test_dataloader, desc='Testing', leave=False):
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
loss = F.mse_loss(torch.flatten(pred), labels.float())
self.testing_loss = torch.sqrt(loss).item()
def save(self, path):
if path:
# Make sure the file extension is .pt
ext = path[len(path)-3:len(path)]
if ext.lower() != ".pt":
path = path+".pt"
torch.save(self.model, path)
class _RegressorKFold:
def __init__(self, hparams, trainingDataset, testingDataset=None):
self.trainingDataset = trainingDataset
self.testingDataset = testingDataset
self.hparams = hparams
self.losses = []
self.min_loss = 0
# at beginning of the script
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
if hparams.conv_layer_type.lower() == 'classic':
self.model = _ClassicReg(trainingDataset.dim_nfeats, hparams.hl_widths).to(device)
elif hparams.conv_layer_type.lower() == 'ginconv':
self.model = _GINConv(trainingDataset.dim_nfeats, hparams.hl_widths,
1, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'graphconv':
self.model = _GraphConvReg(trainingDataset.dim_nfeats, hparams.hl_widths, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'sageconv':
self.model = _SAGEConv(trainingDataset.dim_nfeats, hparams.hl_widths,
1, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'tagconv':
self.model = _TAGConv(trainingDataset.dim_nfeats, hparams.hl_widths,
1, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'gcn':
self.model = _ClassicReg(trainingDataset.dim_nfeats, hparams.hl_widths).to(device)
else:
raise NotImplementedError
if hparams.optimizer_str.lower() == "adadelta":
self.optimizer = torch.optim.Adadelta(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, rho=hparams.rho, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adagrad":
self.optimizer = torch.optim.Adagrad(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, lr_decay=hparams.lr_decay, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adam":
self.optimizer = torch.optim.Adam(self.model.parameters(), amsgrad=hparams.amsgrad, betas=hparams.betas, eps=hparams.eps,
lr=hparams.lr, maximize=hparams.maximize, weight_decay=hparams.weight_decay)
self.use_gpu = hparams.use_gpu
self.training_loss_list = []
self.validation_loss_list = []
self.node_attr_key = trainingDataset.node_attr_key
# train, validate, test split
num_train = int(len(trainingDataset) * (hparams.split[0]))
num_validate = int(len(trainingDataset) * (hparams.split[1]))
num_test = len(trainingDataset) - num_train - num_validate
idx = torch.randperm(len(trainingDataset))
test_sampler = SubsetRandomSampler(idx[num_train+num_validate:num_train+num_validate+num_test])
if testingDataset:
self.test_dataloader = GraphDataLoader(testingDataset,
batch_size=len(testingDataset),
drop_last=False)
else:
self.test_dataloader = GraphDataLoader(trainingDataset, sampler=test_sampler,
batch_size=hparams.batch_size,
drop_last=False)
def reset_weights(self):
'''
Try resetting model weights to avoid
weight leakage.
'''
device = torch.device("cpu")
if self.hparams.conv_layer_type.lower() == 'classic':
self.model = _ClassicReg(self.trainingDataset.dim_nfeats, self.hparams.hl_widths).to(device)
elif self.hparams.conv_layer_type.lower() == 'ginconv':
self.model = _GINConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
1, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'graphconv':
self.model = _GraphConvReg(self.trainingDataset.dim_nfeats, self.hparams.hl_widths, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'sageconv':
self.model = _SAGEConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
1, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'tagconv':
self.model = _TAGConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
1, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'gcn':
self.model = _ClassicReg(self.trainingDataset.dim_nfeats, self.hparams.hl_widths).to(device)
else:
raise NotImplementedError
if self.hparams.optimizer_str.lower() == "adadelta":
self.optimizer = torch.optim.Adadelta(self.model.parameters(), eps=self.hparams.eps,
lr=self.hparams.lr, rho=self.hparams.rho, weight_decay=self.hparams.weight_decay)
elif self.hparams.optimizer_str.lower() == "adagrad":
self.optimizer = torch.optim.Adagrad(self.model.parameters(), eps=self.hparams.eps,
lr=self.hparams.lr, lr_decay=self.hparams.lr_decay, weight_decay=self.hparams.weight_decay)
elif self.hparams.optimizer_str.lower() == "adam":
self.optimizer = torch.optim.Adam(self.model.parameters(), amsgrad=self.hparams.amsgrad, betas=self.hparams.betas, eps=self.hparams.eps,
lr=self.hparams.lr, maximize=self.hparams.maximize, weight_decay=self.hparams.weight_decay)
def train(self):
device = torch.device("cpu")
# The number of folds (This should come from the hparams)
k_folds = self.hparams.k_folds
# Init the loss and accuracy reporting lists
self.training_loss_list = []
self.validation_loss_list = []
# Set fixed random number seed
torch.manual_seed(42)
# Define the K-fold Cross Validator
kfold = KFold(n_splits=k_folds, random_state=42, shuffle=True)
models = []
weights = []
losses = []
train_dataloaders = []
validate_dataloaders = []
# K-fold Cross-validation model evaluation
for fold, (train_ids, validate_ids) in tqdm(enumerate(kfold.split(self.trainingDataset)), desc="Fold", initial=1, total=k_folds, leave=False):
epoch_training_loss_list = []
epoch_validation_loss_list = []
# Sample elements randomly from a given list of ids, no replacement.
train_subsampler = torch.utils.data.SubsetRandomSampler(train_ids)
validate_subsampler = torch.utils.data.SubsetRandomSampler(validate_ids)
# Define data loaders for training and testing data in this fold
self.train_dataloader = GraphDataLoader(self.trainingDataset, sampler=train_subsampler,
batch_size=self.hparams.batch_size,
drop_last=False)
self.validate_dataloader = GraphDataLoader(self.trainingDataset, sampler=validate_subsampler,
batch_size=self.hparams.batch_size,
drop_last=False)
# Init the neural network
self.reset_weights()
# Run the training loop for defined number of epochs
best_rmse = np.inf
# Run the training loop for defined number of epochs
for _ in tqdm(range(self.hparams.epochs), desc='Epochs', total=self.hparams.epochs, initial=1, leave=False):
# Iterate over the DataLoader for training data
for batched_graph, labels in tqdm(self.train_dataloader, desc='Training', leave=False):
# Make sure the model is in training mode
self.model.train()
# Zero the gradients
self.optimizer.zero_grad()
# Perform forward pass
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
# Compute loss
loss = F.mse_loss(torch.flatten(pred), labels.float())
# Perform backward pass
loss.backward()
# Perform optimization
self.optimizer.step()
epoch_training_loss_list.append(torch.sqrt(loss).item())
self.validate()
epoch_validation_loss_list.append(torch.sqrt(self.validation_loss).item())
models.append(self.model)
weights.append(copy.deepcopy(self.model.state_dict()))
losses.append(torch.sqrt(self.validation_loss).item())
train_dataloaders.append(self.train_dataloader)
validate_dataloaders.append(self.validate_dataloader)
self.training_loss_list.append(epoch_training_loss_list)
self.validation_loss_list.append(epoch_validation_loss_list)
self.validate_dataloaders = validate_dataloaders
self.train_dataloaders = train_dataloaders
self.losses = losses
min_loss = min(losses)
self.min_loss = min_loss
ind = losses.index(min_loss)
self.models = models
self.weights = weights
self.model = models[ind]
self.model.load_state_dict(weights[ind])
self.model.eval()
self.training_loss_list = self.training_loss_list[ind]
self.validation_loss_list = self.validation_loss_list[ind]
def validate(self):
device = torch.device("cpu")
self.model.eval()
for batched_graph, labels in tqdm(self.validate_dataloader, desc='Validating', leave=False):
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
loss = F.mse_loss(torch.flatten(pred), labels.float())
self.validation_loss = loss
def test(self):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
#self.model.eval()
for batched_graph, labels in tqdm(self.test_dataloader, desc='Testing', leave=False):
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
loss = F.mse_loss(torch.flatten(pred), labels.float())
self.testing_loss = torch.sqrt(loss).item()
def save(self, path):
if path:
# Make sure the file extension is .pt
ext = path[len(path)-3:len(path)]
if ext.lower() != ".pt":
path = path+".pt"
torch.save(self.model, path)
class _ClassifierHoldout:
def __init__(self, hparams, trainingDataset, validationDataset=None, testingDataset=None):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
self.trainingDataset = trainingDataset
self.validationDataset = validationDataset
self.testingDataset = testingDataset
self.hparams = hparams
if hparams.conv_layer_type.lower() == 'classic':
self.model = _Classic(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses).to(device)
elif hparams.conv_layer_type.lower() == 'ginconv':
self.model = _GINConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'graphconv':
self.model = _GraphConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'sageconv':
self.model = _SAGEConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'tagconv':
self.model = _TAGConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'gcn':
self.model = _Classic(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses).to(device)
else:
raise NotImplementedError
if hparams.optimizer_str.lower() == "adadelta":
self.optimizer = torch.optim.Adadelta(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, rho=hparams.rho, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adagrad":
self.optimizer = torch.optim.Adagrad(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, lr_decay=hparams.lr_decay, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adam":
self.optimizer = torch.optim.Adam(self.model.parameters(), amsgrad=hparams.amsgrad, betas=hparams.betas, eps=hparams.eps,
lr=hparams.lr, maximize=hparams.maximize, weight_decay=hparams.weight_decay)
self.use_gpu = hparams.use_gpu
self.training_loss_list = []
self.validation_loss_list = []
self.training_accuracy_list = []
self.validation_accuracy_list = []
self.node_attr_key = trainingDataset.node_attr_key
# train, validate, test split
num_train = int(len(trainingDataset) * (hparams.split[0]))
num_validate = int(len(trainingDataset) * (hparams.split[1]))
num_test = len(trainingDataset) - num_train - num_validate
idx = torch.randperm(len(trainingDataset))
train_sampler = SubsetRandomSampler(idx[:num_train])
validate_sampler = SubsetRandomSampler(idx[num_train:num_train+num_validate])
test_sampler = SubsetRandomSampler(idx[num_train+num_validate:num_train+num_validate+num_test])
if validationDataset:
self.train_dataloader = GraphDataLoader(trainingDataset,
batch_size=hparams.batch_size,
drop_last=False)
self.validate_dataloader = GraphDataLoader(validationDataset,
batch_size=hparams.batch_size,
drop_last=False)
else:
self.train_dataloader = GraphDataLoader(trainingDataset, sampler=train_sampler,
batch_size=hparams.batch_size,
drop_last=False)
self.validate_dataloader = GraphDataLoader(trainingDataset, sampler=validate_sampler,
batch_size=hparams.batch_size,
drop_last=False)
if testingDataset:
self.test_dataloader = GraphDataLoader(testingDataset,
batch_size=len(testingDataset),
drop_last=False)
else:
self.test_dataloader = GraphDataLoader(trainingDataset, sampler=test_sampler,
batch_size=hparams.batch_size,
drop_last=False)
def train(self):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
# Init the loss and accuracy reporting lists
self.training_accuracy_list = []
self.training_loss_list = []
self.validation_accuracy_list = []
self.validation_loss_list = []
# Run the training loop for defined number of epochs
for _ in tqdm(range(self.hparams.epochs), desc='Epochs', initial=1, leave=False):
temp_loss_list = []
temp_acc_list = []
# Iterate over the DataLoader for training data
for batched_graph, labels in tqdm(self.train_dataloader, desc='Training', leave=False):
# Make sure the model is in training mode
self.model.train()
# Zero the gradients
self.optimizer.zero_grad()
# Perform forward pass
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
# Compute loss
if self.hparams.loss_function.lower() == "negative log likelihood":
logp = F.log_softmax(pred, 1)
loss = F.nll_loss(logp, labels)
elif self.hparams.loss_function.lower() == "cross entropy":
loss = F.cross_entropy(pred, labels)
# Save loss information for reporting
temp_loss_list.append(loss.item())
temp_acc_list.append(accuracy_score(labels, pred.argmax(1)))
# Perform backward pass
loss.backward()
# Perform optimization
self.optimizer.step()
self.training_accuracy_list.append(np.mean(temp_acc_list).item())
self.training_loss_list.append(np.mean(temp_loss_list).item())
self.validate()
self.validation_accuracy_list.append(self.validation_accuracy)
self.validation_loss_list.append(self.validation_loss)
def validate(self):
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
temp_loss_list = []
temp_acc_list = []
self.model.eval()
for batched_graph, labels in tqdm(self.validate_dataloader, desc='Validating', leave=False):
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float()).to(device)
if self.hparams.loss_function.lower() == "negative log likelihood":
logp = F.log_softmax(pred, 1)
loss = F.nll_loss(logp, labels)
elif self.hparams.loss_function.lower() == "cross entropy":
loss = F.cross_entropy(pred, labels)
temp_loss_list.append(loss.item())
temp_acc_list.append(accuracy_score(labels, pred.argmax(1)))
self.validation_accuracy = np.mean(temp_acc_list).item()
self.validation_loss = np.mean(temp_loss_list).item()
def test(self):
if self.test_dataloader:
temp_loss_list = []
temp_acc_list = []
self.model.eval()
for batched_graph, labels in tqdm(self.test_dataloader, desc='Testing', leave=False):
pred = self.model(batched_graph, batched_graph.ndata[self.node_attr_key].float())
if self.hparams.loss_function.lower() == "negative log likelihood":
logp = F.log_softmax(pred, 1)
loss = F.nll_loss(logp, labels)
elif self.hparams.loss_function.lower() == "cross entropy":
loss = F.cross_entropy(pred, labels)
temp_loss_list.append(loss.item())
temp_acc_list.append(accuracy_score(labels, pred.argmax(1)))
self.testing_accuracy = np.mean(temp_acc_list).item()
self.testing_loss = np.mean(temp_loss_list).item()
def save(self, path):
if path:
# Make sure the file extension is .pt
ext = path[len(path)-3:len(path)]
if ext.lower() != ".pt":
path = path+".pt"
torch.save(self.model, path)
class _ClassifierKFold:
def __init__(self, hparams, trainingDataset, testingDataset=None):
self.trainingDataset = trainingDataset
self.testingDataset = testingDataset
self.hparams = hparams
self.testing_accuracy = 0
self.accuracies = []
self.max_accuracy = 0
# at beginning of the script
#device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
device = torch.device("cpu")
if hparams.conv_layer_type.lower() == 'classic':
self.model = _Classic(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses).to(device)
elif hparams.conv_layer_type.lower() == 'ginconv':
self.model = _GINConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'graphconv':
self.model = _GraphConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'sageconv':
self.model = _SAGEConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
elif hparams.conv_layer_type.lower() == 'tagconv':
self.model = _TAGConv(trainingDataset.dim_nfeats, hparams.hl_widths,
trainingDataset.gclasses, hparams.pooling).to(device)
else:
raise NotImplementedError
if hparams.optimizer_str.lower() == "adadelta":
self.optimizer = torch.optim.Adadelta(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, rho=hparams.rho, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adagrad":
self.optimizer = torch.optim.Adagrad(self.model.parameters(), eps=hparams.eps,
lr=hparams.lr, lr_decay=hparams.lr_decay, weight_decay=hparams.weight_decay)
elif hparams.optimizer_str.lower() == "adam":
self.optimizer = torch.optim.Adam(self.model.parameters(), amsgrad=hparams.amsgrad, betas=hparams.betas, eps=hparams.eps,
lr=hparams.lr, maximize=hparams.maximize, weight_decay=hparams.weight_decay)
self.use_gpu = hparams.use_gpu
self.training_loss_list = []
self.validation_loss_list = []
self.training_accuracy_list = []
self.validation_accuracy_list = []
self.node_attr_key = trainingDataset.node_attr_key
def reset_weights(self):
'''
Try resetting model weights to avoid
weight leakage.
'''
device = torch.device("cpu")
if self.hparams.conv_layer_type.lower() == 'classic':
self.model = _Classic(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
self.trainingDataset.gclasses).to(device)
elif self.hparams.conv_layer_type.lower() == 'ginconv':
self.model = _GINConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
self.trainingDataset.gclasses, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'graphconv':
self.model = _GraphConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
self.trainingDataset.gclasses, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'sageconv':
self.model = _SAGEConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
self.trainingDataset.gclasses, self.hparams.pooling).to(device)
elif self.hparams.conv_layer_type.lower() == 'tagconv':
self.model = _TAGConv(self.trainingDataset.dim_nfeats, self.hparams.hl_widths,
self.trainingDataset.gclasses, self.hparams.pooling).to(device)
else: