# -*- coding: utf-8 -*-
"""P9-1Bayesian Network.ipynb

Automatically generated by Colab.

Original file is located at
    https://colab.research.google.com/drive/1K14g_pZINxfYSFzX4UtRfyawHgOG9TI1
"""

pip install pgmpy

import numpy as np
import csv
import pandas as pd
from pgmpy.models import BayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

#read Cleveland Heart Disease data
heartDisease = pd.read_csv('/content/heart (1).csv')
heartDisease = heartDisease.replace('?',np.nan)

#display the data
print('Few examples from the dataset are given below')
print(heartDisease.head())

#Model Bayesian Network
#ImportError: BayesianNetwork has been deprecated. Please use DiscreteBayesianNetwork instead.

model=DiscreteBayesianNetwork([('age','target'),('sex','target'),
                       ('exang','target'),('cp','target'),
                       ('target','restecg'),('target','chol')])

#Learning CPDs using Maximum Likelihood Estimators
print('\n Learning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

# Inferencing with Bayesian Network
print('\n Inferencing with Bayesian Network:')
HeartDisease_infer = VariableElimination(model)

#computing the Probability of RestEcg given HeartDisease is present
print('\n 1. Probability of HeartDisease given RestEcg')
q=HeartDisease_infer.query(variables=['restecg'],evidence ={'target':1}, joint=False)
print(q['restecg'])

#computing the Probability of HeartDisease given Chestpain
print('\n 2. Probability of HeartDisease given Chestpain')
q=HeartDisease_infer.query(variables=['target'],evidence ={'cp':3}, joint=False)
print(q['target'])

import pandas as pd
import numpy as np
from pgmpy.models import DiscreteBayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

# Load dataset
data = pd.read_csv('/content/heart (1).csv')
data = data.replace('?', np.nan)

print("Sample data:")
print(data.head())

# Define the Bayesian Network structure using DiscreteBayesianNetwork
model = DiscreteBayesianNetwork([
    ('age', 'target'),
    ('sex', 'target'),
    ('exang', 'target'),
    ('cp', 'target'),
    ('target', 'restecg'),
    ('target', 'chol')
])

# Fit the model
model.fit(data, estimator=MaximumLikelihoodEstimator)
print("\nModel training complete using Maximum Likelihood Estimation")

# Inference
infer = VariableElimination(model)

# Query 1: Probability of RestEcg given HeartDisease
print("\n1. Probability of RestEcg given HeartDisease:")
q1 = infer.query(variables=['restecg'], evidence={'target': 1})
print(q1)

# Query 2: Probability of HeartDisease given Chest Pain (cp=3)
print("\n2. Probability of HeartDisease given Chest Pain:")
q2 = infer.query(variables=['target'], evidence={'cp': 3})
print(q2)

