We will be using the Asia network (http://www.bnlearn.com/bnrepository/#asia) and do some inference queries.


In [1]:
# Fetching the network
!wget http://www.bnlearn.com/bnrepository/asia/asia.bif.gz
!gzip -qd asia.bif.gz | rm asia.bif.gz


--2016-09-30 12:38:47--  http://www.bnlearn.com/bnrepository/asia/asia.bif.gz
Resolving www.bnlearn.com (www.bnlearn.com)... 176.58.124.98
Connecting to www.bnlearn.com (www.bnlearn.com)|176.58.124.98|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 310 [application/octet-stream]
Saving to: ‘asia.bif.gz’

asia.bif.gz         100%[===================>]     310  --.-KB/s    in 0s      

2016-09-30 12:38:47 (16,4 MB/s) - ‘asia.bif.gz’ saved [310/310]


In [2]:
from pgmpy.readwrite import BIFReader
reader = BIFReader('asia.bif')
!rm asia.bif
asia_model = reader.get_model()

In [3]:
asia_model.nodes()


Out[3]:
['xray', 'bronc', 'asia', 'dysp', 'lung', 'either', 'smoke', 'tub']

In [4]:
asia_model.edges()


Out[4]:
[('bronc', 'dysp'),
 ('asia', 'tub'),
 ('lung', 'either'),
 ('either', 'dysp'),
 ('either', 'xray'),
 ('smoke', 'bronc'),
 ('smoke', 'lung'),
 ('tub', 'either')]

In [5]:
asia_model.get_cpds()


Out[5]:
[<TabularCPD representing P(asia:2) at 0x7f92cf1e46d0>,
 <TabularCPD representing P(bronc:2 | smoke:2) at 0x7f92ea70f990>,
 <TabularCPD representing P(dysp:2 | bronc:2, either:2) at 0x7f92f80f4ed0>,
 <TabularCPD representing P(either:2 | lung:2, tub:2) at 0x7f92e8e71dd0>,
 <TabularCPD representing P(lung:2 | smoke:2) at 0x7f92cf1e4c50>,
 <TabularCPD representing P(smoke:2) at 0x7f92cf1e4ed0>,
 <TabularCPD representing P(tub:2 | asia:2) at 0x7f92cf1ec210>,
 <TabularCPD representing P(xray:2 | either:2) at 0x7f92cf1ec410>]

In [6]:
# Doing exact inference using Variable Elimination
from pgmpy.inference import VariableElimination
asia_infer = VariableElimination(asia_model)

# Computing the probability of bronc given smoke.
q = asia_infer.query(variables=['bronc'], evidence={'smoke': 0})
print(q['bronc'])


+---------+--------------+
| bronc   |   phi(bronc) |
|---------+--------------|
| bronc_0 |       0.6000 |
| bronc_1 |       0.4000 |
+---------+--------------+

In [7]:
q = asia_infer.query(variables=['bronc'], evidence={'smoke': 1})
print(q['bronc'])


+---------+--------------+
| bronc   |   phi(bronc) |
|---------+--------------|
| bronc_0 |       0.3000 |
| bronc_1 |       0.7000 |
+---------+--------------+