I was trying to compute the MAP Query over the variables given the evidence.
from pgmpy.inference import VariableElimination
from pgmpy.models import BayesianModel
import numpy as np
import pandas as pd
values = pd.DataFrame(np.random.randint(low=0, high=2, size=(1000, 5)),
columns=['A', 'B', 'C', 'D', 'E'])
model = BayesianModel([('A', 'B'), ('C', 'B'), ('C', 'D'), ('B', 'E')])
model.fit(values)
inference = VariableElimination(model)
phi_query = inference.map_query(['A', 'B'], evidence= {'B':1})
which gives me an error :
Finding Elimination Order: : 100%|██████████| 3/3 [00:00<00:00, 651.66it/s]
Eliminating: E: 100%|██████████| 3/3 [00:00<00:00, 309.08it/s]
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-22-0e47cda916c1> in <module>()
8 model.fit(values)
9 inference = VariableElimination(model)
---> 10 phi_query = inference.map_query(['A', 'B'], evidence= {'B':1})
/usr/local/lib/python3.6/dist-packages/pgmpy/inference/ExactInference.py in map_query(self, variables, evidence, elimination_order, show_progress)
360 return_dict = {}
361 for var in variables:
--> 362 return_dict[var] = map_query_results[var]
363 return return_dict
364
KeyError: 'B'
According to the documentation :
Parameters variables (list) – list of variables over which we want to compute the max-marginal.
evidence (dict) – a dict key, value pair as {var: state_of_var_observed} None if no evidence
elimination_order (list) – order of variable eliminations (if nothing is provided) order is computed automatically
So where am I going wrong, why am I getting this error?
EDIT : pgmpy version : 0.1.9
The problem is that you are passing the evidence variable also in the query variables and there aren't any checks to handle this case properly. You already know the state for
B
as1
since it is the evidence, you need to just query forA
as: