Click here to hide/show the list of notebooks.
  pyAgrum on notebooks   pyAgrum jupyter
☰  dynamicBn 
pyAgrum 0.14.2   
generation: 2019-03-05 18:31  

Creative Commons License
This pyAgrum's notebook is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.

dynamic Bayesian Networks with pyAgrum

In [1]:
import pyAgrum as gum
import pyAgrum.lib.notebook as gnb
import pyAgrum.lib.dynamicBN as gdyn
%matplotlib inline

Building a 2TBN

Note the naming convention for a 2TBN : a variable with a name $A$ is present at t=0 with the name $A0$ and at time t as $At$.

In [2]:
twodbn=gum.BayesNet()
a0,b0,c0,at,bt,ct=[twodbn.add(gum.LabelizedVariable(s,s,6)) 
                   for s in ["a0","b0","c0","at","bt","ct"]]
d0,dt=[twodbn.add(gum.LabelizedVariable(s,s,3)) 
       for s in ["d0","dt"]]

twodbn.addArc(a0,b0)

twodbn.addArc(c0,d0)

twodbn.addArc(a0,at)
twodbn.addArc(a0,bt)
twodbn.addArc(a0,dt)
twodbn.addArc(b0,bt)
twodbn.addArc(c0,ct)
twodbn.addArc(d0,ct)
twodbn.addArc(d0,dt)

twodbn.addArc(at,ct)
twodbn.generateCPTs()

gnb.showBN(twodbn)
G a0 a0 b0 b0 a0->b0 at at a0->at bt bt a0->bt dt dt a0->dt b0->bt c0 c0 ct ct c0->ct d0 d0 c0->d0 at->ct d0->ct d0->dt

2TBN

The dbn above actually is a 2TBN and is not correctly shown as a BN. Using the naming convention, it can be shown as a 2TBN.

In [3]:
gdyn.showTimeSlices(twodbn,format="svg")
G cluster_0 Time slice 0 cluster_t Time slice t a0 a b0 b a0->b0 at a a0->at bt b a0->bt dt d a0->dt c0 c b0->bt d0 d c0->d0 ct c c0->ct d0->ct d0->dt at->ct

unrolling 2TBN

A dBN is 'unrolled' using the 2TBN and the time period size. For a couple $a_0$,$a_t$ in the 2TBN, the unrolled dBN will include $a_0, a_1, \cdots, a_{T-1}$

In [4]:
T=5

dbn=gdyn.unroll2TBN(twodbn,T)
gdyn.showTimeSlices(dbn,size="10")
G cluster_0 Time slice 0 cluster_1 Time slice 1 cluster_2 Time slice 2 cluster_3 Time slice 3 cluster_4 Time slice 4 a0 a b0 b a0->b0 a1 a a0->a1 b1 b a0->b1 d1 d a0->d1 c0 c b0->b1 d0 d c0->d0 c1 c c0->c1 d0->c1 d0->d1 a1->c1 a2 a a1->a2 b2 b a1->b2 d2 d a1->d2 b1->b2 c2 c c1->c2 d1->c2 d1->d2 a2->c2 a3 a a2->a3 b3 b a2->b3 d3 d a2->d3 b2->b3 c3 c c2->c3 d2->c3 d2->d3 a3->c3 a4 a a3->a4 b4 b a3->b4 d4 d a3->d4 b3->b4 c4 c c3->c4 d3->c4 d3->d4 a4->c4

We can infer on bn just as on a normal bn. Following the naming convention in 2TBN, the variables in a dbN are named using the convention $a_i$ where $i$ is the number of their time slice.

In [5]:
%config InlineBackend.figure_format = 'svg'
for i in range(T):
    gnb.showPosterior(dbn,target="d{}".format(i),evs={})

dynamic inference : following variables

gdyn.plotFollow directly ask for the 2TBN, unroll it and add evidence evs. Then it shows the dynamic of variable $a$ for instance by plotting $a_0,a_1,\cdots,a_{T-1}$.

In [6]:
import matplotlib.pyplot as plt

plt.rcParams['figure.figsize'] = (15, 4)
gdyn.plotFollow(["a","b","c","d"],twodbn,T=51,evs={'a9':2,'a30':0,'c14':0,'b40':0,'c50':3})  
In [ ]: