-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmarkovNetworkLearning.py
1276 lines (1131 loc) · 41.8 KB
/
markovNetworkLearning.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
"""
@author: Arthur Esquerre-Pourtère
"""
import pyAgrum as gum
import random
import numpy as np
import pandas as pd
from collections import defaultdict
from _utils.progress_bar import ProgressBar
####### GENERATING RANDOM MN #######
def createRandomMNTree(nodeNumber,minDomainSize=2,maxDomainSize=2):
"""
Build a random markov network and return it, the returned markov network is a tree
Examples
--------
>>> import markovNetworkLearning as mnl
>>> mn=mnl.createRandomMNTree(15,2,4)
Parameters
----------
nodeNumber : int
the number of variables of the markov network
minDomainSize : int
2 or above, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
maxDomainSize : int
2 or above, and more than minDomainSize, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
Returns
-------
pyAgrum.MarkovNet
the resulting Markov network
"""
variablesDomainSize=np.random.randint(minDomainSize,maxDomainSize+1,size=nodeNumber)
tree=gum.MarkovNet()
if nodeNumber>0:
tree.add(gum.LabelizedVariable("0","",int(variablesDomainSize[0])))
for i in range(1,nodeNumber):
otherNode=random.choice(list(tree.nodes()))
tree.add(gum.LabelizedVariable(str(i),"",int(variablesDomainSize[i])))
tree.addFactor({otherNode,str(i)})
return tree
def addRandomEdgesMN(graph,newEdgesNumber):
"""
Add edges to a markov Network by randomly merging factors
Examples
--------
>>> mnl.addRandomEdgesMN(mn,3)
Parameters
----------
graph : pyAgrum.MarkovNet
the original markov network
newEdgesNumber : int
the number of edges we want to add
"""
nodes=list(graph.nodes())
finalEdgesNumber=newEdgesNumber+len(graph.edges())
if finalEdgesNumber>len(nodes)*(len(nodes)-1)/2:
raise ValueError('The maximum number of edges in a graph is nodeNumber*(nodeNumber-1)/2, try adding less edges.')
while len(graph.edges())<finalEdgesNumber:
factors=graph.factors()
nodeA=random.choice(nodes)
otherNodeOrFactor=random.choice(nodes+factors)
if(type(otherNodeOrFactor)==int):
if {otherNodeOrFactor,nodeA} not in factors:
graph.addFactor({otherNodeOrFactor,nodeA})
else:
newFactor=otherNodeOrFactor.copy()
newFactor.add(nodeA)
if newFactor not in factors:
graph.eraseFactor(otherNodeOrFactor)
graph.addFactor(newFactor)
def createRandomMarkovNet(nodeNumber,additionalEdge=0,minDomainSize=2,maxDomainSize=2):
"""
Build a random markov network and return it :
-Step 1: build a tree
-Step 2: create and modify existing factors depending on additionalEdge
-Step 3: generate random factor values
Examples
--------
>>> import markovNetworkLearning as mnl
>>> mn=mnl.createRandomMarkovNet(15,0.2,2,4)
Parameters
----------
nodeNumber : int
the number of variables of the markov network
additionalEdge : float
default value : 0, determine how many factors will be merged
minDomainSize : int
2 or above, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
maxDomainSize : int
2 or above, and more than minDomainSize, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
Returns
-------
pyAgrum.MarkovNet
the resulting Markov network
"""
mn=createRandomMNTree(nodeNumber,minDomainSize,maxDomainSize)
newEdgesNumber=int((nodeNumber-1)*additionalEdge)
addRandomEdgesMN(mn,newEdgesNumber)
mn.generateFactors()
return mn
def createRandomMarkovNetUsingUndiGraph(nodeNumber,additionalEdge=0,minDomainSize=2,maxDomainSize=2):
"""
Build a random markov network and return it :
-Step 1: create a random graph using createRandomUndiGraph
-Step 2: transform the undigraph to a markov network
-Step 3: generate random factor values
Examples
--------
>>> import markovNetworkLearning as mnl
>>> mn=mnl.createRandomMarkovNetUsingUndiGraph(5,0.3,2,3)
Parameters
----------
nodeNumber : int
the number of variables of the markov network
additionalEdge : float
default value : 0, determine the density of the graph, the graph will have int((nodeNumber-1)*(1+additionalEdge)) edges
minDomainSize : int
2 or above, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
maxDomainSize : int
2 or above, and more than minDomainSize, default value : 2, each variable will have a random domain size randomly selected between minDomainSize and maxDomainSize
Returns
-------
pyAgrum.MarkovNet
the resulting Markov network
"""
graph=createRandomUndiGraph(nodeNumber,additionalEdge)
variablesDomainSize=np.random.randint(minDomainSize,maxDomainSize+1,size=nodeNumber)
variablesList={node:gum.LabelizedVariable(str(node),"",int(variablesDomainSize[node])) for node in graph.nodes()}
mn=undiGraphToMarkovNetwork(graph,variables=variablesList,domainSize=2)
mn.generateFactors()
return mn
####### GENERATING RANDOM UNDIGRAPH #######
def createRandomUndiGraphTree(nodeNumber):
"""
Build a random undigraph and return it, the returned graph is a tree
Examples
--------
>>> import markovNetworkLearning as mnl
>>> g=mnl.createRandomUndiGraphTree(15)
Parameters
----------
nodeNumber : int
the number of nodes in the graph
Returns
-------
pyAgrum.UndiGraph
the resulting undigraph
"""
tree=gum.UndiGraph()
if nodeNumber>0:
tree.addNode()
for i in range(1,nodeNumber):
otherNode=random.choice(list(tree.nodes()))
tree.addNode()
tree.addEdge(otherNode,i)
return tree
def addRandomEdgesUndiGraph(graph,newEdgesNumber):
"""
Randomly add edges to an undigraph
Examples
--------
>>> mnl.addRandomEdgesUndiGraph(g,3)
Parameters
----------
graph : pyAgrum.UndiGraph
the original graph
newEdgesNumber : int
the number of edges we want to add
"""
nodes=list(graph.nodes())
finalEdgesNumber=newEdgesNumber+len(graph.edges())
if finalEdgesNumber>len(nodes)*(len(nodes)-1)/2:
raise ValueError('The maximum number of edges in a graph is nodeNumber*(nodeNumber-1)/2, try adding less edges.')
for i in range(newEdgesNumber):
edges=graph.edges()
nodeA=random.choice(nodes)
nodeB=random.choice(nodes)
while nodeA==nodeB or (nodeA,nodeB) in edges or (nodeB,nodeA) in edges:
nodeA=random.choice(nodes)
nodeB=random.choice(nodes)
graph.addEdge(nodeA,nodeB)
def createRandomUndiGraph(nodeNumber,additionalEdge=0):
"""
Build a random undigraph and return it :
-Step 1: build a tree
-Step 2: add edges depending on additionalEdge
Examples
--------
>>> import markovNetworkLearning as mnl
>>> g=mnl.createRandomUndiGraph(15,0.2)
Parameters
----------
nodeNumber : int
the number of variables of the markov network
additionalEdge : float
default value : 0, determine the density of the graph, the graph will have int((nodeNumber-1)*(1+additionalEdge)) edges
Returns
-------
pyAgrum.UndiGraph
the resulting undigraph
"""
undiGraph=createRandomUndiGraphTree(nodeNumber)
newEdgesNumber=int((nodeNumber-1)*additionalEdge)
addRandomEdgesUndiGraph(undiGraph,newEdgesNumber)
return undiGraph
####### SAMPLE FROM MN #######
def getOneSampleFromMN(mn):
"""
Get one sample from a markov network
Examples
--------
>>> sample=mnl.getOneSampleFromMN(mn)
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
Returns
-------
dict
the sample, as a dictionary, keys are the variables names and values are the sampled values
"""
variablesToSample=mn.names()
sampledVariables={}
while variablesToSample!=[]:
sampledValue=gum.getPosterior(mn,target=variablesToSample[0],evs=sampledVariables).draw()
sampledVariables.update({variablesToSample[0]:sampledValue})
variablesToSample.pop(0)
return sampledVariables
def bestSamplingOrder(mn):
"""
Return the list of nodes of the markov network, from those having the most neighbors to those having the less
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
Returns
-------
list
the resulting list
"""
nodesNeighboursNB={node:len(mn.neighbours(node)) for node in mn.names()}
order=sorted(nodesNeighboursNB,key=nodesNeighboursNB.__getitem__,reverse=True)
return order
def getEvidence(mn,variable,candidateNodes):
minConSet={str(node) for node in mn.minimalCondSet(variable,candidateNodes)}
return {mn.variable(int(nodeId)).name() for nodeId in minConSet}
def givenEvidence(mn,variablesToSample):
givenEvidences=dict()
for i in range(len(variablesToSample)):
givenEvidences[variablesToSample[i]]=getEvidence(mn,variablesToSample[i],variablesToSample[:i])
return givenEvidences
def fastSampleFromMNRecursive(mn,samples,samplesNumber,variablesToSampleOrder,variablesEvidences,onlineComputedPotential,sampledVariables,prog):
nextSampleIndex=len(sampledVariables)
if nextSampleIndex==len(variablesToSampleOrder):
samples.extend(sampledVariables for _ in range(samplesNumber))
if prog!=None:
prog.increment_amount(samplesNumber)
prog.display()
else:
variable=variablesToSampleOrder[nextSampleIndex]
variableSample=defaultdict(lambda: 0)
sampledVariablesTuple = tuple(sampledVariables[key] for key in variablesToSampleOrder[:nextSampleIndex] if key in variablesEvidences[variable])
if sampledVariablesTuple in onlineComputedPotential[variable]:
posterior=onlineComputedPotential[variable][sampledVariablesTuple]
else:
posterior=gum.getPosterior(mn,target=variable,evs=sampledVariables)
onlineComputedPotential[variable][sampledVariablesTuple]=posterior
for _ in range(samplesNumber):
value=posterior.draw()
variableSample[value]+=1
for value in variableSample.keys():
fastSampleFromMNRecursive(mn,samples,variableSample[value],variablesToSampleOrder,variablesEvidences,onlineComputedPotential,{**sampledVariables,**{variable:value}},prog)
def fastSampleFromMN(mn,fileName,samplesNumber,shuffle=True,display=False):
"""
Get several samples from a markov network and save it in a CSV file
Examples
--------
>>> mnl.sampleFromMN(mn,"./samples/sampleMN.csv",100,display=True)
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
fileName : str
the path to save the samples
samplesNumber : int
the number of samples
shuffle : bool
default value : True, True to shuffle the samples, False otherwise, shuffle is highly recommended most of the time
display : bool
default value : False, True to display a progress bar, False otherwise
"""
if display:
prog = ProgressBar(fileName + ' : ', 0, samplesNumber, 60, mode='static', char='#')
prog.display()
else:
prog=None
df=pd.DataFrame(columns=sorted(mn.names()))
variablesToSampleOrder=bestSamplingOrder(mn)
variablesEvidences=givenEvidence(mn,variablesToSampleOrder)
onlineComputedPotential=dict()
for variableName in variablesEvidences.keys():
onlineComputedPotential[variableName]=dict()
sampledVariables={}
samples=[]
fastSampleFromMNRecursive(mn,samples,samplesNumber,variablesToSampleOrder,variablesEvidences,onlineComputedPotential,sampledVariables,prog)
if shuffle:
random.shuffle(samples)
df=pd.DataFrame(samples)
df.to_csv(fileName, index=False)
if display:
print("\nDone")
####### PSEUDO LOG LIKELIHOOD #######
def factorsName(mn):
"""
Return the list of factor of a markov network, each factor is a set of node names
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
Returns
-------
list
a list of set, each set is a factor and contains node names
"""
factors=mn.factors()
return [{mn.variable(variable).name() for variable in factor} for factor in factors]
def multiplyFactor(myList,instance,mn) :
result = 1
for x in myList:
result = result * mn.factor(x)[instance]
return result
def computePseudoLogLikelihoodData(mn,df):
"""
Compute the pseudo loglikelihood, on a given markov network, of an instantiation
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
df : pandas.core.series.Series
the instantiation
Returns
-------
float
the pseudo Loglikelihood
"""
data=df.to_dict()
I=gum.Instantiation()
for i in data.keys():
I.add(mn.variableFromName(i))
I.fromdict(data)
sumPseudoLogLikelihood=0
factors=factorsName(mn)
for variable in data.keys():
originalValue=I[variable]
variable=mn.variableFromName(variable)
variableFactors=[factor for factor in factors if variable.name() in factor]
phat=multiplyFactor(variableFactors,I,mn)
sommephat=sum([multiplyFactor(variableFactors,
I.chgVal(variable,int(value)),mn) for value in range(variable.domainSize())])
I.chgVal(variable,originalValue)
sumPseudoLogLikelihood+=np.log(phat/sommephat)
return sumPseudoLogLikelihood
def computePseudoLogLikelihoodDataset(mn,df):
"""
Compute the pseudo loglikelihood, on a given markov network, of a dataset
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
df : pandas.core.frame.DataFrame
the dataset
Returns
-------
float
the pseudo Loglikelihood
"""
return df.apply(lambda data : computePseudoLogLikelihoodData(mn,data), axis = 1).sum()
####### PARAMETERS LEARNING #######
def bestDepart(mn,df):
"""
Replace the factors values of a markov network by their joint probability in a given dataset
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
df : pandas.core.frame.DataFrame
the dataset
"""
for factor in factorsName(mn):
factorList=list(factor)
factorList.sort()
jointProbability=(df.groupby(factorList).size()/df.shape[0])
for factorI in mn.factor(factor).loopIn():
I=[factorI[value] for value in factorList]
try:
factorValue=jointProbability.loc[tuple(I)]
except :
factorValue=0.000001
mn.factor(factor)[factorI]=factorValue
def seriesToInstantiation(mn,df):
d=df.to_dict()
I=gum.Instantiation()
for i in d.keys():
I.add(mn.variableFromName(i))
I.fromdict(d)
return I
def multiplyFactorDict(myList,instance,mn):
result = 1
for x in myList:
result = result * mn[tuple(sorted(x))][instance]
return result
def computeGradientIDataVariable(mn,mnDict,Idata,Ifactor,dictFactor,variable,variableFactors):
"""
Compute the gradient of a value of a factor, on a variable in an instantiation
Parameters
----------
mn : pyAgrum.MarkovNet
the original markov network
mnDict : dict
the markov network we are using to a learn, as a dictionary
Idata : pyAgrum.Instantiation
the instantiation
Ifactor : pyAgrum.Instantiation
Instantiation that describe the value of the factor
dictFactor : dict
Dict that describe the value of the factor
variable : pyAgrum.DiscreteVariable
the variable
variableFactors : dict
keys are variable, values are list of factors that contains the variable in their scope
Returns
-------
float
the gradient
"""
gradient=0
variableName=variable.name()
dictFactorKeys=tuple(sorted(dictFactor.keys()))
originalValue=Idata[variableName]
variableFactors[variableName].remove(dictFactorKeys)
Idata.chgVal(variable,Ifactor[variableName])
up=multiplyFactorDict(variableFactors[variableName],Idata,mnDict)
Idata.chgVal(variable,originalValue)
variableFactors[variableName].append(dictFactorKeys)
down=sum([multiplyFactorDict(variableFactors[variableName],
Idata.chgVal(variable,int(value)),mnDict) for value in range(variable.domainSize())])
gradient-=up/down
Idata.chgVal(variable,originalValue)
if(Ifactor[variableName]==Idata[variableName]):
gradient+=1/mnDict[dictFactorKeys][Ifactor]
return gradient
def computeGradientIData(mn,mnDict,Idata,Ifactor,dictFactor,variableFactors):
"""
Compute the gradient of a value of a factor, on an instantiation
Parameters
----------
mn : pyAgrum.MarkovNet
the original markov network
mnDict : dict
the markov network we are using to a learn, as a dictionary
Idata : pyAgrum.Instantiation
the instantiation
Ifactor : pyAgrum.Instantiation
Instantiation that describe the value of the factor
dictFactor : dict
Dict that describe the value of the factor
variableFactors : dict
keys are variable, values are list of factors that contains the variable in their scope
Returns
-------
float
the gradient
"""
keys={Idata.variable(i).name() for i in range(Idata.nbrDim())}
gradient=0
for i in range(Ifactor.nbrDim()):
variable=Ifactor.variable(i)
keys.remove(variable.name())
if all([not(Ifactor.contains(mn.variableFromName(variable2))) or Ifactor[variable2]==Idata[variable2] for variable2 in keys]):
gradient+=computeGradientIDataVariable(mn,mnDict,Idata,Ifactor,dictFactor,variable,variableFactors)
keys.add(variable.name())
return gradient
def computeGradientIDataset(mn,mnDict,df_I,Ifactor,dictFactor,variableFactors):
"""
Compute the gradient of a value of a factor, on a dataset
Parameters
----------
mn : pyAgrum.MarkovNet
the original markov network
mnDict : dict
the markov network we are using to a learn, as a dictionary
df_I : pandas.core.frame.Series
the dataset, contains Instantiation
Ifactor : pyAgrum.Instantiation
Instantiation that describe the value of the factor
dictFactor : dict
Dict that describe the value of the factor
variableFactors : dict
keys are variable, values are list of factors that contains the variable in their scope
Returns
-------
float
the gradient
"""
return df_I.apply(lambda data : computeGradientIData(mn,mnDict,data,Ifactor,dictFactor,variableFactors)).sum()
def updateMNAndComputeGradient(mn,mnDict,df_I,step,newMnDict,variableFactors,factorsName):
"""
Perform one iteration of the gradient algorithm
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
mnDict : dict
the markov network we are using to learn, as a dictionary
df_I : pandas.core.frame.Series
the dataset, contains Instantiation
step : float
the learning rate
newMnDict : dict
temporary markov network we are using to learn, as a dictionary
variableFactors : dict
keys are variable, values are list of factors that contains the variable in their scope
factorsName : list
the list of factor of the markov network, each factor is a set of node names
Returns
-------
float
the sum of the gradient
"""
sumGradient=0
for factor in factorsName:
for Ifactor in mnDict[factor].loopIn():
dictFactor=Ifactor.todict()
gradient=computeGradientIDataset(mn,mnDict,df_I,Ifactor,dictFactor,variableFactors)
sumGradient+=np.abs(gradient)
if gradient > 0:
newMnDict[factor][dictFactor]=max(mnDict[factor][Ifactor]*(1+step),0.000001)
elif gradient < 0:
newMnDict[factor][dictFactor]=max(mnDict[factor][Ifactor]/(1+step),0.000001)
for factor in factorsName:
mnDict[factor].fillWith(newMnDict[factor])
return mnDict,sumGradient
def sortedFactors(factors):
return {tuple(sorted(factor)):factor for factor in factors}
def mnToDictOfPotential(mn,factorsNames):
mnDict=dict()
for factor in factorsNames:
mnDict[factor]=mn.factor(factorsNames[factor])
return mnDict
def fillMnWithDictOfPotentiel(mn,factorsNames,mnDict):
for factor in factorsNames:
mn.factor(factorsNames[factor]).fillWith(mnDict[factor])
def copyDictOfPotential(mnDict):
newMnDict=dict()
for factor in mnDict:
newMnDict[factor]=gum.Potential(mnDict[factor])
return newMnDict
def learnParameters(mn,df,threshold=-1,maxIt=float('inf'),step=0.1,stepDiscount=1,display=False):
"""
Learn the parameters of a markov network, using gradient algorithm, with a given the database
The objective function we want to maximise is the pseudo-log-likelihood
It is necessery to set a value to either threshold or maxIt
Examples
--------
>>> mnl.learnParameters(forgottenMn,df,maxIt=25,step=0.15,stepDiscount=0.9,display=True)
Parameters
----------
mn : pyAgrum.MarkovNet
the markov network
df : pandas.core.frame.DataFrame
the dataset
threshold : float
default value : -1, the algorithm stops if the sum of the gradient is less than this threshold
maxIt : int
default value : inf, the algorithm stops after maxIt iteration of the gradient
step : float
default value : 0.1, the learning rate
stepDiscount : 1
default value : 1, the discount of the learning rate
display : bool
default value : False, True to display information at each iteration, False otherwise
"""
#bestDepart(mn,df)
assert maxIt>0, 'maxIt be have a strictly positive value'
assert threshold>0 or maxIt!=float('inf'), 'you must give a strictly positive value to threshold or maxIt, otherwise the algorithm can not stop'
factorsNames=sortedFactors(factorsName(mn))
mnDict=mnToDictOfPotential(mn,factorsNames)
for factor in factorsNames:
for Ifactor in mnDict[factor].loopIn():
mnDict[factor][Ifactor]=max(mnDict[factor][Ifactor],0.001)
df_I=df.apply(lambda data : seriesToInstantiation(mn,data), axis = 1)
newMnDict=copyDictOfPotential(mnDict)
variableFactors=dict()
for variable in mn.names():
variableFactors[variable]=[factor for factor in factorsNames if variable in factor]
mnDict,sumGradient=updateMNAndComputeGradient(mn,mnDict,df_I,step,newMnDict,variableFactors,factorsNames)
oldGradient=sumGradient
if display:
print("Sum Gradient ",sumGradient)
print("Step size : ",step)
it=1
while sumGradient>threshold and it<maxIt:
mnDict,sumGradient=updateMNAndComputeGradient(mn,mnDict,df_I,step,newMnDict,variableFactors,factorsNames)
if display:
print("Sum Gradient ",sumGradient)
print("Step size : ",step)
if oldGradient <= sumGradient:
step=step*stepDiscount
oldGradient=sumGradient
it+=1
fillMnWithDictOfPotentiel(mn,factorsNames,mnDict)
####### UNDIGRAPH TO MARKOV NETWORK #######
def degeneracyOrdering(graph):
"""
Return the degeneracy ordering of a graph
Parameters
----------
graph : dict
the graph, as an adjacency list
Returns
-------
list
the degeneracy ordering
"""
L = []
d=dict()
maxDegree=-1
for v in graph:
degree=len(graph[v])
d[v]=degree
if degree>maxDegree:
maxDegree = degree
D =[[] for _ in range(maxDegree+1)]
for v in graph:
D[len(graph[v])].append(v)
k=0
for _ in range(len(graph)):
for i in range(0,maxDegree+1):
if len(D[i]) != 0:
break
k=max(k,i)
v=D[i].pop()
L.insert(0,v)
for w in graph[v]:
if w not in L:
degree = d[w]
D[degree].remove(w)
D[degree-1].append(w)
d[w]-=1
return L
def BronKerbosch(graph,P,R,X):
cliques=[]
if len(P)==0 and len(X)==0:
cliques.append(R)
else:
for v in list(P):
cliques.extend(BronKerbosch(graph,P.intersection(graph[v]),R.union([v]), X.intersection(graph[v])))
P.remove(v)
X.add(v)
return cliques
def removeSelfLoop(graph):
for node in graph:
if node in graph[node]:
graph[node].remove(node)
def getAllMaximalCliquesDict(graph):
"""
Return every maximal cliques of the given graph, using Bron Kerbosch algorithm
Parameters
----------
graph : dict
the graph, as an adjacency list
Returns
-------
list
the list of maximal cliques
"""
removeSelfLoop(graph)
P = set(graph.keys())
X = set()
cliques = []
order=degeneracyOrdering(graph)
for i in range(len(order)):
v=order[i]
neighbors=set(graph[v])
P=neighbors.intersection(set(order[i:]))
X=neighbors.intersection(set(order[:i]))
cliques.extend(BronKerbosch(graph,P,{v},X))
return cliques
def undiGraphToDict(graph):
"""
Return an adjacency list representing the given graph
Parameters
----------
graph : pyAgrum.UndiGraph
the given graph
Returns
-------
list
the adjacency list
"""
graphDict=dict()
for node in graph.nodes():
graphDict[node]=graph.neighbours(node)
return graphDict
def getAllMaximalCliquesUndiGraph(graph):
"""
Return every maximal cliques of the given graph, using Bron Kerbosch algorithm
Parameters
----------
graph : pyAgrum.UndiGraph
the graph
Returns
-------
list
the list of maximal cliques
"""
graphDict=undiGraphToDict(graph)
return getAllMaximalCliquesDict(graphDict)
def undiGraphToMarkovNetwork(graph,variables=dict(),domainSize=2):
"""
Build a markov network from an UndiGraph
Variables can be either given in parameters or can be created if they are not defined
Parameters
----------
graph : pyAgrum.UndiGraph
the graph
variables : dict<str:pyAgrum.DiscreteVariable>
already defined variables, keys are variables name
domainSize : int
the domain of variables that are not defined
Returns
-------
pyAgrum.MarkovNet
the resulting Markov network
"""
nodes=graph.nodes()
cliques=getAllMaximalCliquesUndiGraph(graph)
definedVariables=variables.keys()
mn=gum.MarkovNet()
for node in nodes:
if node in definedVariables:
mn.add(variables[node])
else:
mn.add(gum.LabelizedVariable(str(node),"",domainSize))
for clique in cliques:
mn.addFactor(clique)
return mn
def dictToMarkovNetwork(graph,variables=dict(),domainSize=2):
"""
Build a markov network from an adjacency list
Variables can be either given in parameters or can be created if they are not defined
Parameters
----------
graph : dict
the graph, as an adjacency list
variables : dict<str:pyAgrum.DiscreteVariable>
already defined variables, keys are variables name
domainSize : int
the domain of variables that are not defined
Returns
-------
pyAgrum.MarkovNet
the resulting Markov network
"""
for var1 in graph.keys():
for var2 in graph[var1]:
if var1 not in graph[var2]:
raise ValueError('Can only convert an adjacency list into a markov network : as "'
+str(var2)+'" is a neighbor of "'+str(var1)+'", then "'+str(var1)+'" must be a neighbor of "'+str(var2)+'".')
nodes=graph.keys()
cliques=getAllMaximalCliquesDict(graph)
definedVariables=variables.keys()
mn=gum.MarkovNet()
for node in nodes:
if node in definedVariables:
mn.add(variables[node])
else:
mn.add(gum.LabelizedVariable(str(node),"",domainSize))
for clique in cliques:
mn.addFactor(clique)
return mn
####### STRUCTURE LEARNING #######
def isIndependant(variable,Y,MB,learner,threshold):
"""
Check whether or not two variables are independant given a set of other variables
Use a statistical test Chi2 on a database
True if independant, False otherwise
"""
stat,pvalue=learner.chi2(variable,Y,list(MB))
#stat,pvalue=learner.G2(variable,Y,list(MB))
return pvalue>=threshold
def GS(variable,V,learner,threshold):
MB=set()
#grow phase
toTest=set(V)
toTest.remove(variable)
tested=set()
while toTest:
Y=toTest.pop()
if(not isIndependant(variable,Y,MB,learner,threshold)):
MB.add(Y)
toTest=toTest.union(tested)
tested.clear()
else:
tested.add(Y)
#Shrink phase
toTest=set(MB)
tested=set()
while toTest:
Y=toTest.pop()
MB.remove(Y)
if(not isIndependant(variable,Y,MB,learner,threshold)):
MB.add(Y)
tested.add(Y)
else:
toTest=toTest.union(tested)
tested.clear()
return MB
def correctError(MB):
for var1 in MB.keys():
for var2 in MB[var1]:
if var1 not in MB[var2]:
MB[var2].add(var1)
def GSMN(mn,fileName,threshold=0.05):
"""
Learn the structure of a markov network, using GSMN algorithm on a given the database
Examples
--------
>>> mn=mnl.GSMN(template,"./samples/sampleMN.csv",0.0001)
Parameters
----------
mn : pyAgrum.MarkovNet
the template of the markov network
fileName : str
the other markov network
threshold : float
default value : 0.05, hyperparameter used for the statistical test
Returns
-------
pyAgrum.MarkovNet
the learned markov network
"""
V=mn.names()
mnVariables=dict()
for name in V:
mnVariables[name]=mn.variableFromName(name)
MB=dict()
learner=gum.BNLearner(fileName)
for variable in V:
MB[variable]=GS(variable,V,learner,threshold)
correctError(MB)
mn=dictToMarkovNetwork(MB,mnVariables)
return mn
def IGSMNStar(X,Y,S,F,T,learner,threshold):
if Y in T:
return False
if Y in F:
return True
return isIndependant(X,Y,S,learner,threshold)
def GSMNStar(mn,fileName,threshold=0.05):
"""
Learn the structure of a markov network, using GSMNStar algorithm on a given the database
Examples
--------
>>> mn=mnl.GSMNStar(template,"./samples/sampleMN.csv",0.0001)
Parameters
----------
mn : pyAgrum.MarkovNet
the template of the markov network
fileName : str
the other markov network
threshold : float
default value : 0.05, hyperparameter used for the statistical test
Returns
-------
pyAgrum.MarkovNet