-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBayesianNetwork.py
1431 lines (1205 loc) · 52.6 KB
/
BayesianNetwork.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
#!/usr/bin/env python3
import itertools
from collections import defaultdict
from functools import reduce
from operator import mul
import networkx as nx
import numpy as np
import pandas as pd
from joblib import Parallel, delayed
from tqdm.auto import tqdm
from pgmpy.base import DAG
from pgmpy.factors.continuous import ContinuousFactor
from pgmpy.factors.discrete import (
DiscreteFactor,
JointProbabilityDistribution,
TabularCPD,
)
from pgmpy.global_vars import logger
from pgmpy.models.MarkovNetwork import MarkovNetwork
from pgmpy.utils import compat_fns
class BayesianNetwork(DAG):
"""
Initializes a Bayesian Network.
A models stores nodes and edges with conditional probability
distribution (cpd) and other attributes.
models hold directed edges. Self loops are not allowed neither
multiple (parallel) edges.
Nodes can be any hashable python object.
Edges are represented as links between nodes.
Parameters
----------
ebunch: input graph
Data to initialize graph. If ebunch=None (default) an empty
graph is created. The ebunch can be an edge list, or any
NetworkX graph object.
latents: list, array-like
List of variables which are latent (i.e. unobserved) in the model.
Examples
--------
Create an empty Bayesian Network with no nodes and no edges.
>>> from pgmpy.models import BayesianNetwork
>>> G = BayesianNetwork()
G can be grown in several ways.
**Nodes:**
Add one node at a time:
>>> G.add_node('a')
Add the nodes from any container (a list, set or tuple or the nodes
from another graph).
>>> G.add_nodes_from(['a', 'b'])
**Edges:**
G can also be grown by adding edges.
Add one edge,
>>> G.add_edge('a', 'b')
a list of edges,
>>> G.add_edges_from([('a', 'b'), ('b', 'c')])
If some edges connect nodes not yet in the model, the nodes
are added automatically. There are no errors when adding
nodes or edges that already exist.
**Shortcuts:**
Many common graph features allow python syntax for speed reporting.
>>> 'a' in G # check if node in graph
True
>>> len(G) # number of nodes in graph
3
"""
def __init__(self, ebunch=None, latents=set()):
super(BayesianNetwork, self).__init__(ebunch=ebunch, latents=latents)
self.cpds = []
self.cardinalities = defaultdict(int)
def add_edge(self, u, v, **kwargs):
"""
Add an edge between u and v.
The nodes u and v will be automatically added if they are
not already in the graph
Parameters
----------
u,v : nodes
Nodes can be any hashable python object.
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> G = BayesianNetwork()
>>> G.add_nodes_from(['grade', 'intel'])
>>> G.add_edge('grade', 'intel')
"""
if u == v:
raise ValueError("Self loops are not allowed.")
if u in self.nodes() and v in self.nodes() and nx.has_path(self, v, u):
raise ValueError(
"Loops are not allowed. Adding the edge from (%s->%s) forms a loop."
% (u, v)
)
else:
super(BayesianNetwork, self).add_edge(u, v, **kwargs)
def remove_node(self, node):
"""
Remove node from the model.
Removing a node also removes all the associated edges, removes the CPD
of the node and marginalizes the CPDs of its children.
Parameters
----------
node : node
Node which is to be removed from the model.
Returns
-------
None
Examples
--------
>>> import pandas as pd
>>> import numpy as np
>>> from pgmpy.models import BayesianNetwork
>>> model = BayesianNetwork([('A', 'B'), ('B', 'C'),
... ('A', 'D'), ('D', 'C')])
>>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 4)),
... columns=['A', 'B', 'C', 'D'])
>>> model.fit(values)
>>> model.get_cpds()
[<TabularCPD representing P(A:2) at 0x7f28248e2438>,
<TabularCPD representing P(B:2 | A:2) at 0x7f28248e23c8>,
<TabularCPD representing P(C:2 | B:2, D:2) at 0x7f28248e2748>,
<TabularCPD representing P(D:2 | A:2) at 0x7f28248e26a0>]
>>> model.remove_node('A')
>>> model.get_cpds()
[<TabularCPD representing P(B:2) at 0x7f28248e23c8>,
<TabularCPD representing P(C:2 | B:2, D:2) at 0x7f28248e2748>,
<TabularCPD representing P(D:2) at 0x7f28248e26a0>]
"""
affected_nodes = [v for u, v in self.edges() if u == node]
for affected_node in affected_nodes:
node_cpd = self.get_cpds(node=affected_node)
if node_cpd:
node_cpd.marginalize([node], inplace=True)
if self.get_cpds(node=node):
self.remove_cpds(node)
self.latents = self.latents - set([node])
super(BayesianNetwork, self).remove_node(node)
def remove_nodes_from(self, nodes):
"""
Remove multiple nodes from the model.
Removing a node also removes all the associated edges, removes the CPD
of the node and marginalizes the CPDs of its children.
Parameters
----------
nodes : list, set (iterable)
Nodes which are to be removed from the model.
Returns
-------
None
Examples
--------
>>> import pandas as pd
>>> import numpy as np
>>> from pgmpy.models import BayesianNetwork
>>> model = BayesianNetwork([('A', 'B'), ('B', 'C'),
... ('A', 'D'), ('D', 'C')])
>>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 4)),
... columns=['A', 'B', 'C', 'D'])
>>> model.fit(values)
>>> model.get_cpds()
[<TabularCPD representing P(A:2) at 0x7f28248e2438>,
<TabularCPD representing P(B:2 | A:2) at 0x7f28248e23c8>,
<TabularCPD representing P(C:2 | B:2, D:2) at 0x7f28248e2748>,
<TabularCPD representing P(D:2 | A:2) at 0x7f28248e26a0>]
>>> model.remove_nodes_from(['A', 'B'])
>>> model.get_cpds()
[<TabularCPD representing P(C:2 | D:2) at 0x7f28248e2a58>,
<TabularCPD representing P(D:2) at 0x7f28248e26d8>]
"""
for node in nodes:
self.remove_node(node)
def add_cpds(self, *cpds):
"""
Add CPD (Conditional Probability Distribution) to the Bayesian Model.
Parameters
----------
cpds : list, set, tuple (array-like)
List of CPDs which will be associated with the model
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete.CPD import TabularCPD
>>> student = BayesianNetwork([('diff', 'grades'), ('aptitude', 'grades')])
>>> grades_cpd = TabularCPD('grades', 3, [[0.1,0.1,0.1,0.1,0.1,0.1],
... [0.1,0.1,0.1,0.1,0.1,0.1],
... [0.8,0.8,0.8,0.8,0.8,0.8]],
... evidence=['diff', 'aptitude'], evidence_card=[2, 3],
... state_names={'grades': ['gradeA', 'gradeB', 'gradeC'],
... 'diff': ['easy', 'hard'],
... 'aptitude': ['low', 'medium', 'high']})
>>> student.add_cpds(grades_cpd)
+---------+-------------------------+------------------------+
|diff: | easy | hard |
+---------+------+--------+---------+------+--------+--------+
|aptitude:| low | medium | high | low | medium | high |
+---------+------+--------+---------+------+--------+--------+
|gradeA | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |
+---------+------+--------+---------+------+--------+--------+
|gradeB | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 | 0.1 |
+---------+------+--------+---------+------+--------+--------+
|gradeC | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 | 0.8 |
+---------+------+--------+---------+------+--------+--------+
"""
for cpd in cpds:
if not isinstance(cpd, (TabularCPD, ContinuousFactor)):
raise ValueError("Only TabularCPD or ContinuousFactor can be added.")
if set(cpd.scope()) - set(cpd.scope()).intersection(set(self.nodes())):
raise ValueError("CPD defined on variable not in the model", cpd)
for prev_cpd_index in range(len(self.cpds)):
if self.cpds[prev_cpd_index].variable == cpd.variable:
logger.warning(f"Replacing existing CPD for {cpd.variable}")
self.cpds[prev_cpd_index] = cpd
break
else:
self.cpds.append(cpd)
def get_cpds(self, node=None):
"""
Returns the cpd of the node. If node is not specified returns all the CPDs
that have been added till now to the graph
Parameters
----------
node: any hashable python object (optional)
The node whose CPD we want. If node not specified returns all the
CPDs added to the model.
Returns
-------
A list of TabularCPDs: list
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> student = BayesianNetwork([('diff', 'grade'), ('intel', 'grade')])
>>> cpd = TabularCPD('grade', 2, [[0.1, 0.9, 0.2, 0.7],
... [0.9, 0.1, 0.8, 0.3]],
... ['intel', 'diff'], [2, 2])
>>> student.add_cpds(cpd)
>>> student.get_cpds()
"""
if node is not None:
if node not in self.nodes():
raise ValueError("Node not present in the Directed Graph")
else:
for cpd in self.cpds:
if cpd.variable == node:
return cpd
else:
return self.cpds
def remove_cpds(self, *cpds):
"""
Removes the cpds that are provided in the argument.
Parameters
----------
*cpds: TabularCPD object
A CPD object on any subset of the variables of the model which
is to be associated with the model.
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> student = BayesianNetwork([('diff', 'grade'), ('intel', 'grade')])
>>> cpd = TabularCPD('grade', 2, [[0.1, 0.9, 0.2, 0.7],
... [0.9, 0.1, 0.8, 0.3]],
... ['intel', 'diff'], [2, 2])
>>> student.add_cpds(cpd)
>>> student.remove_cpds(cpd)
"""
for cpd in cpds:
if isinstance(cpd, (str, int)):
cpd = self.get_cpds(cpd)
self.cpds.remove(cpd)
def get_cardinality(self, node=None):
"""
Returns the cardinality of the node. Throws an error if the CPD for the
queried node hasn't been added to the network.
Parameters
----------
node: Any hashable python object(optional).
The node whose cardinality we want. If node is not specified returns a
dictionary with the given variable as keys and their respective cardinality
as values.
Returns
-------
variable cardinalities: dict or int
If node is specified returns the cardinality of the node else returns a dictionary
with the cardinality of each variable in the network
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> student = BayesianNetwork([('diff', 'grade'), ('intel', 'grade')])
>>> cpd_diff = TabularCPD('diff', 2, [[0.6], [0.4]]);
>>> cpd_intel = TabularCPD('intel', 2, [[0.7], [0.3]]);
>>> cpd_grade = TabularCPD('grade', 2, [[0.1, 0.9, 0.2, 0.7],
... [0.9, 0.1, 0.8, 0.3]],
... ['intel', 'diff'], [2, 2])
>>> student.add_cpds(cpd_diff,cpd_intel,cpd_grade)
>>> student.get_cardinality()
defaultdict(<class 'int'>, {'diff': 2, 'intel': 2, 'grade': 2})
>>> student.get_cardinality('intel')
2
"""
if node is not None:
return self.get_cpds(node).cardinality[0]
else:
cardinalities = defaultdict(int)
for cpd in self.cpds:
cardinalities[cpd.variable] = cpd.cardinality[0]
return cardinalities
@property
def states(self):
"""
Returns a dictionary mapping each node to its list of possible states.
Returns
-------
state_dict: dict
Dictionary of nodes to possible states
"""
state_names_list = [cpd.state_names for cpd in self.cpds]
state_dict = {
node: states for d in state_names_list for node, states in d.items()
}
return state_dict
def check_model(self):
"""
Check the model for various errors. This method checks for the following
errors.
* Checks if the sum of the probabilities for each state is equal to 1 (tol=0.01).
* Checks if the CPDs associated with nodes are consistent with their parents.
Returns
-------
check: boolean
True if all the checks pass otherwise should throw an error.
"""
for node in self.nodes():
cpd = self.get_cpds(node=node)
# Check if a CPD is associated with every node.
if cpd is None:
raise ValueError(f"No CPD associated with {node}")
# Check if the CPD is an instance of either TabularCPD or ContinuousFactor.
elif isinstance(cpd, (TabularCPD, ContinuousFactor)):
evidence = cpd.get_evidence()
parents = self.get_parents(node)
# Check if the evidence set of the CPD is same as its parents.
if set(evidence) != set(parents):
raise ValueError(
f"CPD associated with {node} doesn't have proper parents associated with it."
)
if len(set(cpd.variables) - set(cpd.state_names.keys())) > 0:
raise ValueError(
f"CPD for {node} doesn't have state names defined for all the variables."
)
# Check if the values of the CPD sum to 1.
if not cpd.is_valid_cpd():
raise ValueError(
f"Sum or integral of conditional probabilities for node {node} is not equal to 1."
)
for node in self.nodes():
cpd = self.get_cpds(node=node)
for index, node in enumerate(cpd.variables[1:]):
parent_cpd = self.get_cpds(node)
# Check if the evidence cardinality specified is same as parent's cardinality
if parent_cpd.cardinality[0] != cpd.cardinality[1 + index]:
raise ValueError(
f"The cardinality of {node} doesn't match in it's child nodes."
)
# Check if the state_names are the same in parent and child CPDs.
if parent_cpd.state_names[node] != cpd.state_names[node]:
raise ValueError(
f"The state names of {node} doesn't match in it's child nodes."
)
return True
def to_markov_model(self):
"""
Converts Bayesian Network to Markov Model. The Markov Model created would
be the moral graph of the Bayesian Network.
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> G = BayesianNetwork([('diff', 'grade'), ('intel', 'grade'),
... ('intel', 'SAT'), ('grade', 'letter')])
>>> mm = G.to_markov_model()
>>> mm.nodes()
NodeView(('diff', 'grade', 'intel', 'letter', 'SAT'))
>>> mm.edges()
EdgeView([('diff', 'grade'), ('diff', 'intel'), ('grade', 'letter'), ('grade', 'intel'), ('intel', 'SAT')])
"""
moral_graph = self.moralize()
mm = MarkovNetwork(moral_graph.edges())
mm.add_nodes_from(moral_graph.nodes())
mm.add_factors(*[cpd.to_factor() for cpd in self.cpds])
return mm
def to_junction_tree(self):
"""
Creates a junction tree (or clique tree) for a given Bayesian Network.
For converting a Bayesian Model into a Clique tree, first it is converted
into a Markov one.
For a given markov model (H) a junction tree (G) is a graph
1. where each node in G corresponds to a maximal clique in H
2. each sepset in G separates the variables strictly on one side of the
edge to other.
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> G = BayesianNetwork([('diff', 'grade'), ('intel', 'grade'),
... ('intel', 'SAT'), ('grade', 'letter')])
>>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]])
>>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]])
>>> grade_cpd = TabularCPD('grade', 3,
... [[0.1,0.1,0.1,0.1,0.1,0.1],
... [0.1,0.1,0.1,0.1,0.1,0.1],
... [0.8,0.8,0.8,0.8,0.8,0.8]],
... evidence=['diff', 'intel'],
... evidence_card=[2, 3])
>>> sat_cpd = TabularCPD('SAT', 2,
... [[0.1, 0.2, 0.7],
... [0.9, 0.8, 0.3]],
... evidence=['intel'], evidence_card=[3])
>>> letter_cpd = TabularCPD('letter', 2,
... [[0.1, 0.4, 0.8],
... [0.9, 0.6, 0.2]],
... evidence=['grade'], evidence_card=[3])
>>> G.add_cpds(diff_cpd, intel_cpd, grade_cpd, sat_cpd, letter_cpd)
>>> jt = G.to_junction_tree()
"""
mm = self.to_markov_model()
return mm.to_junction_tree()
def fit(
self,
data,
estimator=None,
state_names=[],
complete_samples_only=True,
n_jobs=-1,
**kwargs,
):
"""
Estimates the CPD for each variable based on a given data set.
Parameters
----------
data: pandas DataFrame object
DataFrame object with column names identical to the variable names of the network.
(If some values in the data are missing the data cells should be set to `numpy.NaN`.
Note that pandas converts each column containing `numpy.NaN`s to dtype `float`.)
estimator: Estimator class
One of:
- MaximumLikelihoodEstimator (default)
- BayesianEstimator: In this case, pass 'prior_type' and either 'pseudo_counts'
or 'equivalent_sample_size' as additional keyword arguments.
See `BayesianEstimator.get_parameters()` for usage.
- ExpectationMaximization
state_names: dict (optional)
A dict indicating, for each variable, the discrete set of states
that the variable can take. If unspecified, the observed values
in the data set are taken to be the only possible states.
complete_samples_only: bool (default `True`)
Specifies how to deal with missing data, if present. If set to `True` all rows
that contain `np.Nan` somewhere are ignored. If `False` then, for each variable,
every row where neither the variable nor its parents are `np.NaN` is used.
n_jobs: int (default: -1)
Number of threads/processes to use for estimation. It improves speed only
for large networks (>100 nodes). For smaller networks might reduce
performance.
Returns
-------
Fitted Model: None
Modifies the network inplace and adds the `cpds` property.
Examples
--------
>>> import pandas as pd
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.estimators import MaximumLikelihoodEstimator
>>> data = pd.DataFrame(data={'A': [0, 0, 1], 'B': [0, 1, 0], 'C': [1, 1, 0]})
>>> model = BayesianNetwork([('A', 'C'), ('B', 'C')])
>>> model.fit(data)
>>> model.get_cpds()
[<TabularCPD representing P(A:2) at 0x7fb98a7d50f0>,
<TabularCPD representing P(B:2) at 0x7fb98a7d5588>,
<TabularCPD representing P(C:2 | A:2, B:2) at 0x7fb98a7b1f98>]
"""
from pgmpy.estimators import BaseEstimator, MaximumLikelihoodEstimator
if estimator is None:
estimator = MaximumLikelihoodEstimator
else:
if not issubclass(estimator, BaseEstimator):
raise TypeError("Estimator object should be a valid pgmpy estimator.")
_estimator = estimator(
self,
data,
state_names=state_names,
complete_samples_only=complete_samples_only,
)
cpds_list, counts_tables = _estimator.get_parameters(n_jobs=n_jobs, **kwargs)
self.add_cpds(*cpds_list)
return counts_tables
def fit_update(self, data, n_prev_samples=None, n_jobs=-1):
"""
Method to update the parameters of the BayesianNetwork with more data.
Internally, uses BayesianEstimator with dirichlet prior, and uses
the current CPDs (along with `n_prev_samples`) to compute the pseudo_counts.
Parameters
----------
data: pandas.DataFrame
The new dataset which to use for updating the model.
n_prev_samples: int
The number of samples/datapoints on which the model was trained before.
This parameter determines how much weight should the new data be given.
If None, n_prev_samples = nrow(data).
n_jobs: int (default: -1)
Number of threads/processes to use for estimation. It improves speed only
for large networks (>100 nodes). For smaller networks might reduce
performance.
Returns
-------
Updated model: None
Modifies the network inplace.
Examples
--------
>>> from pgmpy.utils import get_example_model
>>> from pgmpy.sampling import BayesianModelSampling
>>> model = get_example_model('alarm')
>>> # Generate some new data.
>>> data = BayesianModelSampling(model).forward_sample(int(1e3))
>>> model.fit_update(data)
"""
from pgmpy.estimators import BayesianEstimator
# from BayesianEstimator import BayesianEstimator
if n_prev_samples is None:
n_prev_samples = data.shape[0]
# Step 1: Compute the pseudo_counts for the dirichlet prior.
pseudo_counts = {
var: self.get_cpds(var).get_values() * n_prev_samples
for var in data.columns
}
# Step 2: Get the current order of state names for aligning pseudo counts.
state_names = {}
for var in data.columns:
state_names.update(self.get_cpds(var).state_names)
# Step 3: Estimate the new CPDs.
_est = BayesianEstimator(self, data, state_names=state_names)
cpds = _est.get_parameters(
prior_type="dirichlet", pseudo_counts=pseudo_counts, n_jobs=n_jobs
)
self.add_cpds(*cpds)
def predict(self, data, stochastic=False, n_jobs=-1):
"""
Predicts states of all the missing variables.
Parameters
----------
data: pandas DataFrame object
A DataFrame object with column names same as the variables in the model.
stochastic: boolean
If True, does prediction by sampling from the distribution of predicted variable(s).
If False, returns the states with the highest probability value (i.e. MAP) for the
predicted variable(s).
n_jobs: int (default: -1)
The number of CPU cores to use. If -1, uses all available cores.
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> from pgmpy.models import BayesianNetwork
>>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)),
... columns=['A', 'B', 'C', 'D', 'E'])
>>> train_data = values[:800]
>>> predict_data = values[800:]
>>> model = BayesianNetwork([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')])
>>> model.fit(train_data)
>>> predict_data = predict_data.copy()
>>> predict_data.drop('E', axis=1, inplace=True)
>>> y_pred = model.predict(predict_data)
>>> y_pred
E
800 0
801 1
802 1
803 1
804 0
... ...
993 0
994 0
995 1
996 1
997 0
998 0
999 0
"""
from pgmpy.inference import VariableElimination
if set(data.columns) == set(self.nodes()):
raise ValueError("No variable missing in data. Nothing to predict")
elif set(data.columns) - set(self.nodes()):
raise ValueError("Data has variables which are not in the model")
missing_variables = set(self.nodes()) - set(data.columns)
model_inference = VariableElimination(self)
if stochastic:
data_unique_indexes = data.groupby(list(data.columns)).apply(
lambda t: t.index.tolist()
)
data_unique = data_unique_indexes.index.to_frame()
pred_values = Parallel(n_jobs=n_jobs)(
delayed(model_inference.query)(
variables=missing_variables,
evidence=data_point.to_dict(),
show_progress=False,
)
for index, data_point in tqdm(
data_unique.iterrows(), total=data_unique.shape[0]
)
)
predictions = pd.DataFrame()
for i, row in enumerate(data_unique_indexes):
p = pred_values[i].sample(n=len(row))
p.index = row
predictions = pd.concat((predictions, p), copy=False)
return predictions.reindex(data.index)
else:
data_unique = data.drop_duplicates()
pred_values = []
# Send state_names dict from one of the estimated CPDs to the inference class.
pred_values = Parallel(n_jobs=n_jobs)(
delayed(model_inference.map_query)(
variables=missing_variables,
evidence=data_point.to_dict(),
show_progress=False,
)
for index, data_point in tqdm(
data_unique.iterrows(), total=data_unique.shape[0]
)
)
df_results = pd.DataFrame(pred_values, index=data_unique.index)
data_with_results = pd.concat([data_unique, df_results], axis=1)
return data.merge(data_with_results, how="left").loc[
:, list(missing_variables)
]
def predict_probability(self, data):
"""
Predicts probabilities of all states of the missing variables.
Parameters
----------
data : pandas DataFrame object
A DataFrame object with column names same as the variables in the model.
Examples
--------
>>> import numpy as np
>>> import pandas as pd
>>> from pgmpy.models import BayesianNetwork
>>> values = pd.DataFrame(np.random.randint(low=0, high=2, size=(100, 5)),
... columns=['A', 'B', 'C', 'D', 'E'])
>>> train_data = values[:80]
>>> predict_data = values[80:]
>>> model = BayesianNetwork([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')])
>>> model.fit(values)
>>> predict_data = predict_data.copy()
>>> predict_data.drop('B', axis=1, inplace=True)
>>> y_prob = model.predict_probability(predict_data)
>>> y_prob
B_0 B_1
80 0.439178 0.560822
81 0.581970 0.418030
82 0.488275 0.511725
83 0.581970 0.418030
84 0.510794 0.489206
85 0.439178 0.560822
86 0.439178 0.560822
87 0.417124 0.582876
88 0.407978 0.592022
89 0.429905 0.570095
90 0.581970 0.418030
91 0.407978 0.592022
92 0.429905 0.570095
93 0.429905 0.570095
94 0.439178 0.560822
95 0.407978 0.592022
96 0.559904 0.440096
97 0.417124 0.582876
98 0.488275 0.511725
99 0.407978 0.592022
"""
from pgmpy.inference import VariableElimination
if set(data.columns) == set(self.nodes()):
raise ValueError("No variable missing in data. Nothing to predict")
elif set(data.columns) - set(self.nodes()):
raise ValueError("Data has variables which are not in the model")
missing_variables = set(self.nodes()) - set(data.columns)
pred_values = defaultdict(list)
model_inference = VariableElimination(self)
for _, data_point in data.iterrows():
full_distribution = model_inference.query(
variables=missing_variables,
evidence=data_point.to_dict(),
show_progress=False,
)
states_dict = {}
for var in missing_variables:
states_dict[var] = full_distribution.marginalize(
missing_variables - {var}, inplace=False
)
for k, v in states_dict.items():
for l in range(len(v.values)):
state = self.get_cpds(k).state_names[k][l]
pred_values[k + "_" + str(state)].append(v.values[l])
return pd.DataFrame(pred_values, index=data.index)
def get_state_probability(self, states):
"""
Given a fully specified Bayesian Network, returns the probability of the given set
of states.
Parameters
----------
state: dict
dict of the form {variable: state}
Returns
-------
float: The probability value
Examples
--------
>>> from pgmpy.utils import get_example_model
>>> model = get_example_model('asia')
>>> model.get_state_probability({'either': 'no', 'tub': 'no', 'xray': 'yes', 'bronc': 'no'})
0.02605122
"""
# Step 1: Check that all variables and states are in the model.
self.check_model()
for var, state in states.items():
if var not in self.nodes():
raise ValueError(f"{var} not in the model.")
if state not in self.states[var]:
raise ValueError(f"State: {state} not define for {var}")
# Step 2: Missing variables in states.
missing_vars = list(set(self.nodes()) - set(states.keys()))
missing_var_states = {var: self.states[var] for var in missing_vars}
# Step 2: Compute the probability
final_prob = 0
for state_comb in itertools.product(*missing_var_states.values()):
temp_states = {
**{var: state_comb[i] for i, var in enumerate(missing_vars)},
**states,
}
prob = 1
for cpd in self.cpds:
index = []
for var in cpd.variables:
index.append(cpd.name_to_no[var][temp_states[var]])
prob *= cpd.values[tuple(index)]
final_prob += prob
return final_prob
def get_factorized_product(self, latex=False):
# TODO: refer to IMap class for explanation why this is not implemented.
pass
def is_imap(self, JPD):
"""
Checks whether the Bayesian Network is Imap of given JointProbabilityDistribution
Parameters
----------
JPD: An instance of JointProbabilityDistribution Class, for which you want to check the Imap
Returns
-------
is IMAP: True or False
True if Bayesian Network is Imap for given Joint Probability Distribution False otherwise
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> from pgmpy.factors.discrete import JointProbabilityDistribution
>>> G = BayesianNetwork([('diff', 'grade'), ('intel', 'grade')])
>>> diff_cpd = TabularCPD('diff', 2, [[0.2], [0.8]])
>>> intel_cpd = TabularCPD('intel', 3, [[0.5], [0.3], [0.2]])
>>> grade_cpd = TabularCPD('grade', 3,
... [[0.1,0.1,0.1,0.1,0.1,0.1],
... [0.1,0.1,0.1,0.1,0.1,0.1],
... [0.8,0.8,0.8,0.8,0.8,0.8]],
... evidence=['diff', 'intel'],
... evidence_card=[2, 3])
>>> G.add_cpds(diff_cpd, intel_cpd, grade_cpd)
>>> val = [0.01, 0.01, 0.08, 0.006, 0.006, 0.048, 0.004, 0.004, 0.032,
0.04, 0.04, 0.32, 0.024, 0.024, 0.192, 0.016, 0.016, 0.128]
>>> JPD = JointProbabilityDistribution(['diff', 'intel', 'grade'], [2, 3, 3], val)
>>> G.is_imap(JPD)
True
"""
if not isinstance(JPD, JointProbabilityDistribution):
raise TypeError("JPD must be an instance of JointProbabilityDistribution")
factors = [cpd.to_factor() for cpd in self.get_cpds()]
factor_prod = reduce(mul, factors)
JPD_fact = DiscreteFactor(JPD.variables, JPD.cardinality, JPD.values)
if JPD_fact == factor_prod:
return True
else:
return False
def copy(self):
"""
Returns a copy of the model.
Returns
-------
Model's copy: pgmpy.models.BayesianNetwork
Copy of the model on which the method was called.
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> model = BayesianNetwork([('A', 'B'), ('B', 'C')])
>>> cpd_a = TabularCPD('A', 2, [[0.2], [0.8]])
>>> cpd_b = TabularCPD('B', 2, [[0.3, 0.7], [0.7, 0.3]],
... evidence=['A'],
... evidence_card=[2])
>>> cpd_c = TabularCPD('C', 2, [[0.1, 0.9], [0.9, 0.1]],
... evidence=['B'],
... evidence_card=[2])
>>> model.add_cpds(cpd_a, cpd_b, cpd_c)
>>> copy_model = model.copy()
>>> copy_model.nodes()
NodeView(('A', 'B', 'C'))
>>> copy_model.edges()
OutEdgeView([('A', 'B'), ('B', 'C')])
>>> len(copy_model.get_cpds())
3
"""
model_copy = BayesianNetwork()
model_copy.add_nodes_from(self.nodes())
model_copy.add_edges_from(self.edges())
if self.cpds:
model_copy.add_cpds(*[cpd.copy() for cpd in self.cpds])
model_copy.latents = self.latents
return model_copy
def get_markov_blanket(self, node):
"""
Returns a markov blanket for a random variable. In the case
of Bayesian Networks, the markov blanket is the set of
node's parents, its children and its children's other parents.
Returns
-------
Markov Blanket: list
List of nodes contained in Markov Blanket of `node`
Parameters
----------
node: string, int or any hashable python object.
The node whose markov blanket would be returned.
Examples
--------
>>> from pgmpy.models import BayesianNetwork
>>> from pgmpy.factors.discrete import TabularCPD
>>> G = BayesianNetwork([('x', 'y'), ('z', 'y'), ('y', 'w'), ('y', 'v'), ('u', 'w'),
... ('s', 'v'), ('w', 't'), ('w', 'm'), ('v', 'n'), ('v', 'q')])
>>> G.get_markov_blanket('y')
['s', 'u', 'w', 'v', 'z', 'x']
"""
children = self.get_children(node)
parents = self.get_parents(node)
blanket_nodes = children + parents
for child_node in children:
blanket_nodes.extend(self.get_parents(child_node))
blanket_nodes = set(blanket_nodes)
blanket_nodes.discard(node)
return list(blanket_nodes)
@staticmethod