Learn practical skills, build real-world projects, and advance your career
Created 4 years ago
import numpy as np
import pandas as pd
from pgmpy.models import BayesianModel
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination
import csv
lines=list(csv.reader(open('/home/jss/Documents/datasets/71.csv',"r")))
attributes=lines[0]
heartDisease=pd.read_csv('/home/jss/Documents/datasets/72.csv',names=attributes)
heartDisease=heartDisease.replace('?',np.nan)
print("the dataset names")
print(heartDisease.head())
print("the datatypes and features")
print(heartDisease.dtypes)
model=BayesianModel([('age','trestbps'),('age','fbs'),('sex','trestbps'),
('exang','trestbps'),('trestbps','heartdisease'),('fbs','heartdisease'),
('heartdisease','restecg'),('heartdisease','thalach'),('heartdisease','chol')])
print("learning from CPDs of MaximumLIlelihoodEstimator")
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)
print("Inferencing from Variable elimination")
HeartDisease_infer=VariableElimination(model)
print("probablity when trestbps and fbs is given")
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'trestbps':4,'fbs':0})
print(q['heartdisease'])
the dataset names
age sex cp trestbps chol fbs restecg thalach exang oldpeak \
0 63.0 1.0 1.0 145.0 233.0 1.0 2.0 150.0 0.0 2.3
1 67.0 1.0 4.0 160.0 286.0 0.0 2.0 108.0 1.0 1.5
2 67.0 1.0 4.0 120.0 229.0 0.0 2.0 129.0 1.0 2.6
3 37.0 1.0 3.0 130.0 250.0 0.0 0.0 187.0 0.0 3.5
4 41.0 0.0 2.0 130.0 204.0 0.0 2.0 172.0 0.0 1.4
slope ca thal heartdisease
0 3.0 0.0 6.0 0
1 2.0 3.0 3.0 2
2 2.0 2.0 7.0 1
3 3.0 0.0 3.0 0
4 1.0 0.0 3.0 0
the datatypes and features
age float64
sex float64
cp float64
trestbps float64
chol float64
fbs float64
restecg float64
thalach float64
exang float64
oldpeak float64
slope float64
ca object
thal object
heartdisease int64
dtype: object
learning from CPDs of MaximumLIlelihoodEstimator
Inferencing from Variable elimination
probablity when trestbps and fbs is given
+----------------+---------------------+
| heartdisease | phi(heartdisease) |
+================+=====================+
| heartdisease_0 | 1.0000 |
+----------------+---------------------+
| heartdisease_1 | 0.0000 |
+----------------+---------------------+
| heartdisease_2 | 0.0000 |
+----------------+---------------------+
| heartdisease_3 | 0.0000 |
+----------------+---------------------+
| heartdisease_4 | 0.0000 |
+----------------+---------------------+