-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathTSTF.py
More file actions
2926 lines (2190 loc) · 146 KB
/
TSTF.py
File metadata and controls
2926 lines (2190 loc) · 146 KB
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
#!/usr/bin/env python3
'''
# Train on subgraph and Test on Full graph. Thus TSTF
'''
'''
To run relaxation:
1. Set relax_target_data = False (Normal run)
2. Run for each model_type for Cora and CiteSeer. This saves the corresponding shadow and target files to train n test attacks
3. Set relax_target_data = True
4. Change data_type to CiteSeer
5. End
'''
'''
To run vanpd, set isoutput_perturb_defense = True
To run lbp_defense, set use_binning = True, use_lbp = True and num_bins
To run nsd_defense, set use_nsd = True and how_many_edges_k
'''
import os.path as osp
import torch
import torch.nn.functional as F
from torch_geometric.datasets import Planetoid, Reddit, Flickr
from torch_geometric.nn import GCNConv, SAGEConv, SGConv, GATConv
from tqdm import tqdm
import networkx as nx
import time
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import os
import torch.nn as nn
from torch_geometric.data import NeighborSampler
from torch_geometric.utils import subgraph
from torch_geometric.data import Data
import random
import sys
import itertools
# from itertools import tee
import statistics
from sklearn.metrics import accuracy_score, precision_score, recall_score, auc, roc_curve, roc_auc_score, f1_score
from torch.nn.utils import clip_grad_norm_
from scipy.spatial.distance import jensenshannon
# No need for this, condor auto assigns
if torch.cuda.is_available():
torch.cuda.set_device(0) # change this cos sometimes port 0 is full
# # Reset params of trained model
# for layer in model.children():
# if hasattr(layer, "reset_parameters"):
# layer.reset_parameters()
if torch.cuda.is_available():
global_path = "/dstore/home/iyiola/"
else:
global_path = "./"
num_of_runs = 2#11 # # this runs the program 10 times
# Different defense mechanisms
def lbp_defense(pred, num_
s, beta, use_lbp):
# #Binned version========>
pred = pred.cpu().detach().numpy()
for i in range(0, len(pred)):
each_pred = pred[i]
idx = np.array([x for x in range(pred.shape[1])])
p = np.random.permutation(len(each_pred))
# shuffled versions
each_pred = each_pred[p]
idx = idx[p]
# divide into bins
random_split_pred = np.array_split(each_pred, num_bins)
random_split_idx = np.array_split(idx, num_bins)
# print("random_split_pred", random_split_pred, "random_split_idx", random_split_idx)
# print("random_split_idx====>", random_split_idx[0], random_split_idx[1], random_split_idx[2])
for bin in range(num_bins):
if use_lbp:
''' version on bins. use beta '''
beta = 1 / beta
random_split_pred[bin] += np.random.laplace(0, beta,
1) # multiply each partition by the corresponding noise value
else:
''' This is the normal version that use the mean of each partition as noise '''
mean_each_split_pred = np.mean(random_split_pred[bin]) # calculate mean of each partition
# print("mean", mean_each_split_pred)
random_split_pred[
bin] += mean_each_split_pred # multiply each partition by the corresponding mean value
# Loop through and set value of pred back to the new one with their bins
for w, k in zip(random_split_idx[bin], random_split_pred[bin]):
# print("This is w", w, "k", k)
pred[i][w] = k
# turn back to float tensor
pred = torch.FloatTensor(pred)
return pred
def multiply_perturbation_defense(pred, beta):
# Original========> i.e no binning
# just multiply each posterior by 0.1 i,e alpha
pred = pred.cpu().detach().numpy()
for i in range(0, len(pred)):
# changed it to \beta * U(-1, 1) whwre alpha is the. Bes
# sample_noise_uniform
alpha = round(random.uniform(0.1, 0.2), 10) #random.uniform(0.1, 0.2) #multiply each row by different numbers between 0.1 and 1.0 with floating precision of 10 e.g 0.7812920741
# print("alpha", alpha)
# That is, samoling from unifirm distribution of numbers between 0.1 and 1.0 and they have equal probability of appearing
for j in range(0, len(pred[i])):
pred[i][j] *= alpha#alpha # only use multiplication if you are perturbing the shadow as well (alpha*beta) 0.1 beta is better
# turn back to float tensor
pred = torch.FloatTensor(pred)
return pred
def vanpd_defense(pred, beta):
pred = pred.cpu().detach().numpy()
# add laplacian noise
beta = 1 / beta # 1 here is the sensitivity
for i in range(0, len(pred)):
for j in range(0, len(pred[i])):
pred[i][j] += np.random.laplace(0, beta, 1)
# turn back to float tensor
pred = torch.FloatTensor(pred)
return pred
def normalize_posterior(pred):
pred = torch.exp(pred)
# convert to numpy
pred = pred.cpu().detach().numpy()
norm_pred = pred / pred.sum(axis=1,keepdims=True) # scale or divide each element by the sum of each row
# convert back to torch
norm_pred = torch.FloatTensor(norm_pred).to(device)
return norm_pred
def clip_logits_norm(parameters, max_norm=4, norm_type=2, beta=0.1, add_laplacian_noise=False, add_gaussian_noise=False):
r"""Clips gradient norm of an iterable of parameters.
The norm is computed over all gradients together, as if they were
concatenated into a single vector. Gradients are modified in-place.
Arguments:
parameters (Iterable[Tensor] or Tensor): an iterable of Tensors or a
single Tensor that will have gradients normalized
max_norm (float or int): max norm of the gradients
norm_type (float or int): type of the used p-norm. Can be ``'inf'`` for
infinity norm.
Returns:
Total norm of the parameters (viewed as a single vector).
"""
# if isinstance(parameters, torch.Tensor):
# parameters = [parameters]
# parameters = list(filter(lambda p: p.grad is not None, parameters))
max_norm = float(max_norm)
norm_type = float(norm_type)
# if norm_type == inf:
# total_norm = max(p.grad.detach().abs().max() for p in parameters)
# else:
# total_norm = torch.norm(torch.stack([torch.norm(p.grad.detach(), norm_type) for p in parameters]), norm_type)
# print("b4 parameters", parameters)
total_norm = torch.norm(parameters, norm_type)
# print("total_norm", total_norm)
clip_coef = max_norm / (total_norm + 1e-6)
# print("clip_coef", clip_coef)
if clip_coef < 1:
for i in range(0, len(parameters)):
# print("p", p)
# p.grad.detach().mul_(clip_coef)
parameters[i].mul(clip_coef)
# print("after multiplying parameters", parameters)
# add Gaussian noise
if add_gaussian_noise:
# print("torch.normal(mean=0.0, std=beta * max_norm, size=(parameters.shape[0], parameters.shape[1]))", torch.normal(mean=0.0, std=beta * max_norm, size=(parameters.shape[0], parameters.shape[1])))
parameters += torch.normal(mean=0.0, std=beta * max_norm, size=(parameters.shape[0], parameters.shape[1])).to(device)
elif add_laplacian_noise:
# laplacian noise
for i in range(0, len(parameters)):
for j in range(0, len(parameters[i])):
# k = torch.normal(2, 3, size=(1, 1))
# print("k", k)
beta = 1 / beta # 1 here is the sensitivity
# print("np.random.laplace(0, beta, 1)", np.random.laplace(0, beta, 1))
lap_noise = torch.distributions.laplace.Laplace(torch.tensor([0.0]), torch.tensor([beta]))
parameters[i][j] += lap_noise.sample().item()
# noisy_logits
else:
print("no noise")
# print("noisy parameters", parameters)
return parameters
def delete_tensor(tensor, indices):
# deletes all tensors except those that were selected i.e only keep the indices
mask = torch.zeros(tensor[0].numel(), dtype=torch.bool)
mask[indices] = True
# Remove from both direction of edge index
tensor_0 = tensor[0][mask]
tensor_1 = tensor[1][mask]
stack_tensor = torch.stack([tensor_0, tensor_1])
return stack_tensor
def k_edge_index(edge_index, k):
print("B4 k edge index", len(edge_index[0]))
# node:neighbors_index
node_list_index_list = []
node_list_index_dict = {}
for i in edge_index[0]:
# print(i)
node_list_index = (edge_index[0] == i).nonzero(as_tuple=True)[0].tolist() # returns the index of all the occurences of the node. We will use that to "delete" the node later
node_list_index_dict[i.item()] = node_list_index
print("len(node_list_index_dict)", len(node_list_index_dict))
for node in node_list_index_dict:
# loop through and only select top k
if len(node_list_index_dict[node]) > k:
# randomly select k
selected = random.sample(node_list_index_dict[node], k)
node_list_index_list.append(selected)
# join list of list
all_selected_node_index = list(itertools.chain.from_iterable(node_list_index_list))
# print("all_selected_node_index", all_selected_node_index)
print("After k edge index", len(all_selected_node_index))
# delete all except those that were selected
# delete_tensor()
k_edge_index = delete_tensor(edge_index, all_selected_node_index)
return k_edge_index
# confidence score distortion
def compute_confidence_distortion(noisy_posterior, non_noisy_posteriors):
targetmember_noisy = pd.read_csv(noisy_posterior, header=None, sep=" ")
print("targetmember_noisy", targetmember_noisy.shape)
# convert to tensor
targetmember_noisy = torch.tensor(targetmember_noisy.values)
targetmember_nonoise = pd.read_csv(non_noisy_posteriors, header=None, sep=" ")
print("targetmember_nonoise", targetmember_nonoise.shape)
targetmember_nonoise = torch.tensor(targetmember_nonoise.values)
target_member_nonoise_noise_overall_sum = []
for i in range(len(targetmember_nonoise)):
target_member_nonoise_noisy_js = jensenshannon(targetmember_nonoise[i], targetmember_noisy[i],
base=2) # rel_entr(targetmember_nonoise[i], targetmember_noisy[i])
sum_each_dim = target_member_nonoise_noisy_js # sum(target_member_nonoise_noisy_js)
print(sum_each_dim)
target_member_nonoise_noise_overall_sum.append(sum_each_dim.item())
final_member_nonoise_noisy_js = sum(target_member_nonoise_noise_overall_sum) / len(targetmember_nonoise)
print("final_member_nonoise_noisy_js", final_member_nonoise_noisy_js)
return final_member_nonoise_noisy_js
for global_model_type in ["Cora", "CiteSeer", "PubMed", "Flickr"]: #["Cora"]:#, "CiteSeer", "PubMed", "Flickr"]:
# for global_k in [0, 1, 2, 3]:
# for global_bin in [2, 3, 4]:
# for global_eps in [0.2, 0.5, 1.2, 2.0, 3, 10]:
# random_data = [1050154401, 87952126, 461858464, 2251922041, 2203565404, 2569991973, 569824674, 2721098863, 836273002,2935227127]
random_data = [1050154401]
if torch.cuda.is_available():
home_root = "/dstore/home/iyiola/"
else:
home_root = "./"
all_results = []
result_file_average = open(home_root + "Average_resultfile_TSTF_" +".txt", "a")
target_train_loss_acc_per_run = []
target_approx_train_acc_per_run = []
target_train_acc_per_run = []
target_test_acc_per_run = []
target_macro_acc_per_run = []
target_micro_acc_per_run = []
shadow_train_loss_acc_per_run = []
shadow_approx_train_acc_per_run = []
shadow_train_acc_per_run = []
shadow_test_acc_per_run = []
shadow_macro_acc_per_run = []
shadow_micro_acc_per_run = []
precision_per_run = []
auroc_per_run = []
recall_per_run = []
f1_score_per_run = []
total_time_per_run = []
# we run each data_type e.g cora against all model type
'''
Set parameters here ===================================================================================?????????
'''
model_type = "GCN" # GCN, GAT, SAGE, SGC
shadow_model_type = "GCN"
target_num_neurons = 256
shadow_num_neurons = 256 # 256 64
# relaxation
relax_target_data = False
# defense
isdp_logits = False # Adds noise to the logits (logits = layer b4 the softmax)
add_laplacian_to_logits = False
add_gaussian_to_logits = False
max_norm_logits = 2
isoutput_perturb_defense = False # This adds noise only to the posterior of the target model. The shadow is left untouched!. Note, noise should be addded at the test (when u query the target model!)
beta = 0.2#global_eps #0.2
perturb_shadow = False # perturb shadow model with the same perturbation as the target
ismultiply_by_beta = False # True # multiply posterior by beta. 0.2. Works better than 0.5. If set to false, then its normal i.e no multiplication
# ismultiply_by_beta needs to be set to True to use use_binning and use_lbp
# if use_binning is set to False, then there is no binning and just do multiplicative with the value of beta
use_binning = False # meanbdp Set to True to use the binned version. If set to true, it uses the mean of each bin and adds the corresponding value. No need for beta
use_lbp = False # lbdp Also binned but add noise drawn from Laplacian distribution to each bin. It use beta here. Also use_binning needs be True
num_bins = 2#global_bin #2
use_prior_inductive_split = False # True #False # set to true if you wanna use the prior method of splitting the graph. Setting to false is a lot faster and better method!
remove_edge_at_test_index = False#True # When an attacker send a query, do not use the entire neighbor
use_nsd = False # nsd to use this remove_edge_at_test_index needs to be set to False
how_many_edges_k = 2#global_k #3 # e.g selects 3 random neighbors {mask on the adjacency matrix}
data_type = global_model_type #"Cora" # CiteSeer, Cora, PubMed, Flickr, Reddit
# # CiteSeer (binary features), Cora (binary features), PubMed(float where necessary), Flickr(integers), Reddit(float rep)
# catering for only using Cora as target and CiteSeer as shadow and vice versa.
# The data_type becomes the shadow and the opposite becomes the target
# e.g if Cora is the data_type, then CiteSeer is the target n Cora is the shadow
if relax_target_data:
if data_type == "Cora":
relax_target_data_type = "CiteSeer"
else:
relax_target_data_type = "Cora"
else:
relax_target_data_type = data_type # the same as data type
print("Target data type for relaxation", relax_target_data_type)
print("Shadow data type", data_type)
mode = "TSTF" # train on subgraph, test on full grah
if isdp_logits == True and add_laplacian_to_logits == True:
def_t = "vanlapdp_logits"
defense_type = def_t + str(max_norm_logits)+str(beta)
elif isdp_logits == True and add_gaussian_to_logits == True:
def_t = "vangaudp_logits"
defense_type = def_t + str(max_norm_logits) + str(beta)
elif isoutput_perturb_defense == True:
def_t = "vanpd_posterior"
defense_type = def_t + str(beta) #original vanilla
elif ismultiply_by_beta and use_binning and use_lbp:
def_t = "lbdp"
defense_type = def_t + str(beta) + str(num_bins)
elif ismultiply_by_beta and use_binning:
def_t = "meanbdp"
defense_type = def_t + str(num_bins)
elif use_nsd == True:
def_t = "neigbhordist"
defense_type = def_t +str(how_many_edges_k)
else:
def_t = "normal"
defense_type = def_t # no defense
print("defense type", defense_type)
# writing all print to file
old_stdout = sys.stdout
log_file = open("message"+data_type+model_type+defense_type+".txt","w")
sys.stdout = log_file
#TODO Run after
save_shadow_OutTrain = "posteriorsShadowOut_" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_shadow_InTrain = "posteriorsShadowTrain_" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_target_OutTrain = "posteriorsTargetOut_" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_target_InTrain = "posteriorsTargetTrain_" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_correct_incorrect_homophily_prediction = "correct_incorrect_homo_pred" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_global_true_homophily = "true_homophily" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_global_pred_homophily = "pred_homophily" + mode + "_" + data_type + "_" + model_type + defense_type + ".txt"
save_target_InTrain_nodes_neigbors = "nodesNeigborsTargetTrain_" + mode + "_" + data_type + "_" + model_type + defense_type + ".npy" # TODO N
save_target_OutTrain_nodes_neigbors = "nodesNeigborsTargetOut_" + mode + "_" + data_type + "_" + model_type + defense_type + ".npy" # TODO N
for which_run, rand_state in enumerate(random_data): #range(1, num_of_runs)
# result_file = open(global_path + "resultfile_" + mode + "_" + model_type + "_" + shadow_model_type + defense_type +".txt", "a")
result_file = open(global_path + "resultfile_" + mode + "_" + model_type + "_" + shadow_model_type + def_t +".txt", "a")
# random_data = os.urandom(4)
# rand_state = 1050154401 #int.from_bytes(random_data, byteorder="big") # 4123696913 #10, #3469326556, 959554842 1048906271 2784139507 2676276030(Better), 75126506#
# rand_state = [1050154401, 87952126, 461858464, 2251922041, 2203565404, 2569991973, 569824674, 2721098863, 836273002,2935227127]
# rand_state = [1050154401]
print("rand_state", rand_state)
torch.manual_seed(rand_state)
torch.cuda.manual_seed(rand_state)
random.seed(rand_state)
np.random.seed(seed=rand_state)
torch.cuda.manual_seed_all(rand_state) # if you are using multi-GPU.
torch.backends.cudnn.benchmark = False
torch.backends.cudnn.deterministic = True
# torch.set_default_dtype(torch.float64) #set default torch to 64 floating
start_time = time.time()
'''
######################################## Data ##############################################
'''
if data_type == "Reddit":
###################################### Reddit ##################################
# path = osp.join(osp.dirname(osp.realpath(__file__)), '..', 'data', 'Reddit')
path = global_path+"data/"+data_type #"/dstore/home/iyiola/data/Reddit"
dataset = Reddit(path)
# data = dataset[0]
# print("len(dataset)", len(dataset)) # Reddit dataset consists of 1 graph
# print("data", data) # Data(edge_index=[2, 114615892], test_mask=[232965], train_mask=[232965], val_mask=[232965], x=[232965, 602], y=[232965])
# print("Total Num of nodes in dataset", data.num_nodes) # 232965
# print("Total Num of edges in dataset", data.num_edges) # 114615892
# print("Total Num of node features in dataset", data.num_node_features) # 602
# print("Total Num of features in dataset", dataset.num_features) # same as node features # 602
# print("Num classes", dataset.num_classes) #41
# Reduced this cos it's taking too long to create subgraph
num_train_Train_per_class = 500 #500 # 1000 50 for redditSmall
num_train_Shadow_per_class = 500 #500 # 1000
num_test_Target = 20500 #20500 # 41000
num_test_Shadow = 20500 #20500 # 41000
# normal train test of target model. For comparing with distorted / the defensed method
# note: all normal_precision, normal_recall and normal_auroc is wrt to not using prior inductive split for fair comparison
if model_type == "GCN":
normal_test = 0
normal_precision = 0
normal_recall = 0
normal_auroc = 0
elif model_type == "GAT":
normal_test = 0
normal_precision = 0
normal_recall = 0
normal_auroc = 0
elif model_type == "SGC":
normal_test = 0
normal_precision = 0
normal_recall = 0
normal_auroc = 0
else:
normal_test = 0 #SAGE
normal_precision = 0
normal_recall = 0
normal_auroc = 0
elif data_type == "Flickr":
###################################### Flickr ##################################
path = global_path+"data/"+data_type #"/dstore/home/iyiola/Flickr"
dataset = Flickr(path)
data = dataset[0]
# print("len(dataset)", len(dataset)) # Flikr dataset consists of 1 graph
# print("data",
# data) # Data(edge_index=[2, 899756], test_mask=[89250], train_mask=[89250], val_mask=[89250], x=[89250, 500], y=[89250])
# print("Total Num of nodes in dataset", data.num_nodes) # 89250
# print("Total Num of edges in dataset", data.num_edges) # 899756
# print("Total Num of node features in dataset", data.num_node_features) # 500
# print("Total Num of features in dataset", dataset.num_features) # same as node features # 500
# print("Num classes", dataset.num_classes) # 7
num_train_Train_per_class = 1500 # cos min of all classes only have 3k nodes
num_train_Shadow_per_class = 1500
num_test_Target = 10500
num_test_Shadow = 10500
# normal train test of target model. For comparing with distorted / the defensed method
if model_type == "GCN":
normal_test = 0.18
normal_precision = 0.871
normal_recall = 0.881
normal_auroc = 0.871
elif model_type == "GAT":
normal_test = 0.14
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif model_type == "SGC":
normal_test = 0.10
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
else:
normal_test = 0.20 #SAGE
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif data_type == "Cora":
###################################### Cora ##################################
path = global_path+"data/"+data_type #'/dstore/home/iyiola/Cora'
dataset = Planetoid(root=path, name="Cora", split="random") # set test to 1320 to match train
num_train_Train_per_class = 90 # 180
num_train_Shadow_per_class = 90
num_test_Target = 630
num_test_Shadow = 630
# normal train test of target model. For comparing with distorted / the defensed method
if model_type == "GCN":
normal_test = 0.84
normal_precision = 0.815
normal_recall = 0.812
normal_auroc = 0.811
elif model_type == "GAT":
normal_test = 0.83
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif model_type == "SGC":
normal_test = 0.84
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
else:
normal_test = 0.76 #SAGE
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif data_type == "CiteSeer":
###################################### CiteSeer ##################################
path = global_path+"data/"+data_type #'/dstore/home/iyiola/CiteSeer'
dataset = Planetoid(root=path, name="CiteSeer", split="random")
num_train_Train_per_class = 100
num_train_Shadow_per_class = 100
num_test_Target = 600
num_test_Shadow = 600
# normal train test of target model. For comparing with distorted / the defensed method
if model_type == "GCN":
normal_test = 0.75
normal_precision = 0.887
normal_recall = 0.879
normal_auroc = 0.879
elif model_type == "GAT":
normal_test = 0.73
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif model_type == "SGC":
normal_test = 0.74
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
else:
normal_test = 0.67 #SAGE
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif data_type == "PubMed":
###################################### PubMed ##################################
path = global_path + "data/" + data_type #'/dstore/home/iyiola/PubMed'
dataset = Planetoid(root=path, name="PubMed", split="random")
num_train_Train_per_class = 1500
num_train_Shadow_per_class = 1500
num_test_Target = 4500
num_test_Shadow = 4500
# normal train test of target model. For comparing with distorted / the defensed method
if model_type == "GCN":
normal_test = 0.80
normal_precision = 0.689
normal_recall = 0.678
normal_auroc = 0.678
elif model_type == "GAT":
normal_test = 0.76
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
elif model_type == "SGC":
normal_test = 0.78
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
else:
normal_test = 0.78 #SAGE
normal_precision = 0.
normal_recall = 0.
normal_auroc = 0.
else:
print("Error: No data specified")
data = dataset[0]
print("data", data)
'''
############################################# Target and Shadow Models ###############################################
'''
class TargetModel(torch.nn.Module):
def __init__(self, dataset):
super(TargetModel, self).__init__()
if model_type == "GCN":
# GCN
self.conv1 = GCNConv(dataset.num_node_features, target_num_neurons)
self.conv2 = GCNConv(target_num_neurons, dataset.num_classes)
elif model_type == "SAGE":
# GraphSage
# self.conv1 = SAGEConv(dataset.num_node_features, 256)
# self.conv2 = SAGEConv(256, dataset.num_classes)
# TODO SAGE
self.num_layers = 2
self.convs = torch.nn.ModuleList()
self.convs.append(SAGEConv(dataset.num_node_features, target_num_neurons))
self.convs.append(SAGEConv(target_num_neurons, dataset.num_classes))
elif model_type == "SGC":
# SGC
self.conv1 = SGConv(dataset.num_node_features, target_num_neurons, K=2, cached=False)
self.conv2 = SGConv(target_num_neurons, dataset.num_classes, K=2, cached=False)
elif model_type == "GAT":
# GAT
self.conv1 = GATConv(dataset.num_features, target_num_neurons, heads=8, dropout=0.1)
# On the Pubmed dataset, use heads=8 in conv2.
if data_type == "PubMed":
self.conv2 = GATConv(target_num_neurons * 8, dataset.num_classes, heads=8, concat=False)
# self.conv2 = GATConv(8 * 8, dataset.num_classes, heads=8, concat=False, dropout=0.1)
else:
self.conv2 = GATConv(target_num_neurons * 8, dataset.num_classes, heads=1, concat=False)
else:
print("Error: No model selected")
def forward(self, x, edge_index):
# print("xxxxxxx", x.size())
# TODO SAGE
if model_type == "SAGE":
all_node_and_neigbors = [] # {} # lookup table dictionary #changed to list cos it;s not possible to slice esp for TSTS TODO C
all_nodes = []
# the edge_index here is quite different (it is a list cos we will be passing train_loader). edge index is different based on batch data.
# Note edge_index here is a bipartite graph. meaning all the edges retured are connected
for i, (edge_ind, _, size) in enumerate(edge_index):
# print("iiiiiiiiiiiiiiii", i)
edges_raw = edge_ind.cpu().numpy()
# print("edges_raw", edges_raw)
edges = [(x, y) for x, y in zip(edges_raw[0, :], edges_raw[1, :])]
G = nx.Graph()
G.add_nodes_from(list(range(
data.num_nodes)))
G.add_edges_from(edges)
# getting the neigbors of a particular node.
for n in range(0, x.size(
0)):
all_nodes.append(n) # get all nodes
# all_node_and_neigbors[n] = [node for node in G.neighbors(n)] # set the value of the dict to the corresponding value if it has a neighbor else put empty list
all_node_and_neigbors.append((n, [node for node in G.neighbors(n)])) # TODO C
# print("n:", n, "neighbors:", [n for n in G.neighbors(n)]) # G.adj[n] # gets the neighbors of a particular n
x_target = x[:size[1]] # Target nodes are always placed first.
x = self.convs[i]((x, x_target), edge_ind)
if i != self.num_layers - 1:
x = F.relu(x)
# x = F.dropout(x, p=0.5, training=self.training)
# print("Final all nodes and neighbors", all_node_and_neigbors)
return x.log_softmax(dim=-1), all_node_and_neigbors
else:
edges_raw = edge_index.cpu().numpy()
# print("edges_raw", edges_raw)
edges = [(x, y) for x, y in zip(edges_raw[0, :], edges_raw[1, :])]
G = nx.Graph()
G.add_nodes_from(list(range(
data.num_nodes)))
G.add_edges_from(edges)
all_node_and_neigbors = [] # {} # lookup table list
all_nodes = []
for n in range(0, x.size(
0)):
all_nodes.append(n) # get all nodes
all_node_and_neigbors.append((n, [node for node in G.neighbors(n)])) #
x, edge_index = x, edge_index
x = self.conv1(x, edge_index)
x = F.relu(x)
# x = F.dropout(x, p=0.5, training=self.training)
# x = F.normalize(x, p=2, dim=-1)
x = self.conv2(x, edge_index)
# clip logits here and add noise
if isdp_logits:
x = clip_logits_norm(x, max_norm=max_norm_logits, norm_type=2, beta=beta, add_laplacian_noise=add_laplacian_to_logits,
add_gaussian_noise=add_gaussian_to_logits)
# x = F.relu(x)
# x = F.normalize(x, p=2, dim=-1)
return F.log_softmax(x, dim=1), all_node_and_neigbors
def inference(self, x_all):
for i in range(self.num_layers):
xs = []
all_node_and_neigbors = []
all_nodes = []
for batch_size, n_id, adj in all_graph_loader:
edge_index, _, size = adj.to(device)
x = x_all[n_id].to(device)
edges_raw = edge_index.cpu().numpy()
# print("edges_raw inference", edges_raw)
edges = [(x, y) for x, y in zip(edges_raw[0, :], edges_raw[1, :])]
G = nx.Graph()
G.add_nodes_from(list(range(
data.num_nodes)))
G.add_edges_from(edges)
for n in range(0, x.size(
0)):
all_nodes.append(n) # get all nodes
all_node_and_neigbors.append((n, [node for node in G.neighbors(n)]))
x_target = x[:size[1]]
x = self.convs[i]((x, x_target), edge_index)
if i != self.num_layers - 1:
x = F.relu(x)
xs.append(x.cpu())
x_all = torch.cat(xs, dim=0)
return F.log_softmax(x_all, dim=1), all_node_and_neigbors
class ShadowModel(torch.nn.Module):
def __init__(self, dataset):
super(ShadowModel, self).__init__()
if shadow_model_type == "GCN":
# GCN
self.conv1 = GCNConv(dataset.num_node_features, shadow_num_neurons)
self.conv2 = GCNConv(shadow_num_neurons, dataset.num_classes)
elif shadow_model_type == "SAGE":
# GraphSage
# self.conv1 = SAGEConv(dataset.num_node_features, 256)
# self.conv2 = SAGEConv(256, dataset.num_classes)
# TODO SAGE
self.num_layers = 2
self.convs = torch.nn.ModuleList()
self.convs.append(SAGEConv(dataset.num_node_features, shadow_num_neurons))
self.convs.append(SAGEConv(shadow_num_neurons, dataset.num_classes))
elif shadow_model_type == "SGC":
# SGC
self.conv1 = SGConv(dataset.num_node_features, shadow_num_neurons, K=2, cached=False)
self.conv2 = SGConv(shadow_num_neurons, dataset.num_classes, K=2, cached=False)
elif shadow_model_type == "GAT":
# GAT
self.conv1 = GATConv(dataset.num_features, shadow_num_neurons, heads=8, dropout=0.1)
# On the Pubmed dataset, use heads=8 in conv2.
if data_type == "PubMed":
self.conv2 = GATConv(shadow_num_neurons * 8, dataset.num_classes, heads=8, concat=False)
# self.conv2 = GATConv(8 * 8, dataset.num_classes, heads=8, concat=False, dropout=0.1)
else:
self.conv2 = GATConv(shadow_num_neurons * 8, dataset.num_classes, heads=1, concat=False)
else:
print("Error: No model selected")
def forward(self, x, edge_index):
# print("xxxxxxx", x.size())
if shadow_model_type == "SAGE":
all_node_and_neigbors = []
all_nodes = []
for i, (edge_ind, _, size) in enumerate(edge_index):
# print("iiiiiiiiiiiiiiii", i)
edges_raw = edge_ind.cpu().numpy()
# print("edges_raw", edges_raw)
edges = [(x, y) for x, y in zip(edges_raw[0, :], edges_raw[1, :])]
G = nx.Graph()
G.add_nodes_from(list(range(
data.num_nodes)))
G.add_edges_from(edges)
for n in range(0, x.size(
0)):
all_nodes.append(n) # get all nodes
all_node_and_neigbors.append((n, [node for node in G.neighbors(n)])) # TODO C
x_shadow = x[:size[1]] # Shadow nodes are always placed first.
x = self.convs[i]((x, x_shadow), edge_ind)
if i != self.num_layers - 1:
x = F.relu(x)
# x = F.dropout(x, p=0.5, training=self.training)
# print("Final all nodes and neighbors", all_node_and_neigbors)
return x.log_softmax(dim=-1), all_node_and_neigbors
else:
edges_raw = edge_index.cpu().numpy()
# print("edges_raw", edges_raw)
edges = [(x, y) for x, y in zip(edges_raw[0, :], edges_raw[1, :])]
G = nx.Graph()
G.add_nodes_from(list(range(
data.num_nodes)))
G.add_edges_from(edges)
all_node_and_neigbors = []
all_nodes = []
for n in range(0, x.size(
0)):
all_nodes.append(n)
all_node_and_neigbors.append((n, [node for node in G.neighbors(n)]))
x, edge_index = x, edge_index
x = self.conv1(x, edge_index)
x = F.relu(x)
# x = F.dropout(x, p=0.5, training=self.training)
# x = F.normalize(x, p=2, dim=-1)
x = self.conv2(x, edge_index)
# x = F.relu(x)
# x = F.normalize(x, p=2, dim=-1)
return F.log_softmax(x, dim=1), all_node_and_neigbors
def inference(self, x_all):
for i in range(self.num_layers):
xs = []
all_node_and_neigbors = []
all_nodes = []
for batch_size, n_id, adj in all_graph_loader:
edge_index, _, size = adj.to(device)
x = x_all[n_id].to(device)
edges_raw = edge_index.cpu().numpy()
# print("edges_raw inference", edges_raw)
edges = [(x, y) for x, y in zip(edges_raw[0, :], edges_raw[1, :])]
G = nx.Graph()
G.add_nodes_from(list(range(
data.num_nodes)))
G.add_edges_from(edges)
for n in range(0, x.size(
0)):
all_nodes.append(n)
all_node_and_neigbors.append((n, [node for node in G.neighbors(n)]))
x_shadow = x[:size[1]]
x = self.convs[i]((x, x_shadow), edge_index)
if i != self.num_layers - 1:
x = F.relu(x)
xs.append(x.cpu())
x_all = torch.cat(xs, dim=0)
return F.log_softmax(x_all, dim=1), all_node_and_neigbors
'''
##################################### Data Processing Inductive Split ######################################
'''
def get_inductive_spilt(data, num_classes, num_train_Train_per_class, num_train_Shadow_per_class, num_test_Target,
num_test_Shadow):
# -----------------------------------------------------------------------
# target_train, target_out
# shadow_train, shadow_out
'''
Randomly choose 'num_train_Train_per_class' and 'num_train_Shadow_per_class' per classes for training Target and shadow models respectively
Random choose 'num_test_Target' and 'num_test_Shadow' for testing (out data) Target and shadow models respectively
'''
st_time = time.time()
# convert all label to list
label_idx = data.y.numpy().tolist()
print("label_idx", len(label_idx))
if os.path.isfile(global_path + "/target_train_idx" + mode + "_" + data_type + "_" + str(rand_state)+ ".pt"):
target_train_idx = torch.load(global_path + "/target_train_idx" + mode + "_" + data_type + "_" + str(rand_state)+ ".pt")
shadow_train_idx = torch.load(global_path + "/shadow_train_idx" + mode + "_" + data_type + "_" + str(rand_state)+ ".pt")
target_test_idx = torch.load(global_path + "/target_test_idx" + mode + "_" + data_type + "_" + str(rand_state)+ ".pt")
shadow_test_idx = torch.load(global_path + "/shadow_test_idx" + mode + "_" + data_type + "_" + str(rand_state)+ ".pt")
else:
target_train_idx = []
shadow_train_idx = []