AI &MI LAB
AI &MI LAB
LAB MANUAL
Regulation : 2021
Course Outcomes
AIM
Algorithm:
1. Create an empty queue (for BFS) add the initial state to it.
RESULT
Thus the python program to implement Breadth First Search was done successfully.
EX.NO : 1B UNINFORMED SEARCH STRATEGIES
AIM
Algorithm:
1. Create an empty stack (for DFS) and add the initial state to it.
Remove the first state from the last state from the stack.
If the state is the goal state, return the path from the initial state to the current
state.
Otherwise, generate all possible actions from the current state.
For each action, generate the resulting state and check if it has been visited
before.
If it has not been visited, add it to the stack and mark it as visited.
4. If the stack is empty and no goal state has been found, return failure.
GRAPH
PROGRAM
OUTPUT
RESULT
Thus the python program to implement Depth First Search was done successfully.
EX.NO : 2A INFORMED SEARCH STRATEGIES
(A* SEARCH)
AIM
Algorithm:
2. Add the initial state to the open set with a cost of 0 and an estimated total cost (f-score) of the
heuristic value of the initial state.
Choose the state with the lowest f-score from the open set.
If this state is the goal state, return the path from the initial state to this state.
Generate all possible actions from the current state.
For each action, generate the resulting state and compute the cost to get to that
state by adding the cost of the current state plus the cost of the action.
If the resulting state is not in the closed set or the new cost to get there is less than
the old cost, update its cost and estimated total cost in the open set and add it to
the open set.
Add the current state to the closed set.
4.If the open set is empty and no goal state has been found, return failure.
GRAPH
PROGRAM
OUTPUT
RESULT
Aim:
Aim is to write a program in python to solve problems by using Implementation of
Algorithm:
2. Add the initial state to the open set with a cost of 0 and an estimated total cost
a. Choose the state with the lowest f-score from the open set.
b. If this state is the goal state, return the path from the initial state to this state.
d. For each action, generate the resulting state and compute the cost to get to that state by
adding the cost of the current state plus the cost of the action.
e. If the resulting state is not in the closed set or the new cost to get there is less than the old
cost, update its cost and estimated total cost in the open set and add it to the open set.
g. If the size of the closed set plus the open set exceeds the maximum memory usage, remove
the state with the highest estimated total cost from the closed set and add it back to the open
set.
4. If the open set is empty and no goal state has been found, return failure.
Program :
import sys
frontier = PriorityQueue()
frontier.put((0, start_node))
explored = set()
total_cost = {start_node: 0}
return None
_, current_node = frontier.get()
if current_node == goal_node:
path = []
path.append(current_node)
current_node = current_node.parent
path.append(start_node)
path.reverse()
return path
explored.add(current_node)
continue
total_cost[child_node] = new_cost
frontier.put((priority, child_node))
return None
class Node:
self.state = state
self.parent = parent
self.cost = 1
def __hash__(self):
return hash(self.state)
def children(self):
children = []
children.append((child_node, child_node.cost))
return children
# Example usage
start_node = Node(1)
goal_node = Node(10)
if path is None:
else:
OUTPUT :
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No:3A Implement naive Bayes models
(Gaussian Naive Bayes)
Aim:
Aim is to write a program in python to solve problems by using Implement naive Bayes
Algorithm:
Input:
Output:
Steps:
1. Calculate the prior probabilities of each class in the training dataset, i.e., P(Y = c), where c is the
class label.
2. Calculate the mean and variance of each feature for each class in the training dataset.
3. For each test instance in X_test, calculate the posterior probability of each class c, i.e., P(Y = c
are the mean and variance of feature values for class c, respectively.
4. For each test instance in X_test, assign the class label with the highest posterior probability as
data = load_iris()
X, y = data.data, data.target
gnb = GaussianNB()
gnb.fit(X_train, y_train)
y_pred = gnb.predict(X_test)
# Print results
print("Accuracy:", accuracy)
Output :
Accuracy: 1.0
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No:3b Implement naive Bayes models
(Multinomial Naive Bayes)
Aim:
Aim is to write a program in python to solve problems by using Implement naive Bayes
Algorithm:
1. Convert the training dataset into a frequency table where each row represents a
document, and each column represents a word in the vocabulary. The values in the table
2. Calculate the prior probabilities of each class label by dividing the number of documents
3. Calculate the conditional probabilities of each word given each class label. This involves
calculating the frequency of each word in each class and dividing it by the total number
4. For each document in the test dataset, calculate the posterior probability of each class
6. where word1, word2, ..., wordn are the words in the document and P(word | class_label)
7. Predict the class label with the highest posterior probability for each document in the test
dataset.
vectorizer = CountVectorizer()
# Fit the vectorizer to the training data and transform the data
train_features = vectorizer.fit_transform(train_data)
# Create a Multinomial Naive Bayes classifier and train it on the training data
clf = MultinomialNB()
clf.fit(train_features, train_labels)
test_features = vectorizer.transform(test_data)
# Use the trained classifier to predict the class labels for the test data
predicted_labels = clf.predict(test_features)
print(predicted_labels)
Output :
['negative' 'negative']
RESULT :-
AIM:
Networks.
ALGORITHM:
3. Define a function to compute the joint probability of a set of nodes given their parents
import numpy as np
from scipy.stats import norm
node1 = ("Node1", [], {(): 0.5})
node2 = ("Node2", ["Node1"], {(True,): 0.7, (False,): 0.2})
node3 = ("Node3", ["Node1"], {(True,): 0.1, (False,): 0.8})
# Define a function to compute the joint probability of a set of nodes given thei
r parents
def compute_joint_prob(nodes):
joint_prob = 1.0
for node in nodes:
name, parents, cpt = node
parents_val_tuple = tuple(node_val[parent] for parent in parents)
prob = cpt[parents_val_tuple]
joint_prob *= prob
return joint_prob
RESULT
Thus the python program to implement Bayesian networks was done successfully.
Ex. No: 5 Build Regression Models
AIM:
To write a python program to solve Build Regression Models .
ALGORITHM:
3. Split the data into training and testing sets using the train_test_split function from scikit
learn.
4. Train a linear regression model using the training data by creating an instance of the
LinearRegression class and calling its fit method with the training data.
5. Evaluate the performance of the model using mean squared error on both the training and
import numpy as np
import pandas as pd
# Load data
data = pd.read_csv('data.csv')
X = data.drop('target', axis=1)
y = data['target']
reg = LinearRegression()
reg.fit(X_train, y_train)
# Evaluate model
train_pred = reg.predict(X_train)
test_pred = reg.predict(X_test)
RESULT :-
AIM:
ALGORITHM:
Choose a feature that provides the most information gain (reduces uncertainty)
Split the dataset based on the selected feature
import pandas as pd
dataset = pd.read_csv('housing.csv')
X = dataset.drop('MEDV', axis=1)
y = dataset['MEDV']
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
r2 = r2_score(y_test, y_pred)
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No: 6B Build random forests
AIM:
To write a python program to solve Build random forests .
ALGORITHM:
For a new data point, pass it through each tree in the forest
Aggregate the predictions of all trees (e.g., by majority vote)
import pandas as pd
iris = load_iris()
X = iris.data
y = iris.target
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No: 7 Build SVM models
Algorithm Steps:
Output
[1]
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No: 8 Implement ensembling techniques
AIM:
To write a python program to solve Implement ensembling techniques
ALGORITHM:
1. Load the breast cancer dataset and split the data into training and testing sets using
train_test_split() function.
2. Train 10 random forest models using bagging by randomly selecting 50% of the training
data for each model, and fit a random forest classifier with 100 trees to the selected data.
3. Test each model on the testing set and calculate the accuracy of each model using
accuracy_score() function.
4. Combine the predictions of the 10 models by taking the average of the predicted
probabilities for each class, round the predicted probabilities to the nearest integer, and
5. Print the accuracy of each individual model and the ensemble model.
Program :
from sklearn.datasets import load_breast_cancer
data = load_breast_cancer()
X = data.data
y = data.target
models = []
for i in range(10):
model.fit(X_bag, y_bag)
y_pred = model.predict(X_test)
models.append(model)
y_preds = []
y_pred = model.predict(X_test)
y_preds.append(y_pred)
print(f"Ensemble: {acc_ensemble}")
Output :
Model 1: 0.9649122807017544
Model 2: 0.9473684210526315
Model 3: 0.956140350877193
Model 4: 0.9649122807017544
Model 5: 0.956140350877193
Model 6: 0.9649122807017544
Model 7: 0.956140350877193
Model 8: 0.956140350877193
Model 9: 0.956140350877193
Ensemble: 0.956140350877193
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No: 9A Implement clustering algorithms
(Hierarchical clustering)
AIM:
To write a python program to solve Implement clustering algorithms (Hierarchical
clustering)
ALGORITHM:
1. Begin with a dataset containing n data points.
4. Find the closest pair of clusters based on the pairwise distance between their data points.
6. Update the pairwise distance matrix to reflect the distance between the new cluster and
7. Repeat steps 4-6 until all data points are in a single cluster.
Program:
import numpy as np
Z = linkage(X, 'ward')
# Plot dendrogram
plt.figure(figsize=(10, 5))
dendrogram(Z)
plt.show()
Output :
RESULT :-
Thus the python program has been written and executed Successfully
Ex. No: 9b Implement clustering algorithms
(Density-based clustering)
AIM:
To write a python program to solve Implement clustering algorithms (Density-based
clustering) .
ALGORITHM:
1. Choose an appropriate distance metric (e.g., Euclidean distance) to measure the
2. Choose the value of the radius eps around each data point that will be considered when
identifying dense regions. This value determines the sensitivity of the algorithm to noise
and outliers.
3. Choose the minimum number of points min_samples that must be found within a
radius of eps around a data point for it to be considered a core point. Points with fewer
neighbors are considered border points, while those with no neighbors are considered
noise points.
5. Determine whether p is a core point, border point, or noise point based on the number of
6. If p is a core point, create a new cluster and add p and all its density-reachable neighbors
to the cluster.
7. If p is a border point, add it to any neighboring cluster that has not reached its
min_samples threshold.
8. Mark p as visited.
9. Repeat steps 4-8 until all data points have been visited.
db = DBSCAN(eps=0.5, min_samples=5).fit(X)
labels = db.labels_
plt.show()
Output :
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No: 10 Implement EM for Bayesian networks
AIM:
To write a python program to solve Implement EM for Bayesian networks .
ALGORITHM:
1. Define the structure of the Bayesian network
2. Define the parameters of the network, such as the conditional probability tables (CPDs)
reached:
a) E-step: compute the expected sufficient statistics of the hidden variables given the
import numpy as np
model.add_cpds(cpd_C, cpd_F)
cpd_C = mle.estimate_cpd('C')
for i in range(10):
infer = VariableElimination(model)
evidence = data.to_dict('records')
qs = infer.query(['C'], evidence=evidence)
p_C = qs['C'].values
model.add_cpds(cpd_C, cpd_F)
print(cpd_C)
print(cpd_F)
OUTPUT :
╒═════╤═══════╕
│ C_0 │ 0.686 │
├─────┼───────┤
│ C_1 │ 0.314 │
╘═════╧═══════╛
╒═════╤═════╤═════╕
│ C │ C_0 │ C_1 │
├─────┼─────┼─────┤
├─────┼─────┼─────┤
╘═════╧═════╧═════
RESULT :-
Thus the python program has been written and executed Successfully.
Ex. No: 11 Build simple NN models
AIM
To write a python program to solve Implement to build simple NN models.
ALGORITHM:
#import libraries
import numpy as np
y = np.array([0, 1, 1, 0])
model.fit(x, y)
#make predictions
print(predictions)
plt.xlabel('x1')
plt.ylabel('x2')
plt.show()
Output:
RESULT :-
Thus the python program has been written and executed successfully.
Ex. No: 12 Build deep learning NN models
AIM:
To write a python program to solve Build deep learning NN models .
ALGORITHM:
1. Load the MNIST dataset using mnist.load_data() from the keras.datasets module.
2. Preprocess the data by reshaping the input data to a 1D array, converting the data type to
float32, normalizing the input data to values between 0 and 1, and converting the target
3. Define the neural network architecture using the Sequential() class from Keras. The
model should have an input layer of 784 nodes, two hidden layers of 512 nodes each with
ReLU activation and dropout layers with a rate of 0.2, and an output layer of 10 nodes
5. Train the model using fit() with the preprocessed training data, the batch size of 128, the
number of epochs of 10, and the validation data. Finally, evaluate the model using
evaluate() with the preprocessed test data and print the test loss and accuracy
Program :
import numpy as np
# Convert data type to float32 and normalize the input data to values between 0 and 1
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255
model = Sequential()
model.add(Dropout(0.2))
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
model.add(Dense(10, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
y_test))
Output:
RESULT :-
Thus the python program has been written and executed successfully.