-
Notifications
You must be signed in to change notification settings - Fork 4
/
PrivBayes_COARSE(Processes).py
2255 lines (1668 loc) · 84.1 KB
/
PrivBayes_COARSE(Processes).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 warnings
warnings.simplefilter(action='ignore', category=FutureWarning)
warnings.filterwarnings("ignore")
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import tensorflow as tf
import logging
tf.get_logger().setLevel(logging.ERROR)
from scipy import special as sp
from sklearn.metrics import accuracy_score
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
from sklearn.neural_network import MLPClassifier
from sklearn.svm import LinearSVC
import numpy as np
import csv
import itertools
import random as rd
import networkx as nx
import math
import xgboost as xgb
from multiprocessing import Process, Lock, RLock
import sys
import time
import multiprocessing
import gc
import pickle
def GetSubsets(attr_set,k,choice):
if (choice == 0): # Get all possible subsets A' (with size k + 1) of the attribute set A
List = (list(itertools.combinations(attr_set,k+1)))
else: # Get all possible subsets A' (with size less than or equal to k) of the attribute set A
List = []
for i in range (1,k+1):
List = List + (list(itertools.combinations(attr_set,i)))
return List
def normalize(List): # Normalize to [0,1]
total_sum = sum(List)
if (total_sum != 0):
List = [(x/total_sum) for x in List]
return List
def GetCounts(Attributes,Dataset,dA_sub,Attribute_dict,AddNoise,StrL,epsilon,k): # This is a function that each user runs on his own dataset from a dataset (returns counts cA of dataset)
NumOfAttrs = len(Attributes)
if (AddNoise):
if(StrL == 2):
e_2 = epsilon
mu = 0
b = 2*NumOfAttrs/(e_2)
elif (StrL == 1):
mu = 0
b = (2*sp.comb(NumOfAttrs,k + 1,exact='True'))/epsilon
else:
mu = 1
b = 1
Counts = [0 for i in range(0,len(dA_sub))]
Indexes = [Attribute_dict[attr] for attr in Attributes]
noise = []
Ai_Dataset_Columns = Dataset[:, Indexes]
del Indexes
gc.collect()
for row in Ai_Dataset_Columns:
i = 0
for attr_values in dA_sub:
if (list(row) == list(attr_values)):
Counts[i] = Counts[i] + 1
break
i = i + 1
if (AddNoise):
noise = np.random.laplace(loc=mu,scale=b,size=len(dA_sub)).tolist()
noise = [round(x) for x in noise] # noise must be integers
noise = [0 if (x<0) else x for x in noise] # noise must be >=0
Counts = AddListsOfNumbers(Counts,noise) # Add noise to count to ensure ε-differential privacy
Counts = [round(x) for x in Counts] # counts must be integers
Counts = [0 if (x<0) else x for x in Counts] # counts must be >=0
return Counts,sum(noise)
def AddListsOfNumbers(List1,List2):
if (len(List1) == len(List2)):
Result = [0 for i in range(0,len(List1))]
for i in range(0,len(List1)): # Sum counts of each dataset to find cAi to calculate the probability (Line 5)
Result[i] = List1[i] + List2[i]
return Result
else:
print("Error!! The lists must have the same length !!")
def AttrDomProd(Attributes,Attr_domains): # Calculate dA_sub' for current A'
Needed_Attr_domains = [Attr_domains[attr] for attr in Attributes]
dA_sub = list(itertools.product(*Needed_Attr_domains)) # We construct the arbitrary ordered dA_sub
return dA_sub
def unique(list1):
# insert the list to the set
list_set = set(list1)
# convert the set to the list
unique_list = (list(list_set))
return unique_list
def CalculateProbabilities(A,Attr_domains,All_Probabilities,k,Child_Parents):
#print("Child_Parents are",Child_Parents)
New_Probabilities = {} # Of k-sized or less attr comb
Up_to_k_sized_attr_combinations = GetSubsets(A,k,1)
'''
else: # We want only those to calculate the cond_probs joint and marginal probabilities
Up_to_k_sized_attr_combinations = GetSubsets(A,1,1) # We want all the marginal probabilities P(A) of the attributes
for child,parents in Child_Parents.items():
if (len(parents) >= 1): # We dont want the empty set that is the parent set of the starting attribute or to re add marginal probabilities
Up_to_k_sized_attr_combinations.append(tuple(parents)) # We want all the joint probabilities of the parents ONLY of the attributes
print("[child] + parents are",[child] + parents)
if (len ([child] + parents) < k) and (len ([child] + parents) > 1):
Up_to_k_sized_attr_combinations.append(tuple([child] + parents))
'''
#print ("Up_to_k_sized_attr_combinations are ",Up_to_k_sized_attr_combinations)
for attr_comb in Up_to_k_sized_attr_combinations:
Needed_Attr_domains = [Attr_domains[attr] for attr in attr_comb]
current_attrs_tuples = list(itertools.product(*Needed_Attr_domains))
for cnt in range(0,len(current_attrs_tuples)):
pairs = [(attr_comb[i],current_attrs_tuples[cnt][i]) for i in range(0,len(attr_comb))]
New_Probabilities[frozenset(pairs)] = 0
del Up_to_k_sized_attr_combinations
gc.collect()
#print ("New Probabilites are: ",New_Probabilities)
# Calculate the probabilities for all combinations with size less or equal to k
for Small_dist in New_Probabilities:
for key1 in All_Probabilities:
if (Small_dist.issubset(key1)):
Larg_dist = key1
#print("\nLarger Distribution is ", Larg_dist)
#print("Current distribution is ", Small_dist)
# If we want P(Class = 0) and the distribution we will use to find it is (Sex,Class = 0 , Pain) then atrr_to_add = [Sex,Pain],attr_to_find = [Class]
attr_to_add = [x[0] for x in Larg_dist]
attr_to_find = [x[0] for x in Small_dist]
#print(attr_to_add)
#print(attr_to_find)
attr_to_add = (list(set(attr_to_add) - set(attr_to_find)))
#print(attr_to_add)
subset = list(Small_dist) # It must contain the attributes and values of the probability we wish to calculate
Value_combs = FindFrozenSets(attr_to_add,Attr_domains,subset)
for comb in Value_combs:
New_Probabilities[Small_dist] = All_Probabilities[comb] + New_Probabilities[Small_dist]
break
return New_Probabilities
def FindFrozenSets(Attrs_for_sets,Attr_domains,List_to_include):
Value_combs = [] # List of frozensets e.g frozen set = frozenset({('Sex', 1), ('Pain', 0), ('Class', 0)})
Needed_Attr_domains = [Attr_domains[attr] for attr in Attrs_for_sets]
current_attrs_tuples = list(itertools.product(*Needed_Attr_domains))
for cnt in range(0,len(current_attrs_tuples)):
pairs = [(Attrs_for_sets[i],current_attrs_tuples[cnt][i]) for i in range(0,len(Attrs_for_sets))]
if (len(List_to_include) != 0):
Value_combs.append(frozenset(pairs + List_to_include))
else:
Value_combs.append(frozenset(pairs))
return Value_combs
def CalculateMutualInformation(X,Pa,Probabilities,Attr_domains): # I(X,Pa)
# Create the needed frozen sets to use as keys
X_sets = FindFrozenSets(X,Attr_domains,[])
#print(Pa)
Pa_sets = FindFrozenSets(list(Pa),Attr_domains,[])
X_Pa_sets = FindFrozenSets(X + list(Pa),Attr_domains,[])
'''
print("X_sets")
for i in X_sets:
print(i,Probabilities[i])
print("\nPa_sets")
for i in Pa_sets:
print(i,Probabilities[i])
print("\nX_Pa_sets")
for i in X_Pa_sets:
print(i,Probabilities[i])
'''
MutualInf = 0
for x in X_sets:
px = Probabilities[x]
if (px == 0):
continue
else:
for pa in Pa_sets:
p_pa = Probabilities[pa]
p_x_pa = Probabilities[frozenset(list(x) + list(pa))]
try:
MutualInf = p_x_pa * math.log(p_x_pa/(px*p_pa),2) + MutualInf
except:
continue
#print ("I(", X ,",", Pa,") = " + str(MutualInf))
#print()
return MutualInf
def isBinary(attr_list,Attr_domains):
for attr in attr_list:
if (len(Attr_domains[attr]) != 2):
return False
return False
def CalcSensitivity(x,n,Attr_domains):
if (isBinary([x[0]],Attr_domains)) or ((isBinary(x[1],Attr_domains)) and (len(x[1]) == 1)): # We must have ONE parent and either the child or the parent (or both) must binary
Delta_I = ((1/n) * math.log(n,2)) + (((n-1)/n) * math.log(n/(n-1),2))
else:
Delta_I = ((2/n) * math.log((n+1)/2,2)) + (((n-1)/n) * math.log((n+1)/(n-1),2))
return Delta_I
def NoiseChoice(Str_to_print):
choice = int(input("Add noise? (0 for No, 1 for Yes): "))
while (choice < 0) or (choice > 1) or (not isinstance(choice,int)):
choice = int(input("Add noise? (0 for No, 1 for Yes): "))
if (choice == 1):
epsilon = float(input(Str_to_print))
while (epsilon <= 0) or (not isinstance(epsilon,float)):
epsilon = float(input(Str_to_print))
AddNoise = True
else:
epsilon = 0
AddNoise = False
return AddNoise,epsilon
def ExponentialMechanism(List,Attr_domains,n,epsilon_1,N): # The list contains tuples (X,Pa,I(X,Pa)), Returns diction with list elements as keys and probability as element
ExpProbs = []
for x in List:
Delta_I = CalcSensitivity(x,n,Attr_domains)
I = x[2]
ExpProbs.append(math.exp((I*epsilon_1)/(2*(N-1)*Delta_I)))
ExpProbs = normalize(ExpProbs)
#print("ExpProbs are",ExpProbs)
rand_choice = rd.random()
low_bound = 0
high_bound = 0
choice = 0
for i in range(0,len(ExpProbs)):
low_bound = high_bound
high_bound = low_bound + ExpProbs[i]
if (rand_choice >= low_bound) and (rand_choice < high_bound):
choice = i
#print ("Chosen Pair (X,Pa,I) =",List[choice])
#print()
return List[choice]
def GetVotes(Dataset,A,k,Attr_domains,V,Datasets_Probabilities,Dataset_idx,AddNoise,epsilon_1): # This is a function that each user runs on his own dataset (Returns Child,Parent pair with the highest mutual information)
# Calculate the needed probabilities (Ths must be done by every user separately and privately, only once)
# Normally the dataset probabilities should only exist in this function. However, we define it in main() to access it more easily and to avoid redundant calculations
# (calculating the same probabilities again and again) but the analyst does NOT know them
if (Datasets_Probabilities[Dataset_idx] == 0): # We need to calculate the probabilities
Attribute_dict = {A[i] : i for i in range (0,len(A))}
A_subs = GetSubsets(A,k,0) # Creating A' sets
#print("A_subs are",A_subs)
# Calculate the probabilities
A_sub_probabilities = {} # {Ai',[ probabilities of tuples in dAi'_sub ]}
dA_sub_all = {} # {Ai',dA_sub}
for A_sub in A_subs: # Sharing the Noisy Sufficient Statistics line 2
#print ("\n#################### {} : ####################".format(A_sub))
dA_sub = AttrDomProd (A_sub,Attr_domains)
dA_sub_all[A_sub] = dA_sub
#print("dA_sub' = ",dA_sub)
#print()
All_A_sub_counts = {} # {Ai',[ counts of tuples in in dAi'_sub ]}
All_A_sub_counts[A_sub] = [0 for i in range(0,len(dA_sub))]
## WE DONT USE LAPLACE BUT EXPONENTIAL HERE
#print ("================== Dataset {} : ====================".format(i + 1))
A_sub_count,Total_Noise = GetCounts(A_sub,Dataset,dA_sub,Attribute_dict,False,2,0,k) # Sharing the Noisy Sufficient Statistics line 4 - cAi' ^ (j)
#print (A_sub_count)
All_A_sub_counts[A_sub] = AddListsOfNumbers(All_A_sub_counts[A_sub],A_sub_count) # Sum counts of each dataset to find cAi to calculate the probability (Line 5)
#print(sum(All_A_sub_counts[A_sub]))
# Calculate probability PΑi for each Ai (Line 5)
A_sub_probabilities[A_sub] = [All_A_sub_counts[A_sub][i]/len(Dataset) for i in range(0,len(dA_sub))]
# Line 6
del Attribute_dict
del A_subs
del All_A_sub_counts
gc.collect()
Datasets_Probabilities[Dataset_idx] = {} # e.g {frozenset(((A,0),(B,0))) : 0} = P(A = 0, B = 0) = 0
for key in dA_sub_all.keys():
for cnt in range(0,len(dA_sub_all[key])):
pairs = [(key[i],dA_sub_all[key][cnt][i]) for i in range(0,len(key))]
Datasets_Probabilities[Dataset_idx] [frozenset(pairs)] = A_sub_probabilities[key][cnt]
del dA_sub_all
gc.collect()
Datasets_Probabilities[Dataset_idx].update(CalculateProbabilities(A,Attr_domains,Datasets_Probabilities[Dataset_idx],k,[]))
#print ("\nJoint Probabilities for all distributions are:\n")
#for values,probability in Datasets_Probabilities[Dataset_idx].items():
#print("P(", sorted(list(values)), ") = ",round(probability,3))
All_Probabilities = Datasets_Probabilities[Dataset_idx]
tuple_with_max_I = (0,0,0)
Omega = []
NumOfAttributes = len(A)
Parents = GetSubsets(V,k,1) # Pa(X) such as |Pa(X)| <= k
if (NumOfAttributes != len(V)):
for x in A :
if (x in V): # A \ V
continue
else:
#print("Parents are :",Parents)
#print(" =============== ")
for Pa in Parents: # Line 12 - 13
I = CalculateMutualInformation([x],Pa,All_Probabilities,Attr_domains)
tupl = (x,Pa,I)
Omega.append(tupl) # Line 13
# Choose which I to return using the exponential mechanism (Line 12 of ALg 3.2)
if (AddNoise):
tuple_with_max_I = ExponentialMechanism(Omega,Attr_domains,len(Dataset),epsilon_1,NumOfAttributes)
else:
tuple_with_max_I = Omega[0]
for item in Omega:
if (item[2] > tuple_with_max_I[2]):
tuple_with_max_I = item
#if (final_max_tuple[2] < tuple_with_max_I[2]): # REDUNDANT
#final_max_tuple = tuple_with_max_I[:]
return tuple_with_max_I
def StructureLearning1(Datasets,k,A,Attr_domains,Dataset_size,AddNoise,epsilon):
V = []
Attribute_dict = {A[i] : i for i in range (0,len(A))}
A_subs = GetSubsets(A,k,0) # Creating A' sets
#print("A_subs are",A_subs)
M = len(Datasets) # Num of users
# Calculate the probabilities
A_sub_probabilities = {} # {Ai',[ probabilities of tuples in dAi'_sub ]}
dA_sub_all = {} # {Ai',dA_sub}
New_Dataset_Size = Dataset_size
for A_sub in A_subs: # Sharing the Noisy Sufficient Statistics line 2
New_Dataset_Size = Dataset_size
#print ("\n#################### {} : ####################".format(A_sub))
dA_sub = AttrDomProd (A_sub,Attr_domains)
dA_sub_all[A_sub] = dA_sub
#print("dA_sub' = ",dA_sub)
#print()
All_A_sub_counts = {} # {Ai',[ counts of tuples in in dAi'_sub ]}
All_A_sub_counts[A_sub] = [0 for i in range(0,len(dA_sub))]
for i in range(0,M): # For every dataset
#print ("================== Dataset {} : ====================".format(i + 1))
A_sub_count, Total_Noise = GetCounts(A_sub,Datasets[i],dA_sub,Attribute_dict,AddNoise,1,epsilon,k) # Sharing the Noisy Sufficient Statistics line 4 - cAi' ^ (j)
#print (A_sub_count)
New_Dataset_Size = New_Dataset_Size + Total_Noise
#print (A_sub_count)
All_A_sub_counts[A_sub] = AddListsOfNumbers(All_A_sub_counts[A_sub],A_sub_count) # Sum counts of each dataset to find cAi to calculate the probability (Line 5)
#print(sum(All_A_sub_counts[A_sub]))
A_sub_probabilities[A_sub] = []
# Calculate probability PΑi for each Ai (Line 5)
for i in range(0,len(dA_sub)):
if (not AddNoise):
A_sub_probabilities[A_sub].append(All_A_sub_counts[A_sub][i]/Dataset_size)
else:
try:
A_sub_probabilities[A_sub].append(All_A_sub_counts[A_sub][i]/New_Dataset_Size)
except:
print("Dataset size is :",Dataset_size)
print("New Dataset size is :",New_Dataset_Size)
del All_A_sub_counts
gc.collect()
#print()
#for x in A_sub_probabilities.keys():
#print ("Attributes: ", x, "\nCombinations: ", dA_sub_all[x])
#print ("Probabilities: ", A_sub_probabilities[x] , "\n=======================================")
# Line 6
choice = rd.randint(0,len(A) - 1)
chosen_attr = A[choice]
first_chosen_attr = chosen_attr
#print ("\nStarting node: ", first_chosen_attr)
All_Probabilities = {} # e.g {frozenset(((A,0),(B,0))) : 0} = P(A = 0, B = 0) = 0
for key in dA_sub_all.keys():
for cnt in range(0,len(dA_sub_all[key])):
pairs = [(key[i],dA_sub_all[key][cnt][i]) for i in range(0,len(key))]
All_Probabilities[frozenset(pairs)] = A_sub_probabilities[key][cnt]
del dA_sub_all
del A_sub_probabilities
gc.collect()
#print ("Joint Probabilities for k+1 distributions are:\n")
#for values,probability in All_Probabilities.items():
#print("P(", list(values), ") = ",round(probability,2))
All_Probabilities.update(CalculateProbabilities(A,Attr_domains,All_Probabilities,k,[]))
#print ("\nJoint Probabilities for all distributions are:\n")
#for values,probability in All_Probabilities.items():
#print("P(", sorted(list(values)), ") = ",round(probability,3))
# Line 7
Gen_BN = nx.DiGraph()
Gen_BN.add_node(chosen_attr)
V.append(chosen_attr)
A.remove(chosen_attr) # A \ V
for i in range (0,len(A)):
Omega = []
#print()
#print("A \ V is :",A)
#print("V is :",V)
#print()
for x in A :
Parents = GetSubsets(V,k,1) # Pa(X) such as |Pa(X)| <= k
for Pa in Parents: # Line 12 - 13
I = CalculateMutualInformation([x],Pa,All_Probabilities,Attr_domains)
tupl = (x,Pa,I)
Omega.append(tupl) # Line 13
# Line 14
tuple_with_max_I = Omega[0]
for item in Omega:
if (item[2] > tuple_with_max_I[2]):
tuple_with_max_I = item
# Line 15
A.remove(tuple_with_max_I[0]) # A \ V
V.append(tuple_with_max_I[0])
if (not Gen_BN.has_node(chosen_attr)):
Gen_BN.add_node(chosen_attr)
for attr in tuple_with_max_I[1]:
if (not Gen_BN.has_node(attr)):
Gen_BN.add_node(attr)
Gen_BN.add_edge(attr,tuple_with_max_I[0])
#print("\nGenerated Bayesian Network is : ")
#for i in Gen_BN.edges():
#print (i[0] + " ----> " + i[1])
#print()
return Gen_BN,All_Probabilities,first_chosen_attr
def StructureLearning2(Datasets,k,A,Attr_domains,AddNoise,epsilon):
Datasets_Probabilities = {i:0 for i in range(0,len(Datasets))} # {Dataset Index:Dictionary that contains its joint probabilities}
# Line 1,2
choice = rd.randint(0,len(A) - 1)
first_chosen_attr = A[choice]
#print ("\nStarting node: ", first_chosen_attr)
V = []
Gen_BN = nx.DiGraph()
Gen_BN.add_node(first_chosen_attr)
mu = 0
b = 0
e_1 = 0
V.append(first_chosen_attr)
#print("Starting attribute is",first_chosen_attr)
# Determine noise
if (AddNoise):
e_1 = epsilon
# Line 5 - 7
for i in range(0,len(A)):
Votes = {}
for j in range(0,len(Datasets)):
#print("\nDataset " + str(j))
#print()
Max_I_Pair = GetVotes(Datasets[j],A[:],k,Attr_domains,V,Datasets_Probabilities,j,AddNoise,e_1)
#print("A is ", A)
#print("V is ", V)
Max_I_Pair = (Max_I_Pair[0],Max_I_Pair[1])
if (Max_I_Pair in Votes.keys()):
Votes[Max_I_Pair] = Votes[Max_I_Pair] + 1
else:
Votes[Max_I_Pair] = 1
if (i == 0):
'''
print("The probabilities of the datasets are")
for j in range(0,len(Datasets)):
print("Dataset " + str(j))
for values,probability in Datasets_Probabilities[j].items():
print("P(", sorted(list(values)), ") = ",round(probability,3))
'''
#print("\nThe votes for each value of i are: \n")
# Line 8
max_votes = 0
max_pair = 0
for key,votes in Votes.items():
if (votes > max_votes):
max_votes = votes
max_pair = key
if (votes == max_votes):
if (rd.random() > 0.5): # Arbitrarily break ties
max_votes = votes
max_pair = key
# Line 9
if (i != len(A) - 1):
#print("Votes " + str(i) + " are ",Votes)
if (max_pair[0] in V):
pass
else:
V.append(max_pair[0])
#print("Max pair is :",max_pair,"from Votes " + str(i))
#print()
for attr in max_pair[1]:
if (not Gen_BN.has_node(attr)):
Gen_BN.add_node(attr)
Gen_BN.add_edge(attr,max_pair[0])
del Datasets_Probabilities
gc.collect()
#print("\nGenerated Bayesian Network is : ")
#for i in Gen_BN.edges():
#print (i[0] + " ----> " + i[1])
#print()
return Gen_BN,first_chosen_attr
def GreedyBayes(dataset,NumOfAttrs,A,k,Attr_domains,AddNoise1,epsilon1):
Attribute_dict = {A[i] : i for i in range (0,len(A))}
A_subs = GetSubsets(A,k,0) # Creating A' sets
#print("A_subs are",A_subs)
# Calculate the probabilities
A_sub_probabilities = {} # {Ai',[ probabilities of tuples in dAi'_sub ]}
dA_sub_all = {} # {Ai',dA_sub}
Dataset_size = len(dataset)
for A_sub in A_subs:
#print ("\n#################### {} : ####################".format(A_sub))
dA_sub = AttrDomProd (A_sub,Attr_domains)
dA_sub_all[A_sub] = dA_sub
#print("dA_sub' = ",dA_sub)
#print()
All_A_sub_counts = {} # {Ai',[ counts of tuples in in dAi'_sub ]}
All_A_sub_counts[A_sub] = [0 for i in range(0,len(dA_sub))]
#print ("================== Dataset {} : ====================".format(i + 1))
A_sub_count, Total_Noise = GetCounts(A_sub,dataset,dA_sub,Attribute_dict,False,1,0,k) # Sharing the Noisy Sufficient Statistics line 4 - cAi' ^ (j)
#print (A_sub_count)
All_A_sub_counts[A_sub] = AddListsOfNumbers(All_A_sub_counts[A_sub],A_sub_count) # Sum counts of each dataset to find cAi to calculate the probability (Line 5)
#print(sum(All_A_sub_counts[A_sub]))
A_sub_probabilities[A_sub] = []
# Calculate probability PΑi for each Ai (Line 5)
for i in range(0,len(dA_sub)):
A_sub_probabilities[A_sub].append(All_A_sub_counts[A_sub][i]/Dataset_size)
#print()
#for x in A_sub_probabilities.keys():
#print ("Attributes: ", x, "\nCombinations: ", dA_sub_all[x])
#print ("Probabilities: ", A_sub_probabilities[x] , "\n=======================================")
del Attribute_dict
del A_subs
del All_A_sub_counts
gc.collect()
All_Probabilities = {} # e.g {frozenset(((A,0),(B,0))) : 0} = P(A = 0, B = 0) = 0
for key in dA_sub_all.keys():
for cnt in range(0,len(dA_sub_all[key])):
pairs = [(key[i],dA_sub_all[key][cnt][i]) for i in range(0,len(key))]
All_Probabilities[frozenset(pairs)] = A_sub_probabilities[key][cnt]
del A_sub_probabilities
gc.collect()
#print ("Joint Probabilities for k+1 distributions are:\n")
#for values,probability in All_Probabilities.items():
#print("P(", list(values), ") = ",round(probability,2))
All_Probabilities.update(CalculateProbabilities(A,Attr_domains,All_Probabilities,k,[]))
# Build the Bayesian Network
V = []
choice = rd.randint(0,NumOfAttrs - 1)
chosen_attr = A[choice]
first_chosen_attr = chosen_attr
Gen_BN = nx.DiGraph()
Gen_BN.add_node(chosen_attr)
V.append(chosen_attr)
Parents = GetSubsets(V,k,1) # Pa(X) such as |Pa(X)| <= k
A.remove(chosen_attr) # A \ V
for i in range (0,NumOfAttrs):
Omega = []
#print(A)
#print(V)
if (len(A) == 0):
break
for x in A :
#print(Parents)
for Pa in Parents: # Line 12 - 13
I = CalculateMutualInformation([x],Pa,All_Probabilities,Attr_domains)
tupl = (x,Pa,I)
Omega.append(tupl) # Line 13
if (AddNoise1):
tuple_with_max_I = ExponentialMechanism(Omega,Attr_domains,len(dataset),epsilon1,NumOfAttrs)
else:
tuple_with_max_I = Omega[0]
for item in Omega:
if (item[2] > tuple_with_max_I[2]):
tuple_with_max_I = item
# Line 15
A.remove(tuple_with_max_I[0]) # A \ V
V.append(tuple_with_max_I[0])
Parents = GetSubsets(V,k,1) # Pa(X) such as |Pa(X)| <= k
if (not Gen_BN.has_node(chosen_attr)):
Gen_BN.add_node(chosen_attr)
for attr in tuple_with_max_I[1]:
if (not Gen_BN.has_node(attr)):
Gen_BN.add_node(attr)
Gen_BN.add_edge(attr,tuple_with_max_I[0])
return Gen_BN,All_Probabilities,first_chosen_attr
def NoisyConditionals(k,NumOfAttrs,Joint_Probabilities,epsilon,Dataset_size): ## Add noise to Joint probabilities
mu = 0
b = (4 * (NumOfAttrs - k)) / (Dataset_size * epsilon)
Attr_keys = []
# Add Laplace noise to every probability
for key in Joint_Probabilities.keys():
Joint_Probabilities[key] = Joint_Probabilities[key] + np.random.laplace(loc=mu,scale=b,size=1).tolist()[0]
attrs = [pair[0] for pair in list(key)]
Attr_keys.append(frozenset(attrs))
if (Joint_Probabilities[key] < 0): # If less than zero, make zero
Joint_Probabilities[key] = 0
Attr_keys = set(Attr_keys)
#print(Attr_keys)
# Normalize the probabilities
for attr_key in Attr_keys:
prob_sum = 0
for key in Joint_Probabilities.keys(): # Calculate the sum of probabilities
attrs = frozenset([pair[0] for pair in list(key)])
if (attr_key == attrs):
prob_sum = Joint_Probabilities[key] + prob_sum
for key in Joint_Probabilities.keys(): # Normalize them
attrs = frozenset([pair[0] for pair in list(key)])
if (attr_key == attrs):
if (prob_sum !=0):
Joint_Probabilities[key] = Joint_Probabilities[key]/prob_sum
return Joint_Probabilities
def SharingNoisyModel(Datasets,k,A,Attr_domains,AddNoise1,epsilon1,AddNoise2,epsilon2,Iter_cnt):
CompleteDataset = []
NumOfAttrs = len(A)
cnt = 1
for dataset in Datasets:
G, Joint_Probabilities , starting_attr = GreedyBayes(dataset,NumOfAttrs,A[:],k,Attr_domains,AddNoise1,epsilon1)
Child_Parents = {x:[] for x in A}
#plt.show()
logging.info("First Phase (Structure Learning) is complete!!")
# Second Phase of PrivBayes: Parameter Learning
for edge in G.edges():
Child_Parents[edge[1]].append(edge[0])
# Add noise to Joint Probabilities
if(AddNoise2):
Joint_Probabilities = NoisyConditionals(k,NumOfAttrs,Joint_Probabilities,epsilon2,len(dataset))
#print(Joint_Probabilities)
Conditional_Probabilities = ParameterLearning(Joint_Probabilities,Child_Parents,Attr_domains)
if (AddNoise2): # If we added noise, normalize conditional probabilites
for key in Conditional_Probabilities.keys():
for pair in key: # Get the parent part of this conditional probability
if (pair[0] == 'Parents'):
parents = pair[1]
break
# Get the all the combinations of values that this set of parents can give
Parents_combs = FindFrozenSets(list(parents),Attr_domains,[])
#print("Parents_combs",Parents_combs)
for comb in Parents_combs:
prob_sum = 0
for attr_comb in Conditional_Probabilities[key].keys(): # Sum all cond probabilities where parents have same values and then divide those probs by the sum
if (comb.issubset(attr_comb)):
if (Conditional_Probabilities[key][attr_comb] != math.inf):
prob_sum = Conditional_Probabilities[key][attr_comb] + prob_sum
for attr_comb in Conditional_Probabilities[key].keys(): # Sum all cond probabilities where parents have same values and then divide those probs by the sum
if (frozenset(comb).issubset(attr_comb)):
if (Conditional_Probabilities[key][attr_comb] != math.inf):
#print(prob_sum)
if (prob_sum != 0):
Conditional_Probabilities[key][attr_comb] = Conditional_Probabilities[key][attr_comb] / prob_sum
#print("Changed prob:",key,attr_comb,Conditional_Probabilities[key][attr_comb])
#print("Parameter Learning is complete! (" + str(multiprocessing.current_process()) + ")")
'''
print ("\nConditional Probabilities for the generated Bayesian Network are:")
for child_parents,value_probabilites in Conditional_Probabilities.items():
print("\nP(", child_parents , ") : ")
for key,prob in value_probabilites.items():
if (prob != math.inf):
print ("\t","P",sorted(key)," = ",round(prob,3))
else:
print ("\t","P",sorted(key)," = NOT DEFINED")
'''
SizeOfSynthDataset = len(dataset)
Synth_Dataset = PriorSampling(G,Conditional_Probabilities,SizeOfSynthDataset,Child_Parents,Attr_domains)
CompleteDataset = CompleteDataset + Synth_Dataset
FinalSynthDataset = []
for i in range(0,len(CompleteDataset)):
tuple = []
for attr in A:
tuple.append(CompleteDataset[i][attr])
FinalSynthDataset.append(tuple)
return np.array(FinalSynthDataset).astype('float')
def GetProbabilities(Child_Parents,Datasets,Dataset_size,NumOfAttrs,k,Attr_domains,A,AddNoise,epsilon): # If we choose StrLearning2, so retireved = False, use this to get (noisy) joint probabilities
'''
Joint_Prob_Combs = []
for child,parents in Child_Parents.items():
temp_list = []
temp_list.append(child)
temp_list = temp_list + parents
Joint_Prob_Combs.append(frozenset(temp_list))
#print("Joint_Prob_Combs are ",Joint_Prob_Combs)
'''
Attribute_dict = {A[i] : i for i in range (0,len(A))}
A_subs = GetSubsets(A,k,0) # Creating A' sets
M = len(Datasets) # Num of users
# Calculate the probabilities
A_sub_probabilities = {} # {Ai',[ probabilities of tuples in dAi'_sub ]}
dA_sub_all = {} # {Ai',dA_sub}
for A_sub in A_subs:
New_Dataset_Size = Dataset_size
dA_sub = AttrDomProd (A_sub,Attr_domains)
dA_sub_all[A_sub] = dA_sub
#print("dA_sub' = ",dA_sub)
#print()
All_A_sub_counts = {} # {Ai',[ counts of tuples in in dAi'_sub ]}
All_A_sub_counts[A_sub] = [0 for i in range(0,len(dA_sub))]
for i in range(0,M):
#print ("================== Dataset {} : ====================".format(i + 1))
A_sub_count,Total_Noise = GetCounts(A_sub,Datasets[i],dA_sub,Attribute_dict,AddNoise,2,epsilon,k) # Sharing the Noisy Sufficient Statistics line 4 - cAi' ^ (j)
New_Dataset_Size = New_Dataset_Size + Total_Noise
#print (A_sub_count)
All_A_sub_counts[A_sub] = AddListsOfNumbers(All_A_sub_counts[A_sub],A_sub_count) # Sum counts of each dataset to find cAi to calculate the probability (Line 5)
#print(sum(All_A_sub_counts[A_sub]))
A_sub_probabilities[A_sub] = []
# Calculate probability PΑi for each Ai (Line 5)
for i in range(0,len(dA_sub)):
if (not AddNoise):
A_sub_probabilities[A_sub].append(All_A_sub_counts[A_sub][i]/Dataset_size)
else:
A_sub_probabilities[A_sub].append(All_A_sub_counts[A_sub][i]/New_Dataset_Size)
#print()
#for x in A_sub_probabilities.keys():
#print ("Attributes: ", x, "\nCombinations: ", dA_sub_all[x])
#print ("Probabilities: ", A_sub_probabilities[x] , "\n=======================================")
del All_A_sub_counts
del A_subs
del Attribute_dict
gc.collect()
All_Probabilities = {} # e.g {frozenset(((A,0),(B,0))) : 0} = P(A = 0, B = 0) = 0
for key in dA_sub_all.keys():
for cnt in range(0,len(dA_sub_all[key])):
pairs = [(key[i],dA_sub_all[key][cnt][i]) for i in range(0,len(key))]
All_Probabilities[frozenset(pairs)] = A_sub_probabilities[key][cnt]
del A_sub_probabilities
gc.collect()
#print ("Joint Probabilities for k+1 distributions are:\n")
#for values,probability in All_Probabilities.items():
#print("P(", list(values), ") = ",round(probability,2))
All_Probabilities.update(CalculateProbabilities(A,Attr_domains,All_Probabilities,k,Child_Parents))
#print ("\nJoint Probabilities for the desired child-parents pairs are:\n")
#for values,probability in All_Probabilities.items():
#print("P(", sorted(list(values)), ") = ",round(probability,3))
return All_Probabilities
def ParameterLearning(Joint_Probabilities,Child_Parents,Attr_domains):
cond_prob = {} # e.g {(("Child",X), ("Parents", [Par1,Par2,...])) : { frozenset((X,Value1), (Par1,Value), ....) : cond_probability }
for key in Child_Parents.keys():
child_part = ("Child",key)
parents_part = ["Parents",[par for par in Child_Parents[key]]]
parents_part[1] = frozenset(parents_part[1])
new_key = tuple([child_part,tuple(parents_part)])
cond_prob[new_key] = {}
for key in cond_prob.keys():
all_attrs = [] # Collect all attributes that this cond prob contains (child and parents)
cur_child = key[0][1]
all_attrs.append(cur_child)
for parent in key[1][1]:
all_attrs.append(parent)
subkeys = FindFrozenSets(all_attrs,Attr_domains,[])
#print('Cur_child is',cur_child)
#print("Subkeys are",subkeys)
for subkey in subkeys: # Calculate the conditional probability
parents_fr_set = list(subkey)
child_idx = 0
for i in range(0,len(parents_fr_set)): # Remove the (child,value) tuple from subkey so that only the parents remain
if (parents_fr_set[i][0] == cur_child):