0% found this document useful (0 votes)
23 views8 pages

ML 7th and 10th Program

The document contains two experiments: one on Bayesian Networks using medical data to predict heart disease and another on Locally Weighted Regression (LWR) for data fitting. The Bayesian Network model is built using various health-related variables and allows user input to infer the probability of heart disease. The LWR section includes a function to compute weights based on a Gaussian kernel and visualizes the regression fit on sample data.

Uploaded by

b.nandhu2810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views8 pages

ML 7th and 10th Program

The document contains two experiments: one on Bayesian Networks using medical data to predict heart disease and another on Locally Weighted Regression (LWR) for data fitting. The Bayesian Network model is built using various health-related variables and allows user input to infer the probability of heart disease. The LWR section includes a function to compute weights based on a Gaussian kernel and visualizes the regression fit on sample data.

Uploaded by

b.nandhu2810
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 8

Exp No: 7 Bayesian Network Considerin

Medical Data Date:

Program:
import pandas as pd
from pgmpy.models import BayesianNetwork
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.inference import VariableElimination

# Load the dataset


data = pd.read_csv("heartdisease.csv")
heart_disease = pd.DataFrame(data)
print(heart_disease)

# Define the Bayesian Network model structure


model = BayesianNetwork([
('age', 'Lifestyle'),
('Gender', 'Lifestyle'),
('Family', 'heartdisease'),
('diet', 'cholestrol'),
('Lifestyle', 'diet'),
('cholestrol', 'heartdisease'),
('diet', 'cholestrol')
])

# Fit the model to the data using MaximumLikelihoodEstimator


model.fit(heart_disease, estimator=MaximumLikelihoodEstimator)

# Perform inference using Variable Elimination


HeartDisease_infer = VariableElimination(model)

# Prompt the user for input and ensure it's a valid integer
def get_input(prompt, valid_choices):
while True:
try:
user_input = int(input(prompt))
if user_input not in valid_choices:
print(f"Please enter a valid value from {valid_choices}")
else:
return user_input
except ValueError:
print("Invalid input. Please enter a number.")

# Display options to the user


print('For age Enter { SuperSeniorCitizen:0, SeniorCitizen:1,
MiddleAged:2, Youth:3, Teen:4 }')
print('For Gender Enter { Male:0, Female:1 }')
print('For Family History Enter { yes:1, No:0 }')
print('For diet Enter { High:0, Medium:1 }')
print('For lifeStyle Enter { Athlete:0, Active:1, Moderate:2,
Sedentary:3 }')
print('For cholesterol Enter { High:0, BorderLine:1, Normal:2 }')

# Get user input for each variable


age = get_input('Enter age :', [0, 1, 2, 3, 4])
gender = get_input('Enter Gender :', [0, 1])
family = get_input('Enter Family history :', [0, 1])
diet = get_input('Enter diet :', [0, 1])
lifestyle = get_input('Enter Lifestyle :', [0, 1, 2, 3])
cholestrol = get_input('Enter cholestrol :', [0, 1, 2])

# Perform the query with the provided evidence


q = HeartDisease_infer.query(variables=['heartdisease'], evidence={
'age': age,
'Gender': gender,
'Family': family,
'diet': diet,
'Lifestyle': lifestyle,
'cholestrol': cholestrol
})

# Access the values (probabilities) for the 'heartdisease' variable


print("Probability of heart disease:")
print(q.values) # This will show the probability distribution for
'heartdisease'

# To get the most likely outcome:


heart_disease_outcome = q.values.argmax()
outcome_label = ['No Disease', 'Disease'] # This depends on how your
model is structured (0 -> No, 1 -> Yes)
print(f"The most likely outcome for heart disease is:
{outcome_label[heart_disease_outcome]}")

#csv input eg:- heartdiseas.csv


age,Gender,Family,diet,Lifestyle,cholestrol,heartdisease
0,0,1,1,3,0,1
0,1,1,1,3,0,1
1,0,0,0,2,1,1
4,0,1,1,3,2,0
3,1,1,0,0,2,0
2,0,1,1,1,0,1
4,0,1,0,2,0,1
0,0,1,1,3,0,1
3,1,1,0,0,2,0
1,1,0,0,0,2,1
4,1,0,1,2,0,1
4,0,1,1,3,2,0
2,1,0,0,0,0,0
2,0,1,1,1,0,1
3,1,1,0,0,1,0
0,0,1,0,0,2,1
1,1,0,1,2,1,1
3,1,1,1,0,1,0
4,0,1,1,3,2,0

Output:
For age Enter { SuperSeniorCitizen:0, SeniorCitizen:1, MiddleAged:2,
Youth:3, Teen:4 }
For Gender Enter { Male:0, Female:1 }
For Family History Enter { yes:1, No:0 }
For diet Enter { High:0, Medium:1 }
For lifeStyle Enter { Athlete:0, Active:1, Moderate:2, Sedentary:3 }
For cholesterol Enter { High:0, BorderLine:1, Normal:2 }
Enter age :4
Enter Gender :1
Enter Family history :0
Enter diet :1
Enter Lifestyle :1
Enter cholestrol :1
Probability of heart disease:
[0. 1.]
The most likely outcome for heart disease is: Disease

---------------------------------------------------------------------------------------------

Exp No: 10 Locally Weighted Regression


Date:

Program:
import numpy as np
import matplotlib.pyplot as plt
def gaussian_kernel(x, x0, tau):
return np.exp(-np.sum((x - x0)**2) / (2 * tau**2))
def compute_weights(X, x0, tau):
m = X.shape[0]
weights = np.zeros(m)
for i in range(m):
weights[i] = gaussian_kernel(X[i], x0, tau)
return np.diag(weights)
def locally_weighted_regression(X, y, x0, tau):
X_b = np.c_[np.ones((X.shape[0], 1)), X] # Add intercept term
x0_b = np.r_[1, x0] # Add intercept term to the query point
W = compute_weights(X, x0, tau)
theta = np.linalg.inv(X_b.T @ W @ X_b) @ (X_b.T @ W @ y)
return x0_b @ theta
def plot_lwr(X, y, tau):
X_range = np.linspace(np.min(X), np.max(X), 300)
y_pred = [locally_weighted_regression(X, y, x0, tau) for x0 in X_range]

plt.scatter(X, y, color='blue', label='Data points')


plt.plot(X_range, y_pred, color='red', label='LWR fit')
plt.xlabel('X')
plt.ylabel('y')
plt.title(f'Locally Weighted Regression (tau={tau})')
plt.legend()
plt.show()
# Sample data
X = np.array([[1], [2], [3], [4], [5]])
y = np.array([1, 3, 2, 5, 4])
# Plot LWR
plot_lwr(X, y, tau=0.5)

Output:

You might also like