Using pyAgrum

Creative Commons License

aGrUM

interactive online version

In [1]:
%matplotlib inline
from pylab import *
import matplotlib.pyplot as plt

import os

Initialisation

  • importing pyAgrum

  • importing pyAgrum.lib tools

  • loading a BN

In [2]:
import pyAgrum as gum
import pyAgrum.lib.notebook as gnb
gnb.configuration()
LibraryVersion
OSposix [linux]
Python3.11.6 (main, Nov 14 2023, 09:36:21) [GCC 13.2.1 20230801]
IPython8.19.0
Matplotlib3.8.2
Numpy1.26.3
pyDot2.0.0
pyAgrum1.11.0
Fri Jan 05 17:39:41 2024 CET
In [3]:
bn=gum.loadBN("res/alarm.dsl")
gnb.showBN(bn,size='9')
../_images/notebooks_02-Tutorial_Tutorial2_5_0.svg

Visualisation and inspection

In [4]:
print(bn.variableFromName('SHUNT'))
SHUNT:Labelized({NORMAL|HIGH})
In [5]:
print(bn.cpt(bn.idFromName('SHUNT')))

             ||  SHUNT            |
PULMEM|INTUBA||NORMAL   |HIGH     |
------|------||---------|---------|
TRUE  |NORMAL|| 0.1000  | 0.9000  |
FALSE |NORMAL|| 0.9500  | 0.0500  |
TRUE  |ESOPHA|| 0.1000  | 0.9000  |
FALSE |ESOPHA|| 0.9500  | 0.0500  |
TRUE  |ONESID|| 0.0100  | 0.9900  |
FALSE |ONESID|| 0.0500  | 0.9500  |

In [6]:
gnb.showPotential(bn.cpt(bn.idFromName('SHUNT')),digits=3)
SHUNT
INTUBATION
PULMEMBOLUS
NORMAL
HIGH
NORMAL
TRUE
0.1000.900
FALSE
0.9500.050
ESOPHAGEAL
TRUE
0.1000.900
FALSE
0.9500.050
ONESIDED
TRUE
0.0100.990
FALSE
0.0500.950

Results of inference

It is easy to look at result of inference

In [7]:
gnb.showPosterior(bn,{'SHUNT':'HIGH'},'PRESS')
../_images/notebooks_02-Tutorial_Tutorial2_11_0.svg
In [8]:
gnb.showPosterior(bn,{'MINVOLSET':'NORMAL'},'VENTALV')
../_images/notebooks_02-Tutorial_Tutorial2_12_0.svg

Overall results

In [9]:
gnb.showInference(bn,size="10")
../_images/notebooks_02-Tutorial_Tutorial2_14_0.svg

What is the impact of observed variables (SHUNT and VENTALV for instance) on another on (PRESS) ?

In [10]:
ie=gum.LazyPropagation(bn)
ie.evidenceImpact('PRESS',['SHUNT','VENTALV'])
Out[10]:
PRESS
SHUNT
VENTALV
ZERO
LOW
NORMAL
HIGH
NORMAL
ZERO
0.05690.26690.20050.4757
LOW
0.02080.25150.05530.6724
NORMAL
0.07690.32670.17720.4192
HIGH
0.05010.16330.27960.5071
HIGH
ZERO
0.05890.27260.19970.4688
LOW
0.03180.22370.05210.6924
NORMAL
0.17350.58390.14020.1024
HIGH
0.07110.23470.25330.4410

Using inference as a function

It is also easy to use inference as a routine in more complex procedures.

In [11]:
import time
r=range(0,100,2)
xs=[x/100.0 for x in r]

tf=time.time()
ys=[gum.getPosterior(bn,evs={'MINVOLSET':[0,x/100.0,0.5]},target='VENTALV').tolist()
        for x in r]
delta=time.time()-tf

p=plot(xs,ys)
legend(p,[bn.variableFromName('VENTALV').label(i)
          for i in range(bn.variableFromName('VENTALV').domainSize())],loc=7);
title('VENTALV (100 inferences in %d ms)'%delta);
ylabel('posterior Probability');
xlabel('Evidence on MINVOLSET : [0,x,0.5]')
plt.show()
../_images/notebooks_02-Tutorial_Tutorial2_18_0.svg

Another example : python gives access to a large set of tools. Here the value for the equality of two probabilities of a posterior is easely computed.

In [12]:
x=[p/100.0 for p in range(0,100)]

tf=time.time()
y=[gum.getPosterior(bn,evs={'HRBP':[1.0-p/100.0,1.0-p/100.0,p/100.0]},target='TPR').tolist()
   for p in range(0,100)]
delta=time.time()-tf

p=plot(x,y)
title('HRBP (100 inferences in %d ms)'%delta);
v=bn.variableFromName('TPR');
legend([v.label(i) for i in range(v.domainSize())],loc='best');
np1=(transpose(y)[0]>transpose(y)[2]).argmin()
text(x[np1]-0.05,y[np1][0]+0.005,str(x[np1]),bbox=dict(facecolor='red', alpha=0.1))
plt.show()
../_images/notebooks_02-Tutorial_Tutorial2_20_0.svg

BN as a classifier

Generation of databases

Using the CSV format for the database:

In [13]:
print(f"The log2-likelihood of the generated base : {gum.generateSample(bn,1000,'out/test.csv',with_labels=True):.2f}")
The log2-likelihood of the generated base : -14962.72
In [14]:
with open("out/test.csv","r") as src:
    for _ in range(10):
        print(src.readline(),end="")
INTUBATION,PRESS,INSUFFANESTH,CATECHOL,MINVOL,TPR,KINKEDTUBE,PULMEMBOLUS,HYPOVOLEMIA,ERRCAUTER,STROKEVOLUME,HR,PCWP,PVSAT,VENTLUNG,VENTALV,EXPCO2,BP,ANAPHYLAXIS,LVEDVOLUME,PAP,DISCONNECT,HRSAT,CO,VENTTUBE,FIO2,SAO2,LVFAILURE,MINVOLSET,HRBP,HISTORY,HREKG,SHUNT,ARTCO2,VENTMACH,CVP,ERRLOWOUTPUT
ONESIDED,LOW,FALSE,HIGH,LOW,HIGH,FALSE,FALSE,FALSE,FALSE,NORMAL,HIGH,LOW,LOW,ZERO,NORMAL,LOW,HIGH,FALSE,NORMAL,NORMAL,FALSE,HIGH,NORMAL,LOW,NORMAL,LOW,FALSE,NORMAL,HIGH,FALSE,HIGH,HIGH,NORMAL,NORMAL,NORMAL,FALSE
NORMAL,HIGH,FALSE,HIGH,ZERO,HIGH,FALSE,FALSE,FALSE,FALSE,NORMAL,HIGH,NORMAL,LOW,ZERO,ZERO,LOW,HIGH,FALSE,NORMAL,NORMAL,FALSE,HIGH,HIGH,LOW,NORMAL,LOW,FALSE,NORMAL,HIGH,FALSE,HIGH,NORMAL,HIGH,NORMAL,LOW,FALSE
ONESIDED,LOW,FALSE,HIGH,LOW,LOW,FALSE,FALSE,TRUE,FALSE,LOW,HIGH,NORMAL,LOW,ZERO,NORMAL,LOW,LOW,FALSE,NORMAL,NORMAL,FALSE,HIGH,LOW,LOW,NORMAL,LOW,FALSE,NORMAL,HIGH,FALSE,HIGH,HIGH,NORMAL,NORMAL,NORMAL,FALSE
NORMAL,HIGH,FALSE,HIGH,LOW,HIGH,FALSE,FALSE,TRUE,FALS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ORMAL,HIGH,FALSE,LOW,NORMAL,HIGH,NORMAL,NORMAL,FALSE

probabilistic classifier using BN

(because of the use of from-bn-generated csv files, quite good ROC curves are expected)

In [15]:
from pyAgrum.lib.bn2roc import showROC_PR

showROC_PR(bn,"out/test.csv",
        target='CATECHOL',label='HIGH',  # class and label
        show_progress=True,show_fig=True,with_labels=True)
out/test.csv: 100%|█████████████████████████████████████████████████████████████████████████████████████████|
../_images/notebooks_02-Tutorial_Tutorial2_26_1.svg
Out[15]:
(0.9612501139367423, 0.9300899828, 0.9980599444681879, 0.4221808066)

Using another class variable

In [16]:
showROC_PR(bn,"out/test.csv",'SAO2','HIGH',show_progress=True)
out/test.csv: 100%|█████████████████████████████████████████████████████████████████████████████████████████|
../_images/notebooks_02-Tutorial_Tutorial2_28_1.svg
Out[16]:
(0.9615014709210229, 0.0075124397, 0.7239164434430815, 0.5074962099)

Fast prototyping for BNs

In [17]:
bn1=gum.fastBN("a->b;a->c;b->c;c->d",3)

gnb.sideBySide(*[gnb.getInference(bn1,evs={'c':val},targets={'a','c','d'}) for val in range(3)],
              captions=[f"Inference given that $c={val}$" for val in range(3)])
structs Inference in   0.18ms a 2024-01-05T17:39:46.199340 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ b b a->b c 2024-01-05T17:39:46.243004 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ a->c b->c d 2024-01-05T17:39:46.286750 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ c->d
Inference given that $c=0$
structs Inference in   0.35ms a 2024-01-05T17:39:46.457824 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ b b a->b c 2024-01-05T17:39:46.500744 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ a->c b->c d 2024-01-05T17:39:46.544627 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ c->d
Inference given that $c=1$
structs Inference in   0.32ms a 2024-01-05T17:39:46.700058 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ b b a->b c 2024-01-05T17:39:46.743559 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ a->c b->c d 2024-01-05T17:39:46.786561 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ c->d
Inference given that $c=2$
In [18]:
print(gum.getPosterior(bn1,evs={'c':0},target='c'))
print(gum.getPosterior(bn1,evs={'c':0},target='d'))

