Ai SRK
Ai SRK
No:710721104100
AIM:
To write a python program to implement the Uninformed Breadth First Search
Algorithm.
ALGORITHM:
visited.append(neighbour)
queue.append(neighbour)
print("following is the Breadth first search")
bfs(visited,graph,'5')
OUTPUT:
RESULT:
Thus, the python program for implementation of Uninformed Breadth First
Search Algorithm is executed and its output is verified.
2
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
AIM:
To write a python program to implement the Uninformed Depth First Search
Algorithm.
ALGORITHM:
Step 1: Start the program
Step 2: Put root node ‘r’ on the top of the stack.
Step 3: Examine whether the stack is empty or not
a) If the stack is found to be void, return the failure and stop
b) Else proceed forward.
Step 4: If the first element of the stack is the searched or target node ’t’, return it as
success. Otherwise,
Step 5: Proceed ahead with expansion and removal of first element. The generates of
first element should be placed at the top of stack.
3
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
OUTPUT:
RESULT:
Thus, the python program for implementation of Uninformed Depth First
Search Algorithm is executed and its output is verified.
4
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
AIM:
To write a python program to implement the Informed search [A* search].
ALGORITHM:
5
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
PROGRAM:
class graph:
def __init__(self,adjac_list):
self.adjac_list=adjac_list
def get_neighbours(self,v):
return self.adjac_list[v]
def h(self,n):
H={'A':10,'B':8,'C':5,'D':7,'E':3,'F':6,'G':5,'H':3,'I':1,'J':0}
return H[n]
def a_star_algorithm(self,start,stop):
open_list=set([start])
closed_list=set([])
dist={}
dist[start]=0
prenode={}
prenode[start]=start
while len(open_list)>0:
n=None
for v in open_list:
if n==None or dist[v]+self.h(v) < dist[n]+self.h(n):
n=v
if n==None:
print("Path doesn't exist")
return None
if n==stop:
reconst_path=[]
while prenode[n]!=n:
reconst_path.append(n)
n=prenode[n]
reconst_path.append(start)
reconst_path.reverse()
6
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
adjac_list={'A':[('B',6),('F',3)],'B':[('C',3),('D',2)],'C':[('D',1),('E',5)],'D':[('C',1)
,('E',8)],'E':[('I',5),('J',5)],'F':[('G',1),('H',7)],'G':[('I',3)],'H':[('I',2)],'I':[('E',5),('J'
,3)]}
graph1=graph(adjac_list)
graph1.a_star_algorithm('A','J')
7
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
OUTPUT:
RESULT:
Thus, the python program for implementation of Informed search [A*
search] is executed and its output is verified.
8
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
MEMORY-BOUNDED A*
AIM:
To write a python program to implement the memory-bounded A*.
ALGORITHM:
Step 1: Start the program
Step 2: Get the graph as user input.
Step 3: Create a function A with parameters (Start, goal, path, level, max D).
Step 4: Ger the depth limit as user input.
Step 5: Check for the goal node and return present or not present.
Step 6: Call the function with required parameters.
Step 7: Stop the program and Exit
PROGRAM:
graph={'A':['B','C'],'B':['D','E'],'C':['F','G'],'D':['H','I'],'E':['J','K'],'F':['L','M'],'G':['N
','O'],'H':[],'I':[],'J':[],'K':[],'L':[],'M':[],'N':[],'O':[]}
def MA(start,goal,path,level,maxD):
print("\n current level-->",level)
print("goal node testing for",start)
path.append(start)
if(start==goal):
print("goal test successful")
return path
else:
print("goal node test failed")
if(level==maxD):
return False
print("\n expanding the current node",start)
for child in graph[start]:
if MA(child,goal,path,level+1,maxD):
return path
path.pop()
9
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
return False
start='A'
goal=input("Enter the goal state:")
maxD=int(input("enter the max depth limit:"))
print()
path=list()
res=MA(start,goal,path,1,maxD)
if(res):
print("path to goal node available")
print("path",path)
else:
print("no path available for the goal node in the given depth limit")
10
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
OUTPUT:
RESULT:
Thus, the program to implement memory bounded A* search is executed
and output is verified successfully
11
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
AIM:
To write a python program to implement the naive Bayes models.
ALGORITHM:
Step1 : Start
Step2 : Calculate the prior probability for given class labels
Step3 : Find Likelihood probability with each attribute for each class
Step4 : Put this value in Bayes Formula and calculate posterior probability.
Step5 : See which class has a higher probability, given the input belongs to
the higher probability class.
Step6 : Stop the program
PROGRAM:
# import necessary libarities
import pandas as pd
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
# load data from CSV
data = pd.read_csv('tennisdata.csv')
print("THe first 5 values of data is :\n",data.head())
------------------------------------------------------------------------------------------------
---------------------------
# obtain Train data and Train output
X = data.iloc[:,:-1]
print("\nThe First 5 values of train data is\n",X.head())
------------------------------------------------------------------------------------------------
---------------------------
y = data.iloc[:,-1]
print("\nThe first 5 values of Train output is\n",y.head())
12
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
------------------------------------------------------------------------------------------------
---------------------------
# Convert then in numbers
le_outlook = LabelEncoder()
X.Outlook = le_outlook.fit_transform(X.Outlook)
le_Temperature = LabelEncoder()
X.Temperature = le_Temperature.fit_transform(X.Temperature)
le_Humidity = LabelEncoder()
X.Humidity = le_Humidity.fit_transform(X.Humidity)
le_Windy = LabelEncoder()
X.Windy = le_Windy.fit_transform(X.Windy)
print("\nNow the Train data is :\n",X.head())
------------------------------------------------------------------------------------------------
---------------------------
le_PlayTennis = LabelEncoder()
y = le_PlayTennis.fit_transform(y)
print("\nNow the Train output is\n",y)
------------------------------------------------------------------------------------------------
---------------------------
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y, test_size=0.20)
classifier = GaussianNB()
classifier.fit(X_train,y_train)
from sklearn.metrics import accuracy_score
print("Accuracy is:",accuracy_score(classifier.predict(X_test),y_test))
13
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
OUTPUT:
14
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
RESULT:
Thus, the python program for implementation of naive bayes models is
executed and its output is verified.
15
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
BAYESIAN NETWORKS
AIM:
To write a python program to implement the Bayesian networks.
ALGORITHM:
Step 1 : Start the program
Step 2 : Import the required modules.
Step 3 : Read the csv file and replace the null values.
Step 4 : Build the Bayesian model by passing the appropriate arguments to the
BayesianNetwork()function.
Step 5 : Fill the model by using the maximum likelihood criterion.
Step 6 : Inferencing the network is done by using Variable Elimination () method.
Step 7: The probability is completed, given some of data from the data set.
Step 8: Stop the program and Exit.
PROGRAM:
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
-----------------------------------------------------------------------------------------
----------------------------------
#read Cleveland Heart Disease data
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)
-----------------------------------------------------------------------------------------
----------------------------------
print(heartDisease.head())
-----------------------------------------------------------------------------------------
----------------------------------
#Model Bayesian Network
Model=BayesianModel([('age','trestbps'),('age','fbs'),('sex','trestbps'),('exa
ng','trestbps'),('trestb
ps','heartdisease'),('fbs','heartdisease'),('heartdisease','restecg'),('heartdisea
se','thalach'),('heartd
isease','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 HeartDisease given Age
print('\n 1. Probability of HeartDisease given Age=30')
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'age':28
})
print(q['heartdisease'])
-----------------------------------------------------------------------------------------
----------------------------------
q=HeartDisease_infer.query(variables=['heartdisease'],evidence={'chol':1
00})
print(q['heartdisease'])
OUTPUT:
18
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100
RESULT:
Thus, the python program for implementation of Bayesian network for the
dataset is executed and its output is verified
19