When I try to implement MarkovModel using pgmpy, is there a way to fix KeyError?

434 views Asked by At

I'm trying to implement Markov Random Field. Among them, I would like to obtain a value of phi(A|B = 0, C = 1). However, with the evidence option, KeyError: 'B' occurs. I don't know why this happens.

Below is the code.

from pgmpy.inference import VariableElimination
import numpy as np
pf_value = model.get_partition_function()

infer = VariableElimination(model)

AIB0C1_dist = infer.query(['A'], evidence={'B':0, 'C':1}) # phi(A|B = 0, C = 1)
print('phi(A|B =  0, C = 1)')
print(AIB0C1_dist)
P_AIB0C1 = AIB0C1_dist.values/np.sum(AIB0C1_dist.values)
for val in P_AIB0C1:
    print(val, '\n')

And below is the reason for the error.

KeyError                                  Traceback (most recent call last)
<ipython-input-22-1c3cb220fae0> in <module>
     20     print(val, '\n')
     21 
---> 22 AIB0C1_dist = infer.query(['A'],evidence={'B':0, 'C':1}) # phi(A|B = 0, C = 1)
     23 print('phi(A|B =  0, C = 1)')
     24 print(AIB0C1_dist)

~\anaconda3\lib\site-packages\pgmpy\inference\ExactInference.py in query(self, variables, evidence, elimination_order, joint, show_progress)
    254             )
    255 
--> 256         return self._variable_elimination(
    257             variables=variables,
    258             operation="marginalize",

~\anaconda3\lib\site-packages\pgmpy\inference\ExactInference.py in _variable_elimination(self, variables, operation, evidence, elimination_order, joint, show_progress)
    157         eliminated_variables = set()
    158         # Get working factors and elimination order
--> 159         working_factors = self._get_working_factors(evidence)
    160         elimination_order = self._get_elimination_order(
    161             variables, evidence, elimination_order, show_progress=show_progress

~\anaconda3\lib\site-packages\pgmpy\inference\ExactInference.py in _get_working_factors(self, evidence)
     43             for evidence_var in evidence:
     44                 for factor, origin in working_factors[evidence_var]:
---> 45                     factor_reduced = factor.reduce(
     46                         [(evidence_var, evidence[evidence_var])], inplace=False
     47                     )

~\anaconda3\lib\site-packages\pgmpy\factors\discrete\DiscreteFactor.py in reduce(self, values, inplace)
    453         phi.variables = [phi.variables[index] for index in var_index_to_keep]
    454         phi.cardinality = phi.cardinality[var_index_to_keep]
--> 455         phi.del_state_names([var for var, _ in values])
    456 
    457         phi.values = phi.values[tuple(slice_)]

~\anaconda3\lib\site-packages\pgmpy\utils\state_name.py in del_state_names(self, var_list)
     92         """
     93         for var in var_list:
---> 94             del self.state_names[var]
     95             del self.name_to_no[var]
     96             del self.no_to_name[var]

KeyError: 'B'

Is there a way to fix KeyError?

2

There are 2 answers

3
shaw2thefloor On BEST ANSWER

Use self.state_names.get(var,"") instead.

2
prior On

I already added state_names. 'B' is already defined as a key.

from pgmpy.models import MarkovModel
from pgmpy.factors.discrete import DiscreteFactor

model = MarkovModel([('A', 'B'), ('B', 'C'), ('C', 'D'), ('D', 'A')])
factor1 = DiscreteFactor(['A', 'B'], [2, 2], [30, 5, 1, 10], state_names={'A': [0, 1], 'B': [0, 1]})
factor2 = DiscreteFactor(['B', 'C'], [2, 2], [100, 1, 1, 100], state_names={'A': [0, 1], 'C': [0, 1]})
factor3 = DiscreteFactor(['C', 'D'], [2, 2], [1, 100, 100, 1], state_names={'C': [0, 1], 'D': [0, 1]})
factor4 = DiscreteFactor(['D', 'A'], [2, 2], [100, 1, 1, 100], state_names={'D': [0, 1], 'A': [0, 1]})
model.add_factors(factor1, factor2, factor3, factor4)

Code with evidence still has a problem.