In this example I will try to create the Alarm Bayesian Network using pgmpy and do some simple queries on the network. This network is mentioned in Bayesian Artificial Intelligence - Section 2.5.1 (https://bayesian-intelligence.com/publications/bai/book/BAI_Chapter2.pdf)
In [9]:
#Importing Library
from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination
In [10]:
#Defining network structure
alarm_model = BayesianModel([('Burglary', 'Alarm'),
('Earthquake', 'Alarm'),
('Alarm', 'JohnCalls'),
('Alarm', 'MaryCalls')])
#Defining the parameters using CPT
from pgmpy.factors.discrete import TabularCPD
cpd_burglary = TabularCPD(variable='Burglary', variable_card=2,
values=[[.999], [0.001]])
cpd_earthquake = TabularCPD(variable='Earthquake', variable_card=2,
values=[[0.998], [0.002]])
cpd_alarm = TabularCPD(variable='Alarm', variable_card=2,
values=[[0.999, 0.71, 0.06, 0.05],
[0.001, 0.29, 0.94, 0.95]],
evidence=['Burglary', 'Earthquake'],
evidence_card=[2, 2])
cpd_johncalls = TabularCPD(variable='JohnCalls', variable_card=2,
values=[[0.95, 0.1], [0.05, 0.9]],
evidence=['Alarm'], evidence_card=[2])
cpd_marycalls = TabularCPD(variable='MaryCalls', variable_card=2,
values=[[0.1, 0.7], [0.9, 0.3]],
evidence=['Alarm'], evidence_card=[2])
# Associating the parameters with the model structure
alarm_model.add_cpds(cpd_burglary, cpd_earthquake, cpd_alarm, cpd_johncalls, cpd_marycalls)
In [11]:
# Checking if the cpds are valid for the model
alarm_model.check_model()
Out[11]:
In [12]:
# Viewing nodes of the model
alarm_model.nodes()
Out[12]:
In [13]:
# Viewing edges of the model
alarm_model.edges()
Out[13]:
In [15]:
#Checking independcies of a node
alarm_model.local_independencies('Burglary')
Out[15]:
In [16]:
#Listing all Independencies
alarm_model.get_independencies()
Out[16]: