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.3 (main, Jun 5 2023, 09:32:32) [GCC 13.1.1 20230429]
IPython8.14.0
Matplotlib3.7.2
Numpy1.25.1
pyDot1.4.2
pyAgrum1.8.3.9
Tue Jul 25 09:17:20 2023 CEST
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 : -15043.08
In [14]:
with open("out/test.csv","r") as src:
    for _ in range(10):
        print(src.readline(),end="")
VENTMACH,STROKEVOLUME,HRBP,SHUNT,CO,VENTALV,PCWP,MINVOL,CATECHOL,BP,PULMEMBOLUS,PAP,PRESS,INTUBATION,LVEDVOLUME,HYPOVOLEMIA,HREKG,HRSAT,FIO2,SAO2,INSUFFANESTH,CVP,ERRCAUTER,EXPCO2,ARTCO2,MINVOLSET,VENTLUNG,DISCONNECT,LVFAILURE,PVSAT,KINKEDTUBE,ANAPHYLAXIS,HISTORY,VENTTUBE,TPR,HR,ERRLOWOUTPUT
NORMAL,NORMAL,HIGH,NORMAL,HIGH,ZERO,NORMAL,ZERO,HIGH,NORMAL,FALSE,NORMAL,NORMAL,NORMAL,NORMAL,FALSE,HIGH,HIGH,NORMAL,LOW,FALSE,NORMAL,FALSE,LOW,HIGH,NORMAL,ZERO,FALSE,FALSE,LOW,FALSE,FALSE,FALSE,LOW,HIGH,HIGH,FALSE
NORMAL,NORMAL,HIGH,NORMAL,HIGH,ZERO,NORMAL,ZERO,HIGH,HIGH,FALSE,NORMAL,HIGH,NORMAL,NORMAL,FALSE,HIGH,HIGH,NORMAL,LOW,TRUE,NORMAL,FALSE,LOW,HIGH,NORMAL,ZERO,FALSE,FALSE,LOW,FALSE,FALSE,FALSE,LOW,NORMAL,HIGH,FALSE
NORMAL,LOW,HIGH,NORMAL,LOW,LOW,HIGH,LOW,HIGH,LOW,FALSE,NORMAL,LOW,ESOPHAGEAL,HIGH,TRUE,HIGH,HIGH,NORMAL,LOW,FALSE,HIGH,FALSE,NORMAL,HIGH,NORMAL,LOW,FALSE,FALSE,NORMAL,FALSE,FALSE,FALSE,LOW,NORMAL,HIGH,FALSE
NORMAL,LOW,HIGH,NORMAL,LOW,ZERO,HIGH,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,HIGH,NORMAL,ZERO,FALSE,FALSE,LOW,FALSE,FALSE,FALSE,LOW,NORMAL,HIGH,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.9825479930191973, 0.7234195393, 0.9992027001886943, 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.9630881485058211, 0.0082631642, 0.7236888221847168, 0.11850031505)

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.24ms a 2023-07-25T09:17:25.793131 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ b b a->b c 2023-07-25T09:17:25.844931 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ a->c b->c d 2023-07-25T09:17:25.898450 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ c->d
Inference given that $c=0$
structs Inference in   0.36ms a 2023-07-25T09:17:26.182501 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ b b a->b c 2023-07-25T09:17:26.235199 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ a->c b->c d 2023-07-25T09:17:26.288405 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ c->d
Inference given that $c=1$
structs Inference in   0.35ms a 2023-07-25T09:17:26.476299 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ b b a->b c 2023-07-25T09:17:26.528685 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ a->c b->c d 2023-07-25T09:17:26.581640 image/svg+xml Matplotlib v3.7.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.5243  | 0.2106  | 0.2651  |

c
0
1
2
1.00000.00000.0000
d
0
1
2
0.52430.21060.2651

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 e e d d e->d g g c c g->c f f d->f a a b b a->b b->e b->c c->d
structs Inference in   0.79ms a 2023-07-25T09:17:26.801009 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ b 2023-07-25T09:17:26.856517 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ a->b c 2023-07-25T09:17:26.912418 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ b->c e 2023-07-25T09:17:27.018875 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ b->e d 2023-07-25T09:17:26.965074 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ c->d f 2023-07-25T09:17:27.184162 image/svg+xml Matplotlib v3.7.2, https://matplotlib.org/ d->f e->d g 2023-07-25T09:17:27.239333 image/svg+xml Matplotlib v3.7.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.00410.0702
1
0.00610.0949
1
0
0.02020.3226
1
0.02790.4540

Joint posterior $P(e,f,g)$
g
e
0
1
0
0.02430.3928
1
0.03400.5489

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.44890.5511
1
0.41710.5829
1
0
0.44870.5513
1
0.41750.5825

$\forall e,f, P(a|e,f)$
a
e
d
0
1
0
0
0.44890.5511
1
0.44830.5517
1
0
0.41700.5830
1
0.41840.5816

$\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.42460.0243
1
0.50870.0424
1
0
0.26470.1525
1
0.31710.2658
1
0
0
0.42360.0251
1
0.50760.0437
1
0
0.26680.1507
1
0.31970.2627

$\forall e,f, P(a,b|e,f)$
b
e
d
a
0
1
0
0
0
0.42470.0242
1
0.50890.0421
1
0
0.42150.0268
1
0.50510.0467
1
0
0
0.26420.1528
1
0.31660.2664
1
0
0.27130.1472
1
0.32500.2566

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