I have a Bayesian algorithm program to be executed, I am using python 3
import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)
print('Few examples from the dataset are given below')
print(heartDisease.head())
model = BayesianModel([('age','trestbps'),('age','fbs'),('sex','trestbps'),('exang','trestbps'),('trestbps','heartdisease'),('fbs','heartdisease'),('heartdisease','restecg'),('heartdisease','thalach'),('heartdisease','chol')])
print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)
print('\n Inferencing with Bayesian Network:')
HeartDisease_infer = VariableElimination(model)
print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])
print('\n 2. Probability of HeartDisease given cholesterol=100')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'chol':100})
print(q['heartdisease'])
the error that i have recieved when i run my Bayesian network program is:
TypeError Traceback (most recent call last)
<ipython-input-7-84a6b48627b2> in <module>
23 print('\n 1. Probability of HeartDisease given Age=28')
24 q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
---> 25 print(q['heartdisease'])
26
27 print('\n 2. Probability of HeartDisease given cholesterol=100')
TypeError: 'DiscreteFactor' object is not subscriptable
So far I haven't seen this exact error here on stackoverflow. Can anyone explain why I am getting this error?
After trying to solve the error I came up with the solution.
print('\n 1. Probability of HeartDisease given Age=28')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28})
print(q['heartdisease'])
print(q['heartdisesase']
over in this part of the code snippet I just removed ['heartdisease']. here the output was actually trying to store itself into a array object, however the output actually is in special table format that cant be stored into an array so printing the actual answer 'q' gives you a required result.
print(q)
this get's your job done..!!