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?
Use
self.state_names.get(var,"")
instead.