Aiml Lab (2025)
Aiml Lab (2025)
Aim:
To implementing Breadth-First Search (BFS)
Algorithm:
1. Create an empty queue and enqueue the starting node
2. Mark the starting node as visited
3. While the queue is not empty, dequeue a node from the queue and visit it
4. Enqueue all of its neighbors that have not been visited yet, and mark them as visited
Repeat steps 3-4 until the queue is empty
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = [] # List for visited nodes.
queue = [] #Initialize a queue
def bfs(visited, graph, node): #function for BFS
visited.append(node)
queue.append(node)
while queue: # Creating loop to visit each node
m = queue.pop(0)
print (m, end = " ")
for neighbour in graph[m]:
if neighbour not in visited:
visited.append(neighbour)
queue.append(neighbour) # Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')
Output:
Following is the Breadth-First Search
537248
Result:
Thus the program for BFS is executed successfully and output is verified.
EX.NO:1(B) IMPLEMENTING DEPTH-FIRST SEARCH (DFS)
Aim:
To implementing Depth-First Search (DFS)
Algorithm:
1. Mark the starting node as visited and print it
2. For each adjacent node of the current node that has not been visited, repeat step 1
3. If all adjacent nodes have been visited, backtrack to the previous node and repeat step 2
4. Repeat steps 2-3 until all nodes have been visited
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
visited = set() # Set to keep track of visited nodes of graph.
def dfs(visited, graph, node): #function for dfs
if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
# Driver Code
print("Following is the Depth-First Search")
dfs(visited, graph, '5')
Output:
Following is the Depth-First Search
5
3
2
4
8
7
Result:
Thus the program for DFS is executed successfully and output is verified.
EX.NO:2(A) IMPLEMENTING INFORMED SEARCH ALGORITHM A*
Aim:
To implement informed search algorithm A*
Algorithm:
1. Initialize the starting node with a cost of zero and add it to an open list.
2. While the open list is not empty:
a. Find the node with the lowest cost in the open list and remove it.
b. If this node is the goal node, return the path to this node.
c. Generate all successor nodes of the current node.
d. For each successor node, calculate its cost and add it to the open list.
3. If the open list is empty and the goal node has not been found, then there is no path from the
start node to the goal node.
Program:
from queue import PriorityQueue
v =14
graph =[[] for i in range(v)]
# Function For Implementing Best First Search
# Gives output path having lowest cost
def best_first_search(actual_Src, target, n):
visited =[False] *n
pq =PriorityQueue()
pq.put((0, actual_Src))
visited[actual_Src] =True
while pq.empty() ==False:
u =pq.get()[1]
# Displaying the path having lowest cost
print(u, end=" ")
if u==target:
break
for v, c in graph[u]:
if visited[v] ==False:
visited[v] =True
pq.put((c, v))
print()
# Function for adding edges to graph
def addedge(x, y, cost):
graph[x].append((y, cost))
graph[y].append((x, cost))
# The nodes shown in above example(by alphabets) are
# implemented using integers addedge(x,y,cost);
addedge(0, 1, 3)
addedge(0, 2, 6)
addedge(0, 3, 5)
addedge(1, 4, 9)
addedge(1, 5, 8)
addedge(2, 6, 12)
addedge(2, 7, 14)
addedge(3, 8, 7)
addedge(8, 9, 5)
addedge(8, 10, 6)
addedge(9, 11, 1)
addedge(9, 12, 10)
addedge(9, 13, 2)
source =0
target =9
best_first_search(source, target, v)
Output
013289
Result:
Thus the program for implementing informed search algorithms A* has verified successfully
and output is verified. .
EX.NO:2(B) IMPLEMENTING INFORMED SEARCH ALGORITHM MEMORY
BOUNDED A*
Aim:
To implement informed search algorithm Memory bounded A*
Algorithm:
1. Initialize the starting node with a cost of zero and add it to an open list and a closed list.
2. While the open list is not empty:
a) Find the node with the lowest cost in the open list and remove it.
b) If this node is the goal node, return the path to this node.
c) Generate all successor nodes of the current node.
d) d. For each successor node, calculate its cost and add it to the open list if it is not in
the closed list.
e) e. If the open list is too large, remove the node with the highest cost from the open list
and add it to the closed list.
f) f. Add the current node to the closed list.
3. If the open list is empty and the goal node has not been found, then there is no path from the
start node to the goal node.
Program:
class Node:
def __init__(self, state, parent=None, action=None):
self.state = state
self.parent = parent
self.action = action
while open_list:
if memory_usage(open_list, closed_list) > memory_limit:
prune_memory(open_list, closed_list)
current_node = select_best_node(open_list)
# Return the goal node
if is_goal(current_node):
return current_node
open_list.remove(current_node)
closed_list.append(current_node)
# Example usage
initial_state = (1, 2, 3, 4, 5, 6, 0, 7, 8) # Initial state of the puzzle
if goal_node:
print("Solution found!")
# Print the solution path if needed
while goal_node.parent:
print("Action:", goal_node.action)
print("State:")
print(goal_node.state[:3])
print(goal_node.state[3:6])
print(goal_node.state[6:])
print()
goal_node = goal_node.parent
else:
print("Memory limit exceeded. No solution found within the given memory limit.")
Output:
Case 1 with Memory Limit 1
Memory limit exceeded. No solution found within the given memory limit.
Result:
Thus the program for implementing informed search algorithms Memory bounded A* has
executed successfully and output is verified.
EX.NO:3 IMPLEMENT NAIVE BAYES
Aim:
To write a python program to implement Naive Bayes model.
Algorithm:
1. Load the libraries: import the required libraries such as pandas, numpy, and sklearn.
2. Load the data into a pandas dataframe.
3. Clean and preprocess the data as necessary. For example, you can handle missing values, convert
categorical variables into numerical variables, and normalize the data.
4. Split the data into training and test sets using the train_test_split function from scikit-learn.
5. Train the Gaussian Naive Bayes model using the training data.
6. Evaluate the performance of the model using the test data and the accuracy_score
function from scikit-learn.
7. Finally, you can use the trained model to make predictions on new data.
Program:
import pandas as pd
import numpy as np
import seaborn as sns
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
df=pd.read_csv("data.csv")
df.head()
X = df.drop('buy_computer', axis=1)
y = df['buy_computer']
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=0)
model= GaussianNB()
model.fit(X_train.values, y_train.values)
y_pred = model.predict(X_test.values)
accuracy = accuracy_score(y_test, y_pred)
print("Accuracy:", accuracy)
new_data= np.array([[35, 60000, 1, 100]])
prediction = model.predict(new_data)
print("Prediction:", prediction)
Output:
Accuracy: 0.5
Prediction: [0]
Result:
Thus the Python program for implementing Naive Bayes model was developed and the output
was verified successfully.
Algorithm:
1. Define the variables: The first step in implementing a Bayesian Network is to define the variables that
will be used in the model. Each variable should be clearly defined and its possible states should be
enumerated.
2. Determine the relationships between variables: The next step is to determine the probabilistic
relationships between the variables. This can be done by identifying the causal relationships between the
variables or by using data to estimate the conditional probabilities of each variable given its parents.
3. Construct the Bayesian Network: The Bayesian Network can be constructed by representing the
variables as nodes in a directed acyclic graph (DAG). The edges between the nodes represent the
conditional dependencies between the variables.
4. Assign probabilities to the variables: Once the structure of the Bayesian Network has been defined, the
probabilities of each variable must be assigned. This can be done by using expert knowledge, data, or a
combination of both.
5. Inference: Inference refers to the process of using the Bayesian Network to make predictions or draw
conclusions. This can be done by using various inference algorithms, such as variable elimination or belief
propagation.
6. Learning: Learning refers to the process of updating the probabilities in the Bayesian Network based on
new data. This can be done using various learning algorithms, such as maximum likelihood or Bayesian
learning.
7. Evaluation: The final step in implementing a Bayesian Network is to evaluate its performance. This can
be done by comparing the predictions of the model to actual data and computing various performance
metrics, such as accuracy or precision.
Program:
import numpy as np
import pandas as pd
import csv
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination
heartdisease = pd.read_csv('heart.csv')
heartdisease = heartdisease.replace('?',np.nan)
print('Sample instances from the dataset are given below')
print(heartdisease.head())
print('\n Attributes and datatypes')
print(heartdisease.dtypes)
model=BayesianModel([('age','heartdisease'),('gender','heartdisease'),('exang','heartdisease'),
('cp','heartdisease'),('heartdisease','restecg'),('heartdisease','chol')])
print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartdisease,estimator=MaximumLikelihoodEstimator)
print('\n Inferencing with Bayesian Network:')
Heartdiseasetest_infer = VariableElimination(model)
print('\n 1. Probability of Heartdisease given evidence= restecg')
q1=Heartdiseasetest_infer.query(variables=['heartdisease'],evidence={'restecg':1})
print(q1)
print('\n 2. Probability of Heartdisease given evidence= cp ')
q2=Heartdiseasetest_infer.query(variables=['heartdisease'],evidence={'cp':2})
print(q2)
Output:
Sample instances from the dataset are given below
age gender cp trestbps chol fbs restecg thalach exang oldpeak \
0 63 1 1 145 233 1 2 150 0 2.3
1 67 1 4 160 286 0 2 108 1 1.5
2 67 1 4 120 229 0 2 129 1 2.6
3 37 1 3 130 250 0 0 187 0 3.5
4 41 0 2 130 204 0 2 172 0 1.4
slope ca thal heartdisease
0 3 0 6 0
1 2 3 3 2
2 2 2 7 1
3 3 0 3 0
4 1 0 3 0
| heartdisease(1) | 0.0000 |
+-----------------+---------------------+
| heartdisease(2) | 0.2361 |
+-----------------+---------------------+
| heartdisease(3) | 0.2017 |
+-----------------+---------------------+
| heartdisease(4) | 0.4605 |
+-----------------+---------------------+
Result:
Thus the Python program for implementing Bayesian network was developed and the output
was verified successfully.