0% found this document useful (0 votes)
2 views19 pages

Ai SRK

The document outlines the implementation of various search algorithms and machine learning models using Python, including Breadth First Search, Depth First Search, A* Search, Memory-Bounded A*, Naive Bayes Models, and Bayesian Networks. Each section includes the aim, algorithm steps, program code, and results of execution. The implementations demonstrate the application of these algorithms and models on specific datasets, confirming their functionality.

Uploaded by

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

Ai SRK

The document outlines the implementation of various search algorithms and machine learning models using Python, including Breadth First Search, Depth First Search, A* Search, Memory-Bounded A*, Naive Bayes Models, and Bayesian Networks. Each section includes the aim, algorithm steps, program code, and results of execution. The implementations demonstrate the application of these algorithms and models on specific datasets, confirming their functionality.

Uploaded by

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

Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.

No:710721104100

IMPLEMENTATION OF BREADTH FIRST SEARCH

AIM:
To write a python program to implement the Uninformed Breadth 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.
Step 6: Go back to step 2.
Step 7: Call the function bfs() by passing appropriate arguments
Step 8: Stop the program
PROGRAM:
graph={'5':['3','7'],'3':['2','4'],'7':['8'],'2':[],'4':['8'],'8':[]}
visited=[]
queue=[]
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
m=queue.pop(0)
print(m,end=" ")
for neighbour in graph[m]:
if neighbour not in visited:
1
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100

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

IMPLEMENTATION OF DEPTH FIRST SEARCH

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.

Step 6: Go back to step 2.


Step 7: Stop the program and Exit
PROGRAM:
graph={'5':['3','7'],'3':['2','4'],'7':['8'],'2':[],'4':['8'],'8':[]}
visited=set()
def dfs(visited,graph,node):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited,graph,neighbour)
print("following is the depth first search")
dfs(visited,graph,'5')

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

IMPLEMENTATION OF A*(star) SEARCH

AIM:
To write a python program to implement the Informed search [A* search].
ALGORITHM:

Step 1 : The implementation of A* Algorithm involves maintaining two lists- open


and closed.
Step 2 : open contains those nodes that have been evaluated by the heuristic
function but have not been expanded into successors yet.
Step 3 : closed contains those nodes that have already been visited.
Step 4 : Define a list open.
Step 5 : Initially, openconsists solely of a single node, the start node S.
Step 6 : If the list is empty, return failure and exit.
Step 7 : Remove node n with the smallest value of f(n) from open and move it
to list closed.
Step 8 : If node n is a goal state, return success and exit.
Step 9 : Expand node n.
Step 10: If any successor to n is the goal node, return success and the solution by
tracing the path from goal node to S.
Step 11: Otherwise, go to Step-06.
Step 12: For each successor node,
Step 13: Apply the evaluation function f to the node.
Step 14: If the node has not been in either list, add it to open.
Step 15: Go back to Step-02.

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

print("Path found: ",format(reconst_path))


return reconst_path
for (m,weight) in self.get_neighbours(n):
if m not in open_list and m not in closed_list:
open_list.add(m)
prenode[m]=n
dist[m]=dist[n]+weight
else:
if dist[m]>dist[n]+weight:
dist[m]=dist[n]+weight
prenode[m]=n
if m in closed_list:
closed_list.remove(m)
open_list.add(m)
open_list.remove(n)
closed_list.add(n)

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

NAIVE BAYES MODELS

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)
-----------------------------------------------------------------------------------------
----------------------------------

#display the data


print('Few examples from the dataset are given below')
16
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100

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'])
-----------------------------------------------------------------------------------------
----------------------------------

#computing the Probability of HeartDisease given cholesterol


print('\n 2. Probability of HeartDisease given cholesterol=100')
17
Ex No: Date: Dr.N.G.P.Institute Of Technology Reg.No:710721104100

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

You might also like