Using pyAgrum

Creative Commons License

aGrUM

interactive online version

In [1]:
import numpy as np
import matplotlib.pyplot as plt

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 [darwin]
Python3.14.7 (main, Aug 5 2026, 10:29:49) [Clang 21.0.0 (clang-2100.1.1.101)]
IPython9.16.1
Matplotlib3.11.1
Numpy2.5.2
pyDot4.0.1
pyAgrum3.1.0
Tue Aug 18 12:00:01 2026 CEST
In [3]:
bn = gum.loadBN("res/alarm.dsl")
gnb.showBN(bn, size="9")
../_images/notebooks_02-Tutorial_Using_pyAgrum_5_0.svg

Visualisation and inspection

In [4]:
print(bn["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.showTensor(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")
In [8]:
gnb.showPosterior(bn, {"MINVOLSET": "NORMAL"}, "VENTALV")

Overall results

In [9]:
gnb.showInference(bn, size="10")
../_images/notebooks_02-Tutorial_Using_pyAgrum_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)
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

plt.plot(xs, ys)
plt.legend([bn["VENTALV"].label(i) for i in range(bn["VENTALV"].domainSize())], loc=7)
plt.title("VENTALV (100 inferences in %d ms)" % delta)
plt.ylabel("posterior Probability")
plt.xlabel("Evidence on MINVOLSET : [0,x,0.5]")
plt.show()
../_images/notebooks_02-Tutorial_Using_pyAgrum_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

plt.plot(x, y)
plt.title("HRBP (100 inferences in %d ms)" % delta)
v = bn["TPR"]
plt.legend([v.label(i) for i in range(v.domainSize())], loc="best")
np1 = (np.transpose(y)[0] > np.transpose(y)[2]).argmin()
plt.text(x[np1] - 0.05, y[np1][0] + 0.005, str(x[np1]), bbox=dict(facecolor="red", alpha=0.05))
plt.show()
../_images/notebooks_02-Tutorial_Using_pyAgrum_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 : -14973.62
In [14]:
with open("out/test.csv", "r") as src:
  for _ in range(10):
    print(src.readline(), end="")
HISTORY,VENTLUNG,VENTTUBE,HR,ANAPHYLAXIS,PAP,ARTCO2,BP,SHUNT,PRESS,HYPOVOLEMIA,INTUBATION,HREKG,TPR,STROKEVOLUME,CVP,HRBP,PULMEMBOLUS,FIO2,PCWP,EXPCO2,KINKEDTUBE,MINVOL,CO,HRSAT,INSUFFANESTH,CATECHOL,LVFAILURE,VENTMACH,ERRLOWOUTPUT,DISCONNECT,VENTALV,LVEDVOLUME,ERRCAUTER,SAO2,PVSAT,MINVOLSET
FALSE,ZERO,LOW,HIGH,FALSE,NORMAL,NORMAL,HIGH,HIGH,ZERO,FALSE,ONESIDED,HIGH,NORMAL,NORMAL,NORMAL,HIGH,FALSE,NORMAL,NORMAL,LOW,FALSE,LOW,HIGH,HIGH,FALSE,HIGH,FALSE,NORMAL,FALSE,FALSE,NORMAL,NORMAL,FALSE,LOW,LOW,NORMAL
FALSE,ZERO,LOW,HIGH,FALSE,NORMAL,HIGH,LOW,NORMAL,LOW,TRUE,NORMAL,HIGH,HIGH,LOW,HIGH,HIGH,FALSE,LOW,HIGH,LOW,FALSE,ZERO,LOW,HIGH,FALSE,HIGH,FALSE,NORMAL,FALSE,FALSE,ZERO,HIGH,FALSE,LOW,LOW,NORMAL
FALSE,ZERO,LOW,HIGH,FALSE,NORMAL,HIGH,HIGH,HIGH,HIGH,FALSE,NORMAL,HIGH,HIGH,NORMAL,NORMAL,HIGH,FALSE,NORMAL,NORMAL,LOW,FALSE,ZERO,HIGH,HIGH,FALSE,HIGH,FALSE,NORMAL,FALSE,FALSE,ZERO,NORMAL,FALSE,LOW,LOW,NORMAL
FALSE,ZERO,ZERO,HIGH,FALSE,NORMAL,HIGH,NORMAL,NORMAL,LOW,TRUE,NORMAL,HIGH,NORMAL,LOW,HIGH,HIGH,FALSE,NORMAL,HIGH,LOW,FALSE,ZERO,NORMAL,HIGH,FALSE,HIGH,FALSE,ZERO,FALSE,FALSE,ZERO,HIGH,FALSE,LOW,LOW,NORMAL
FALSE,ZERO,LOW,HIGH,FALSE,NORMAL,HIGH,LOW,NORMAL,HIGH,FALSE,NORMAL,HIGH,LOW,LOW,NORMAL,NORMAL,FALSE,NORMAL,NORMAL,LOW,FALSE,ZERO,NORMAL,HIGH,TRUE,HIGH,FALSE,NORMAL,TRUE,FALSE,ZERO,NORMAL,FALSE,LOW,LOW,NORMAL
FALSE,NORMAL,NORMAL,NORMAL,FALSE,NORMAL,NORMAL,LOW,NORMAL,NORMAL,FALSE,NORMAL,NORMAL,LOW,NORMAL,NORMAL,LOW,FALSE,NORMAL,NORMAL,NORMAL,FALSE,LOW,NORMAL,LOW,FALSE,HIGH,FALSE,LOW,FALSE,FALSE,HIGH,NORMAL,FALSE,NORMAL,HIGH,LOW
FALSE,ZERO,LOW,HIGH,FALSE,NORMAL,HIGH,LOW,NORMAL,HIGH,FALSE,NORMAL,HIGH,LOW,NORMAL,NORMAL,HIGH,FALSE,NORMAL,NORMAL,LOW,FALSE,ZERO,LOW,HIGH,FALSE,HIGH,FALSE,NORMAL,FALSE,FALSE,ZERO,NORMAL,FALSE,LOW,LOW,NORMAL
FALSE,ZERO,LOW,HIGH,FALSE,NORMAL,HIGH,LOW,NORMAL,ZERO,TRUE,NORMAL,HIGH,HIGH,LOW,HIGH,HIGH,FALSE,NORMAL,HIGH,NORMAL,FALSE,ZERO,LOW,HIGH,FALSE,HIGH,FALSE,NORMAL,FALSE,FALSE,ZERO,HIGH,FALSE,LOW,LOW,NORMAL
FALSE,ZERO,ZERO,HIGH,FALSE,NORMAL,HIGH,NORMAL,NORMAL,LOW,FALSE,NORMAL,HIGH,NORMAL,NORMAL,NORMAL,HIGH,FALSE,NORMAL,NORMAL,LOW,FALSE,ZERO,HIGH,HIGH,FALSE,HIGH,FALSE,NORMAL,FALSE,TRUE,ZERO,NORMAL,FALSE,LOW,LOW,NORMAL

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_Using_pyAgrum_26_1.svg
Out[15]:
(np.float64(0.9726631578947369),
 np.float64(0.9300899828),
 np.float64(0.9985482275889731),
 np.float64(0.1340682802))

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_Using_pyAgrum_28_1.svg
Out[16]:
(np.float64(0.28939522050643046),
 np.float64(0.012257517612538345),
 np.float64(0.018485366504415426),
 np.float64(0.012257517612538345))

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.10ms a 2026-08-18T12:00:07.534265 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ b b a->b c 2026-08-18T12:00:07.576993 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ a->c b->c d 2026-08-18T12:00:07.608584 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ c->d
Inference given that $c=0$
structs Inference in   0.12ms a 2026-08-18T12:00:07.889853 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ b b a->b c 2026-08-18T12:00:07.930136 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ a->c b->c d 2026-08-18T12:00:07.954621 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ c->d
Inference given that $c=1$
structs Inference in   0.12ms a 2026-08-18T12:00:08.180536 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ b b a->b c 2026-08-18T12:00:08.218224 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ a->c b->c d 2026-08-18T12:00:08.256866 image/svg+xml Matplotlib v3.11.1, 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.2910  │ 0.3730  │ 0.3361  │

