Bayes Nets

To install, run Pkg.add("BayesNets"). Visualization of Network structure is provided by the TikzGraphs package. Installation requirements (e.g., PGF/Tikz and pdf2svg) are provided here.


In [1]:
using BayesNets

Representation


In [2]:
b = BayesNet([:B, :S, :E, :D, :C])
addEdges!(b, [(:B, :E), (:S, :E), (:E, :D), (:E, :C)])


Out[2]:

In [3]:
srand(0) # seed the random number generator to 0
setCPD!(b, :B, CPDs.Bernoulli(0.1))
setCPD!(b, :S, CPDs.Bernoulli(0.5))
setCPD!(b, :E, CPDs.Bernoulli([:B, :S], randBernoulliDict(2)))
setCPD!(b, :D, CPDs.Bernoulli([:E], randBernoulliDict(1)))
setCPD!(b, :C, CPDs.Bernoulli([:E], randBernoulliDict(1)));

In [4]:
parents(b, :E)


Out[4]:
2-element Array{Symbol,1}:
 :B
 :S

In [5]:
domain(b, :C)


Out[5]:
DiscreteDomain(Bool[false,true])

Tables and Operations (for discrete variables)


In [6]:
table(b, :D)


Out[6]:
EDp
1falsefalse0.72
2truefalse0.79
3falsetrue0.28
4truetrue0.21

In [7]:
table(b, :B)


Out[7]:
Bp
1false0.9
2true0.1

In [8]:
bt = table(b, :B)
st = table(b, :S)
et = table(b, :E)
tt = bt * et * st


Out[8]:
BSEp
1falsefalsefalse0.08100000000000003
2falsefalsetrue0.369
3truefalsefalse0.004999999999999999
4truefalsetrue0.045000000000000005
5falsetruefalse0.3735
6falsetruetrue0.07650000000000001
7truetruefalse0.04100000000000001
8truetruetrue0.009

In [9]:
tt = sumout(tt, [:B, :S])


Out[9]:
Ep
1false0.5005000000000001
2true0.4995

Computing Probability of Assignment


In [10]:
a = [
    :B=>0,
    :S=>1,
    :E=>0,
    :D=>1,
    :C=>1
]
prob(b, a)


Out[10]:
0.005229000000000001

Sampling


In [11]:
rand(b)


Out[11]:
Dict{Any,Any} with 5 entries:
  :D => false
  :B => false
  :C => false
  :E => false
  :S => true

In [12]:
srand(0)
randTable(b, numSamples=5)


Out[12]:
BCDES
1falsefalsefalsetruefalse
2truefalsefalsetruetrue
3falsefalsetruetruefalse
4falsefalsefalsefalsefalse
5truefalsetruefalsetrue

In [13]:
srand(0)
t = randTable(b, numSamples=10, consistentWith=[:B=>true, :C=>false])


Out[13]:
BCDES
1truefalsefalsetruetrue
2truefalsetruefalsetrue
3truefalsetruetruetrue

In [14]:
t = randTable(b, numSamples=100, consistentWith=[:B=>true, :C=>false])
estimate(t)


Out[14]:
BCDESp
1truefalsefalsefalsetrue0.5
2truefalsefalsetruefalse0.25
3truefalsefalsetruetrue0.25

Structure Learning


In [15]:
b = BayesNet([:A, :B, :C])
addEdge!(b, :A, :B)
setCPD!(b, :A, CPDs.Bernoulli(0.5))
setCPD!(b, :B, CPDs.Bernoulli(m->(m[:A] ? 0.5 : 0.45)))
setCPD!(b, :C, CPDs.Bernoulli(0.5))
b


Out[15]:

In [16]:
d = randTable(b, numSamples = 5)


Out[16]:
ABC
1falsetruetrue
2truetruetrue
3truetruefalse
4truetruetrue
5truetruefalse

In [17]:
count(b, d)


Out[17]:
Acount
1false1
2true4
ABcount
1falsetrue1
2truetrue4
Ccount
1true3
2false2

In [18]:
logBayesScore(b, d)


Out[18]:
-9.798127036878302

In [19]:
b = BayesNet([:A, :B, :C])


Out[19]:

In [20]:
logBayesScore(b, d)


Out[20]:
-9.287301413112312