Lab Manual For Aiml
Lab Manual For Aiml
bounded A*)
3. Implement naive Bayes models
1
Ex. No. 1.A UNINFORMED SEARCH ALGORITHM - BFS
Date:
Aim:
To write a Python program to implement Breadth First Search (BFS).
Algorithm:
Step 1. Start
Step 2. Put any one of the graph’s vertices at the back of the queue.
Step 3. Take the front item of the queue and add it to the visited list.
Step 4. Create a list of that vertex's adjacent nodes. Add those which are not within the
visited list to the rear of the queue.
Step 5. Continue steps 3 and 4 till the queue is
empty. Step 6. Stop
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Breadth-First
Search") bfs(visited, graph, '5') # function
calling
2
Result:
Thus the Python program to implement Breadth First Search (BFS) was developed
successfully.
3
Ex. No.1.B UNINFORMED SEARCH ALGORITHM -
DFS
Date:
Aim:
To write a Python program to implement Depth First Search (DFS).
Algorithm:
Step 1.Start
Step 2.Put any one of the graph's vertex on top of the stack.
Step 3.After that take the top item of the stack and add it to the visited list of the vertex.
Step 4.Next, create a list of that adjacent node of the vertex. Add the ones which aren't in the
visited list of vertexes to the top of the stack.
Step 5.Repeat steps 3 and 4 until the stack is
empty. Step 6.Stop
Program:
graph = {
'5' : ['3','7'],
'3' : ['2', '4'],
'7' : ['8'],
'2' : [],
'4' : ['8'],
'8' : []
}
# Driver Code
print("Following is the Depth-First
Search") dfs(visited, graph, '5')
4
Result:
Thus the Python program to implement Depth First Search (DFS) was developed
successfully.
5
Ex. No.2. A INFORMED SEARCH
ALGORITHM
Date:
A* SEARCH
Aim:
To write a Python program to implement A* search algorithm.
Algorithm:
Step 1: Create a priority queue and push the starting node onto the queue.Initialize
minimum value (min_index) to location 0.
Step 2: Create a set to store the visited nodes.
Step 3: Repeat the following steps until the queue is empty:
3.1: Pop the node with the lowest cost + heuristic from the queue.
3.2: If the current node is the goal, return the path to the goal.
3.3 : If the current node has already been visited, skip it.
3.4: Mark the current node as visited.
: Expand the current node and add its neighbors to the queue.
Step 4: If the queue is empty and the goal has not been found, return None (no path found).
Step 5: Stop
Program:
import heapq
class Node:
def init (self, state, parent, cost,
heuristic): self.state = state
self.parent = parent
self.cost = cost
self.heuristic =
heuristic
while heap:
(cost, current) = heapq.heappop(heap)
if current.state ==
goal: path = []
while current is not None:
path.append(current.state)
6
current = current.parent
# Return reversed path
return path[::-1]
if current.state in
visited: continue
visited.add(current.state)
graph = {
'A': {'B': 1, 'D': 3},
'B': {'A': 1, 'C': 2, 'D': 4},
'C': {'B': 2, 'D': 5, 'E': 2},
'D': {'A': 3, 'B': 4, 'C': 5, 'E': 3},
'E': {'C': 2, 'D': 3}
}
start = 'A'
goal = 'E'
Result:
Thus the python program for A* Search was developed and the output was verified
successfully.
7
Ex. No.2.B INFORMED SEARCH
ALGORITHM
Date:
MEMORY-BOUNDED A*
Aim:
To write a Python program to implement memory- bounded A* search algorithm.
Algorithm:
Step 1: Create a priority queue and push the starting node onto the queue.
Step 2: Create a set to store the visited nodes.
Step 3: Set a counter to keep track of the number of nodes expanded.
Step 4: Repeat the following steps until the queue is empty or the node counter exceeds the
max_nodes:
4.1: Pop the node with the lowest cost + heuristic from the queue.
4.2: If the current node is the goal, return the path to the goal.
4.3 : If the current node has already been visited, skip
it. 4.4: Mark the current node as visited.
: Increment the node counter.
: Expand the current node and add its neighbors to the queue.
Step 5: If the queue is empty and the goal has not been found, return None (no path found).
Step 6: Stop
Program:
import heapq
class Node:
def init (self, state, parent, cost,
heuristic): self.state = state
self.parent = parent
self.cost = cost
self.heuristic =
heuristic
visited = set()
node_counter = 0
8
if current.state == goal:
9
path = []
while current is not None:
path.append(current.state)
current = current.parent
return path[::-1]
if current.state in
visited: continue
visited.add(current.state)
node_counter += 1
return None
# Example usage
start = 'A'
goal =
'D'
max_nodes = 10
Result:
Thus the python program for memory-bounded A* search was developed and the
output was verified successfully.
10
Ex. No.3 NAIVE BAYES MODEL
Date:
Aim:
To write a python program to implement Naïve Bayes model.
Algorithm:
Step 1. Load the libraries: import the required libraries such as pandas, numpy, and
sklearn.
Step 2. Load the data into a pandas dataframe.
Step 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.
Step 4. Split the data into training and test sets using the train_test_split function from
scikit-learn.
Step 5. Train the Gaussian Naive Bayes model using the training data.
Step 6. Evaluate the performance of the model using the test data and the accuracy_score
function from scikit-learn.
Step 7. Finally, you can use the trained model to make predictions on new data.
Program:
import pandas as
pd import numpy as
np
from sklearn.naive_bayes import GaussianNB
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
11
# Make a prediction on new data
new_data = np.array([[35, 60000, 1, 100]])
prediction = model.predict(new_data)
print("Prediction:", prediction)
age,income,student,credit_rating,buy_computer
30,45000,0,10,0
32,54000,0,100,0
35,61000,1,10,1
40,65000,0,50,1
45,75000,0,100,0
Result:
Thus the Python program for implementing Naïve Bayes model was developed and
the output was verified successfully.
12
Ex. No.4 BAYESIAN NETWORKS
Date:
Aim:
To write a python program to implement a Bayesian network for the Monty Hall
problem.
Algorithm:
Step 1. Start by importing the required libraries such as math and pomegranate.
Step 2. Define the discrete probability distribution for the guest's initial choice of
door Step 3. Define the discrete probability distribution for the prize door
Step 4. Define the conditional probability table for the door that Monty picks based on the
guest's choice and the prize door
Step 5. Create State objects for the guest, prize, and Monty's choice
Step 6. Create a Bayesian Network object and add the states and edges between
them Step 7. Bake the network to prepare for inference
Step 8. Use the predict_proba method to calculate the beliefs for a given set of
evidence Step 9. Display the beliefs for each state as a string.
Step 10. Stop
Program:
import math
from pomegranate import *
# The door Monty picks, depends on the choice of the guest and the prize door
monty = ConditionalProbabilityTable(
[['A', 'A', 'A', 0.0],
['A', 'A', 'B', 0.5],
['A', 'A', 'C', 0.5],
['A', 'B', 'A', 0.0],
13
['A', 'B', 'B', 0.0],
['A', 'B', 'C', 1.0],
['A', 'C', 'A', 0.0],
['A', 'C', 'B', 1.0],
['A', 'C', 'C', 0.0],
['B', 'A', 'A', 0.0],
['B', 'A', 'B', 0.0],
['B', 'A', 'C', 1.0],
['B', 'B', 'A', 0.5],
['B', 'B', 'B', 0.0],
['B', 'B', 'C', 0.5],
['B', 'C', 'A', 1.0],
['B', 'C', 'B', 0.0],
['B', 'C', 'C', 0.0],
['C', 'A', 'A', 0.0],
['C', 'A', 'B', 1.0],
['C', 'A', 'C', 0.0],
['C', 'B', 'A', 1.0],
['C', 'B', 'B', 0.0],
['C', 'B', 'C', 0.0],
['C', 'C', 'A', 0.5],
['C', 'C', 'B', 0.5],
['C', 'C', 'C', 0.0]], [guest, prize])
d1 = State(guest, name="guest")
d2 = State(prize, name="prize")
d3 = State(monty,
name="monty")
14
Result:
Thus, the Python program for implementing Bayesian Networks was successfully
developed and the output was verified.
15
Ex. No. 5
REGRESSION MODEL
Date:
Aim:
To write a Python program to build Regression models
Algorithm:
Program:
import numpy as
np import pandas
as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
16
# make predictions on new data
new_data = pd.DataFrame({'waist': [80]})
predicted_weight =
model.predict(new_data[['waist']])
print("Predicted weight for new waist value:", int(predicted_weight))
Result:
Thus the Python program to build a simple linear Regression model was developed
successfully.
17
Ex. No. 6 DECISION TREE AND RANDOM
FOREST
Date:
Aim:
To write a Python program to build decision tree and random forest.
Algorithm:
Program:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from sklearn.tree import DecisionTreeClassifier, plot_tree
from sklearn.ensemble import RandomForestClassifier
18
# visualize the decision tree
plt.figure(figsize=(10,6))
plot_tree(tree, filled=True)
plt.title("Decision Tree")
plt.show()
# calculate and print the accuracy of decision tree and random forest
print("Accuracy of decision tree: {:.2f}".format(tree.score(X_test, y_test)))
print("Accuracy of random forest: {:.2f}".format(rf.score(X_test, y_test)))
Sample flowers.csv
Sepal_length,Sepal_width,Petal_length,Petal_width,Flower
4.6,3.2,1.4,0.2,Rose
5.3,3.7,1.5,0.2,Rose
5,3.3,1.4,0.2,Rose
7,3.2,4.7,1.4,Jasmin
6.4,3.2,4.5,1.5,Jasmin
7.1,3,5.9,2.1,Lotus
6.3,2.9,5.6,1.8,Lotus
Result:
Thus the Python program to build decision tree and random forest was developed
successfully.
19
Ex. No.7 SVM MODELS
Date:
Aim:
To write a Python program to build SVM model.
Algorithm:
Step 1.Import the necessary libraries (matplotlib.pyplot, numpy, and svm from sklearn).
Step 2.Define the features (X) and labels (y) for the fruit dataset.
Step 3.Create an SVM classifier with a linear kernel using svm.SVC(kernel='linear').
Step 4.Train the classifier on the fruit data using clf.fit(X, y).
Step 5.Plot the fruits and decision boundary using plt.scatter(X[:, 0], X[:, 1], c=colors),
where colors is a list of colors assigned to each fruit based on its label.
Step 6.Create a meshgrid to evaluate the decision function using
np.meshgrid(np.linspace(xlim[0], xlim[1], 100), np.linspace(ylim[0], ylim[1], 100)).
Step 7.Use the decision function to create a contour plot of the decision boundary and
margins using ax.contour(xx, yy, Z, colors='k', levels=[-1, 0, 1], alpha=0.5,
linestyles=['--', '-', '--']).
Step 8.Show the plot using plt.show().
Program:
20
ax.set_ylabel('Color')
xlim = ax.get_xlim()
ylim = ax.get_ylim()
Result:
Thus, the Python program to build an SVM model was developed, and the output was
successfully verified.
21
EX NO.: 8
Implement EM for Bayesian Networfis
DATE :
Aim:
To write a python program to implement EM for Bayesian Networfis.
Algorithm:
1. Start with a Bayesian network that has some variables that are not directly observed.
For example, suppose we have a Bayesian network with variables A, B, C, and D,
where A and D are observed and B and C are latent.
2. Initialize the parameters of the network. This includes the conditional
probabilities for each variable given its parents, as well as the prior
probabilities for the root variables.
3. E-step: Compute the expected sufficient statistics for the latent variables. This
involves computing the posterior probability distribution over the latent variables
given the observed data and the current parameter estimates. This can be done using
the forward-backward algorithm or the belief propagation algorithm.
4. M-step: Update the parameter estimates using the expected sufficient statistics
computed in step 3. This involves maximizing the likelihood of the data with respect to
the parameters of the network, given the expected sufficient statistics.
5. Repeat steps 3-4 until convergence. Convergence can be measured by monitoring
the change in the log-likelihood of the data, or by monitoring the change in the
parameter estimates.
Program :
import numpy as np
import math
22
probabilities = {
'A': np.array([0.6, 0.4]),
'B': np.array([[0.3, 0.7], [0.9, 0.1]]),
'C': np.array([[0.2, 0.8], [0.7, 0.3]]),
'D': np.array([[[0.1, 0.9], [0.6, 0.4]], [[0.7, 0.3], [0.8, 0.2]]])
}
Compute the posterior probability distribution over the latent variables given the
observed data
joint_prob = np.ones(probabilities['A'].shape)
for node in nodes:
if node in data:
joint_prob *= probabilities[node][data[node]]
else:
parent_probs = [probabilities[parent][data[parent]] for parent in
parents[node]]
joint_prob *= probabilities[node][tuple(parent_probs)]
posterior = joint_prob / np.sum(joint_prob)
return probabilities
Result :
Thus the Python program to Implement EM for Bayesian Networks was
developed successfully.
24
EX NO.: 9
Build Simple NN Models
DATE :
Aim:
To write a python program to build simple NN models.
Algorithm:
Program:
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
25
model.add(Dense(4, input_dim=2, activation='relu')) model.add(Dense(1,
activation='sigmoid'))
Sequential()
Result:
Thus the Python program to build simple NN Models was developed
successfully.
26
EX NO.: 10
Deep Learning NN Models
DATE :
Aim:
To write a python program to implement deep learning of NN models.
Algorithm:
1. Import the necessary libraries, such as numpy and keras.
2. Load or generate your dataset. This can be done using numpy or any other data
manipulation library.
3. Preprocess your data by performing any necessary normalization, scaling, or other
transformations.
4. Define your neural network architecture using the Keras Sequential API. Add
layers to the model using the add() method, specifying the number of units,
activation function, and input dimensions for each layer.
5. Compile your model using the compile() method. Specify the loss function,
optimizer, and any evaluation metrics you want to use.
6. Train your model using the fit() method. Specify the training data, validation
data, batch size, and number of epochs.
7. Evaluate your model using the evaluate() method. This will give you the loss and
accuracy metrics on the test set.
8. Use your trained model to make predictions on new data using the predict()
method.
Program:
Import necessary libraries
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
27
Compile the model
model.compile(loss='categorical_crossentropy',
optimizer='sgd',
metrics=['accuracy'])
Result:
Thus the Python program to implement deep learning of NN Models was
developed successfully.
28