# using pyagrum.lib.notebook's helpers
gnb.flow.row(gum.getPosterior(bn1,evs={'c':0},target='c'),gum.getPosterior(bn1,evs={'c':0},target='d'))

  c                          |
0        |1        |2        |
---------|---------|---------|
 1.0000  | 0.0000  | 0.0000  |


  d                          |
0        |1        |2        |
---------|---------|---------|
 0.3458  | 0.1195  | 0.5347  |

c
0
1
2
1.00000.00000.0000
d
0
1
2
0.34580.11950.5347

Joint posterior, impact of multiple evidence

In [19]:
bn=gum.fastBN("a->b->c->d;b->e->d->f;g->c")
gnb.sideBySide(bn,gnb.getInference(bn))
G b b c c b->c e e b->e a a a->b f f g g g->c d d c->d e->d d->f
structs Inference in   0.85ms a 2024-01-05T17:39:46.993181 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ b 2024-01-05T17:39:47.041938 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ a->b c 2024-01-05T17:39:47.087587 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ b->c e 2024-01-05T17:39:47.275840 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ b->e d 2024-01-05T17:39:47.231254 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ c->d f 2024-01-05T17:39:47.319155 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ d->f e->d g 2024-01-05T17:39:47.363393 image/svg+xml Matplotlib v3.8.2, https://matplotlib.org/ g->c
In [20]:
ie=gum.LazyPropagation(bn)
ie.addJointTarget({"e","f","g"})
ie.makeInference()
gnb.sideBySide(ie.jointPosterior({"e","f","g"}),ie.jointPosterior({"e","g"}),
               captions=["Joint posterior $P(e,f,g)$","Joint posterior $P(e,f)$"])
g
f
e
0
1
0
0
0.09350.2123
1
0.06760.1945
1
0
0.05490.1533
1
0.07270.1511

Joint posterior $P(e,f,g)$
g
e
0
1
0
0.14840.3656
1
0.14030.3457

Joint posterior $P(e,f)$
In [21]:
gnb.sideBySide(ie.evidenceImpact("a",["e","f"]),ie.evidenceImpact("a",["d","e","f"]),
              captions=["$\\forall e,f, P(a|e,f)$",
                        "$\\forall d,e,f, P(a|d,e,f)=P(a|d,e)$ using d-separation"]
                        )
a
f
e
0
1
0
0
0.47750.5225
1
0.56880.4312
1
0
0.46910.5309
1
0.59480.4052

$\forall e,f, P(a|e,f)$
a
e
d
0
1
0
0
0.48310.5169
1
0.45980.5402
1
0
0.54250.4575
1
0.61350.3865

$\forall d,e,f, P(a|d,e,f)=P(a|d,e)$ using d-separation
In [22]:
gnb.sideBySide(ie.evidenceJointImpact(["a","b"],["e","f"]),ie.evidenceJointImpact(["a","b"],["d","e","f"]),
              captions=["$\\forall e,f, P(a,b|e,f)$",
                        "$\\forall d,e,f, P(a,b|d,e,f)=P(a,b|d,e)$ using d-separation"]
                        )
b
f
e
a
0
1
0
0
0
0.15720.3203
1
0.00010.5224
1
0
0.30460.2642
1
0.00030.4309
1
0
0
0.14370.3254
1
0.00010.5308
1
0
0.34650.2483
1
0.00030.4049

$\forall e,f, P(a,b|e,f)$
b
e
d
a
0
1
0
0
0
0.16630.3168
1
0.00020.5167
1
0
0.12870.3311
1
0.00010.5401
1
0
0
0.26220.2803
1
0.00020.4572
1
0
0.37670.2368
1
0.00030.3862

$\forall d,e,f, P(a,b|d,e,f)=P(a,b|d,e)$ using d-separation

Most Probable Explanation

In [23]:
ie=gum.LazyPropagation(bn)
print(ie.mpe())
<d:0|e:0|c:1|b:1|a:1|g:1|f:0>
In [24]:
evs={"e":0,"g":0}
ie.setEvidence(evs)
vals=ie.mpeLog2Posterior()
print(f"The most probable explanation for observation {evs} is the configuration {vals.first} for a log probability of {vals.second:.6f}")
The most probable explanation for observation {'e': 0, 'g': 0} is the configuration <g:0|e:0|d:0|f:0|c:0|b:1|a:1> for a log probability of -2.129536
In [ ]: