AIML LAB - Merged
AIML LAB - Merged
LABORATORY RECORD
2023 - 2024
NAME : ………………………………….…………………………...
BRANCH : ………………………………….…………………………..
DEPARTMENT OF
ELECTRONICS AND COMMUNICATION ENGINEERING
BONAFIDE CERTIFICATE
The above should be written / drawn on the left hand side page of the record
using Pen / 2B Pencil.
LIST OF EXPERIMENTS:
AIM
ALGORITHM
1. Create an empty queue (for BFS) or stack (for DFS) and add the initial state to it.
• Remove the first state from the queue (or 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 queue (or stack) and mark it as visited.
4. If the queue (or stack) is empty and no goal state has been found, return failure
PROGRAM
graph = {
'D': ['B'],
}
# BFS Algorithm
while queue:
visited.append(node)
for neighbor in graph[node]: # Get all adjacent nodes of the dequeued node
queue.append(neighbor)
return visited
return visited
# DFS Algorithm
return visited
return visited
# Example outputs
RESULT
Thus the python program has been written and executed successfully
Ex.No : 2A
Implementation of Informed search algorithms A*
Date :
AIM
ALGORITHM
PROGRAM
open_set = {start_node}
closed_set = set()
n = None
n=v
if n == stop_node or Graph_nodes[n] is None:
continue
else:
open_set.add(m)
parents[m] = n
else:
parents[m] = n
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n is None:
return None
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
return path
open_set.remove(n)
closed_set.add(n)
return None
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None
def heuristic(n):
H_dist = {
return H_dist[n]
Graph_nodes = {
'A': [('B', 6), ('F', 3)], 'B': [('A', 6), ('C', 3), ('D', 2)],
'C': [('B', 3), ('D', 1), ('E', 5)], 'D': [('B', 2), ('C', 1), ('E', 8)],
'F': [('A', 3), ('G', 1), ('H', 7)], 'G': [('F', 1), ('I', 3)],
'H': [('F', 7), ('I', 2)], 'I': [('E', 5), ('G', 3), ('H', 2), ('J', 3)],
aStarAlgo('A', 'J')
OUTPUT
RESULT
Thus the python program has been written and executed successfully
Ex.No : 2B
Informed search algorithms memory-bounded A*
Date :
AIM
ALGORITHM
2. Add the initial state to the open set with a cost of 0 and an estimated total cost
• 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.
• 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.state)
current_node = current_node.parent
path.append(start_node.state)
path.reverse()
return path
explored.add(current_node)
if child_node in explored:
continue
total_cost[child_node] = new_cost
frontier.put((priority, child_node))
return None
class Node:
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:
RESULT
Thus the python program has been written and executed successfully.
Ex.No : 03
Implement naive Bayes models
Date :
AIM
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 | X = x_test), using the Gaussian probability density function: P(Y = c
| X = x_test) = (1 / (sqrt(2*pi)*sigma_c)) * exp(-((x_test - mu_c)^2) / (2 *
sigma_c^2)) where mu_c and sigma_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 the predicted label Y_pred.
5. Return Y_pred as the output.
PROGRAM
iris = datasets.load_iris()
X = iris.data # Features
gaussian_naive_bayes_model = GaussianNB()
gaussian_naive_bayes_model.fit(X_train, y_train)
multinomial_naive_bayes_model = MultinomialNB()
multinomial_naive_bayes_model.fit(X_train, y_train)
y_pred_gaussian = gaussian_naive_bayes_model.predict(X_test)
y_pred_multinomial = multinomial_naive_bayes_model.predict(X_test)
RESULT
Thus the python program has been written and executed successfully
Ex.No : 04
Implement Bayesian Networks
Date :
AIM:
ALGORITHM:
pgmpy.inference.
2. Define the structure of the Bayesian network by creating a BayesianModel object and
3. Define the conditional probability distributions (CPDs) for each node using the
TabularCPD class.
5. Check if the model is valid using the check_model method. If the model is not valid,
7. Use the inference.query method to compute the probability of the Letter node being
good given that the Intelligence node is high and the Difficulty node is low.
evidence=['Grade'], evidence_card=[3])
evidence=['Grade'], evidence_card=[3])
inference = VariableElimination(model)
# Query the Bayesian network for a specific probability
show_progress=False)
OUTPUT :
RESULT :-
Thus the python program has been written and executed successfully
Ex.No : 05
Build Regression Models
Date :
AIM
ALGORITHM:
PROGRAM
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)
Output :
RESULT
Thus the python program has been written and executed successfully.
Ex.No : 6A
Build decision trees
Date :
AIM
ALGORITHM
• Continue until each subset is either pure (only one class label) or too small to
split further
iris = load_iris()
X = iris.data
y = iris.target
clf = DecisionTreeClassifier()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
Output :
Thus the python program has been written and executed successfully
Ex.No : 6B
Build random forests
Date :
AIM
ALGORITHM
• Build a decision tree using the selected features and split criteria
• For a new data point, pass it through each tree in the forest
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)
Output :
Thus the python program has been written and executed successfully
Ex.No : 7
Build SVM models
Date :
AIM
ALGORITHM
iris = datasets.load_iris()
random_state=42)
clf = SVC(kernel='linear')
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
print("Accuracy:", accuracy)
Output :
Accuracy: 1.
RESULT
Thus the python program has been written and executed successfully
Ex.No : 8
Implement ensembling techniques
Date :
AIM
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 calculate the accuracy of the ensemble model using accuracy_score() function.
5. Print the accuracy of each individual model and the ensemble model.
PROGRAM
data = load_breast_cancer()
X = data.data
y = data.target
# Train multiple Random Forest classifiers using bagging and print their accuracies
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)
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
Date : (Hierarchical clustering)
AIM
ALGORITHM
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
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
Date : (Density-based clustering)
AIM
ALGORITHM
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
Date :
AIM
ALGORITHM
2. Define the parameters of the network, such as the conditional probability tables
(CPDs)
is reached:
a) E-step: compute the expected sufficient statistics of the hidden variables given
import numpy as np
network_structure = {
cpds = {
np.random.seed(0)
num_samples = 100
data = {
'B': np.zeros(num_samples),
'C': np.zeros(num_samples)
def initialize_parameters():
if len(network_structure[node]['parents']) == 0:
counts = np.bincount(data[node])
else:
network_structure[node]['parents']] + [network_structure[node]['num_values']])
initialize_parameters()
max_iter = 100
tolerance = 1e-6
converged = False
for _ in range(max_iter):
prev_cpds = cpds.copy()
for i in range(num_samples):
network_structure[node]['parents'])
node_value = int(data[node][i])
expected_counts[node][indices] += 1
keepdims=True)
cpds.keys())
converged = True
break
if converged:
else:
print("Learned parameters:")
for node in cpds.keys():
print(cpds[node])
OUTPUT :
Learned parameters:
CPD for A:
[0.44 0.56]
CPD for B:
[[1. 0.]
[1. 0.]]
CPD for C:
[[ 1. 0.]
[nan nan]]
RESULT
Thus the python program has been written and executed successfully
Ex.No : 11
Build simple NN models
Date :
AIM
ALGORITHM
PROGRAM
import numpy as np
model = Sequential()
model.add(Dense(2, input_shape=(2,)))
model.add(Activation('sigmoid'))
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.summary()
OUTPUT :
Model: "sequential"
_________________________________________________________________
=========================================================
==========================================================
_________________________________________________________________
RESULT
Thus the python program has been written and executed successfully
Ex.No : 12
Build deep learning NN models
Date :
AIM
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
3. Define the neural network architecture using the Sequential() class from Keras.
4. 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
6. 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
model = Sequential([
Dropout(0.2),
Dense(512, activation='relu'),
Dropout(0.2),
Dense(10, activation='softmax')
])
model.compile(loss='categorical_crossentropy', optimizer='adam',
metrics=['accuracy'])
Output:
RESULT
Thus the python program has been written and executed successfully.