Out[18]:
c
0
1
2
1.00000.00000.0000
d
0
1
2
0.29100.37300.3361

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 c c d d c->d f f d->f b b b->c e e b->e g g g->c e->d a a a->b
structs Inference in   0.23ms a 2026-08-18T12:00:08.551762 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ b 2026-08-18T12:00:08.595845 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ a->b c 2026-08-18T12:00:08.630855 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ b->c e 2026-08-18T12:00:08.711860 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ b->e d 2026-08-18T12:00:08.666396 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ c->d f 2026-08-18T12:00:08.746000 image/svg+xml Matplotlib v3.11.1, https://matplotlib.org/ d->f e->d g 2026-08-18T12:00:08.786917 image/svg+xml Matplotlib v3.11.1, 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.18530.4792
1
0.04880.1542
1
0
0.03490.0717
1
0.01650.0093

Joint posterior $P(e,f,g)$
g
e
0
1
0
0.22020.5509
1
0.06540.1636

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.67660.3234
1
0.92970.0703
1
0
0.60920.3908
1
0.91150.0885

$\forall e,f, P(a|e,f)$
a
e
d
0
1
0
0
0.59600.4040
1
0.68130.3187
1
0
0.90680.0932
1
0.93070.0693

$\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.53710.1395
1
0.03460.2889
1
0
0.92440.0052
1
0.05960.0108
1
0
0
0.43390.1753
1
0.02800.3629
1
0
0.89670.0148
1
0.05780.0307

$\forall e,f, P(a,b|e,f)$
b
e
d
a
0
1
0
0
0
0.41370.1823
1
0.02670.3774
1
0
0.54440.1370
1
0.03510.2836
1
0
0
0.88950.0173
1
0.05730.0359
1
0
0.92600.0047
1
0.05960.0097

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

Most Probable Explanation

The Most Probable Explanation (MPE) is a concept commonly used in the field of probabilistic reasoning and Bayesian statistics. It refers to the set of values for the variables in a given probabilistic model that is the most consistent with (that maximizes the likelihood of) the observed evidence. Essentially, it represents the most likely scenario or explanation given the available evidenceand the underlying probabilistic model.

In [23]:
ie = gum.LazyPropagation(bn)
print(ie.mpe())
<d:1|e:0|c:0|b:0|a:0|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 \n - the configuration {vals[0]} \n - for a log probability of {vals[1]:.6f}"
)
The most probable explanation for observation {'e': 0, 'g': 0} is
 - the configuration <g:0|e:0|d:1|f:0|c:0|b:0|a:0>
 - for a log probability of -2.108913