Search code examples
pythonmachine-learningbayesianbayesian-networks

BayesianNetwork pomegranate getting keyerror while create BBN


I am trying to create the baysian belief network by using the example given in website https://pomegranate.readthedocs.io/en/latest/BayesianNetwork.html but in given example its for three variable while I am trying to create with two variable, but always getting KeyError: ('A', 'A', 'B'):

from pomegranate import *

guest = DiscreteDistribution({'A': 0.5, 'B':0.5})
prize = DiscreteDistribution({'A': 0.5, 'B': 0.5})
monty = ConditionalProbabilityTable(
        [['A', 'A', 0.5],    
         ['B', 'B', 0.5],
         ['A', 'B', 0.5],
         ['B', 'A', 0.5]], [guest, prize])

s1 = Node(guest, name="guest")
s2 = Node(prize, name="prize")
s3 = Node(monty, name="monty")

model = BayesianNetwork("Monty Hall Problem")
model.add_states(s1, s2, s3)
model.add_edge(s1, s3)
model.add_edge(s2, s3)
model.bake()

It will be great help if someone can help me to resolve this issue, I have tried my best not able to figure out this.


Solution

  • The conditional table, in this problem must contain 3 variables. This is because the conditional probability, in this case is given by P(Monty|Guess,Prize). In another word, in order to achieve a certain state of Monty, a joint probability of guess and prize must be satisfy. Hence, no variable could be taken out of the table(or the conditional probability equation).

    And to solve your problem of using only 2 variable, we need to change the approach to the problem by ignoring either the probability of "Guess" or "Prize", in order to make monty takes in only 1 variable. And the new probabilistic equation will becomes P(Monty|temp).

    from pomegranate import *
    
    temp = DiscreteDistribution({'A': 0.5, 'B':0.5})
    monty = ConditionalProbabilityTable(
            [['A', 'A_prime', 0.5],    
             ['B', 'B_prime', 0.5],
             ['A', 'B_prime', 0.5],
             ['B', 'A_prime', 0.5]], [temp])
    
    s1 = Node(temp, name="temp")
    s2 = Node(monty, name="monty")
    
    model = BayesianNetwork("Not a Monty Hall Problem")
    model.add_states(s1, s2)
    model.add_edge(s1, s2)
    model.bake()