AI_Lab_File_Vivek_pandey
AI_Lab_File_Vivek_pandey
-1
AIM:
Write a Program to Implement Water-Jug problem.
PROGRAM:
from collections import deque
while q:
jug1, jug2, steps = q.popleft()
if jug1 == d or jug2 == d:
return steps
# 1: Fill jug1
if not visited[m][jug2]:
visited[m][jug2] = True
q.append((m, jug2, steps + 1))
# 2: Fill jug2
if not visited[jug1][n]:
visited[jug1][n] = True
q.append((jug1, n, steps + 1))
# 3: Empty jug1
if not visited[0][jug2]:
visited[0][jug2] = True
q.append((0, jug2, steps + 1))
1
# 4: Empty jug2
if not visited[jug1][0]:
visited[jug1][0] = True
q.append((jug1, 0, steps + 1))
return -1
if __name__ == "__main__":
vol1 = int(input("Enter Volume of first jug: "))
vol2 = int(input("Enter Volume of second jug: "))
reqVol = int(input("Enter the required Volume in a jug: "))
2
EXPERIMENT NO.-2
AIM:
Write a Program to Implement Tower of Hanoi.
PROGRAM:
# Recursive Python function to solve tower of hanoi
def TowerOfHanoi(n, from_rod, to_rod, aux_rod):
if n == 0:
return
# Driver code
N=3
OUTPUT:
3
EXPERIMENT NO.-3
AIM:
Write a Program to Implement 8-Puzzle problem.
PROGRAM:
import copy
from heapq import heappush, heappop
n=3
row = [ 1, 0, -1, 0 ]
col = [ 0, -1, 0, 1 ]
class priorityQueue:
def __init__(self):
self.heap = []
def pop(self):
return heappop(self.heap)
def empty(self):
if not self.heap:
return True
else:
return False
class node:
def __init__(self, parent, mat, empty_tile_pos, cost, level):
self.parent = parent
self.mat = mat
self.empty_tile_pos = empty_tile_pos
self.cost = cost
self.level = level
4
def calculateCost(mat, final) -> int:
count = 0
for i in range(n):
for j in range(n):
if ((mat[i][j]) and
(mat[i][j] != final[i][j])):
count += 1
return count
x1 = empty_tile_pos[0]
y1 = empty_tile_pos[1]
x2 = new_empty_tile_pos[0]
y2 = new_empty_tile_pos[1]
new_mat[x1][y1], new_mat[x2][y2] = new_mat[x2][y2], new_mat[x1][y1]
return new_node
def printMatrix(mat):
for i in range(n):
for j in range(n):
print("%d " % (mat[i][j]), end = " ")
print()
def printPath(root):
if root == None:
return
printPath(root.parent)
printMatrix(root.mat)
5
print()
pq.push(root)
while not pq.empty():
minimum = pq.pop()
if minimum.cost == 0:
printPath(minimum)
return
for i in range(4):
new_tile_pos = [
minimum.empty_tile_pos[0] + row[i],
minimum.empty_tile_pos[1] + col[i], ]
if isSafe(new_tile_pos[0], new_tile_pos[1]):
child = newNode(minimum.mat, minimum.empty_tile_pos, new_tile_pos,
minimum.level + 1, minimum, final,)
pq.push(child)
initial = [ [ 1, 2, 3 ],
[ 8, 6, 0 ],
[ 7, 5, 4 ] ]
final = [ [ 1, 2, 3 ],
[ 8, 0, 4 ],
[ 7, 6, 5 ] ]
empty_tile_pos = [ 1, 2 ]
6
OUTPUT:
7
EXPERIMENT NO.-4
AIM:
Write a Program to Implement Breadth First Search.
PROGRAM:
from collections import deque
while q:
curr = q.popleft()
print(curr, end=" ")
for x in adj[curr]:
if not visited[x]:
visited[x] = True
q.append(x)
for i in range(len(adj)):
if not visited[i]:
bfs(adj, i, visited)
V=5
adj = [[] for _ in range(V)]
8
# Add edges to the graph
add_edge(adj, 0, 1)
add_edge(adj, 0, 4)
add_edge(adj, 1, 2)
add_edge(adj, 1, 4)
add_edge(adj, 2, 3)
add_edge(adj, 2, 4)
add_edge(adj, 3, 4)
OUTPUT:
9
EXPERIMENT NO.-5
AIM:
Write a Program to Implement Depth First Search.
PROGRAM:
class Graph:
def __init__(self, vertices):
self.adj = [[] for _ in range(vertices)]
for i in self.adj[s]:
if not visited[i]:
self.dfs_rec(visited, i)
def dfs(self):
visited = [False] * len(self.adj)
if __name__ == "__main__":
# Number of vertices
V=5
graph = Graph(V)
10
# Populate the adjacency list with edges
for edge in edges:
graph.add_edge(edge[0], edge[1])
# Perform DFS
print("DFS Traversal of given graph:")
graph.dfs()
OUTPUT:
11
EXPERIMENT NO.-6
AIM:
Write a Program to Implement A* algorithm.
PROGRAM:
import math
import heapq
class Cell:
def __init__(self):
self.parent_i = 0
self.parent_j = 0
# Total cost of the cell (g + h)
self.f = float('inf')
# Cost from start to this cell
self.g = float('inf')
# Heuristic cost from this cell to destination
self.h = 0
12
row = dest[0]
col = dest[1]
13
# Initialize the details of each cell
cell_details = [[Cell() for _ in range(COL)] for _ in range(ROW)]
# Initialize the open list (cells to be visited) with the start cell
open_list = []
heapq.heappush(open_list, (0.0, i, j))
14
if is_destination(new_i, new_j, dest):
# Set the parent of the destination cell
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j
print("The destination cell is found")
# Trace and print the path from source to destination
trace_path(cell_details, dest)
found_dest = True
return
else:
# Calculate the new f, g, and h values
g_new = cell_details[i][j].g + 1.0
h_new = calculate_h_value(new_i, new_j, dest)
f_new = g_new + h_new
# If the cell is not in the open list or the new f value is smaller
if cell_details[new_i][new_j].f == float('inf') or cell_details[new_i][new_j].f >
f_new:
# Add the cell to the open list
heapq.heappush(open_list, (f_new, new_i, new_j))
# Update the cell details
cell_details[new_i][new_j].f = f_new
cell_details[new_i][new_j].g = g_new
cell_details[new_i][new_j].h = h_new
cell_details[new_i][new_j].parent_i = i
cell_details[new_i][new_j].parent_j = j
def main():
# Define the grid (1 for unblocked, 0 for blocked)
grid = [
[1, 1, 1, 1, 0, 0, 0, 0],
[1, 1, 1, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 0, 1, 1, 1],
[0, 1, 1, 1, 1, 1, 1, 1]
]
15
# Define the source and destination
src = [0, 0]
dest = [3, 7]
if __name__ == "__main__":
main()
OUTPUT:
16
EXPERIMENT NO.-7
AIM:
Write a program to demonstrate the working of the decision tree based ID3. Use an
appropriate data set for building the decision tree and apply this knowledge to
classify a new sample.
PROGRAM:
import numpy as np
import math
import csv
def read_data(filename):
with open(filename, 'r') as csvfile:
datareader = csv.reader(csvfile, delimiter=',')
headers = next(datareader)
metadata = []
traindata = []
for name in headers:
metadata.append(name)
for row in datareader:
traindata.append(row)
class Node:
def __init__(self, attribute):
self.attribute = attribute
self.children = []
self.answer = ""
def __str__(self):
return self.attribute
17
for x in range(items.shape[0]):
for y in range(data.shape[0]):
if data[y, col] == items[x]:
count[x] += 1
for x in range(items.shape[0]):
dict[items[x]] = np.empty((int(count[x]), data.shape[1]), dtype="|S32")
pos = 0
for y in range(data.shape[0]):
if data[y, col] == items[x]:
dict[items[x]][pos] = data[y]
pos += 1
if delete:
dict[items[x]] = np.delete(dict[items[x]], col, 1)
def entropy(S):
items = np.unique(S)
if items.size == 1:
return 0
for x in range(items.shape[0]):
counts[x] = sum(S == items[x]) / (S.size * 1.0)
total_size = data.shape[0]
entropies = np.zeros((items.shape[0], 1))
intrinsic = np.zeros((items.shape[0], 1))
18
for x in range(items.shape[0]):
ratio = dict[items[x]].shape[0]/(total_size * 1.0)
entropies[x] = ratio * entropy(dict[items[x]][:, -1])
intrinsic[x] = ratio * math.log(ratio, 2)
for x in range(entropies.shape[0]):
total_entropy -= entropies[x]
return total_entropy / iv
split = np.argmax(gains)
node = Node(metadata[split])
metadata = np.delete(metadata, split, 0)
for x in range(items.shape[0]):
child = create_node(dict[items[x]], metadata)
node.children.append((items[x], child))
return node
def empty(size):
s = ""
for x in range(size):
19
s += " "
return s
OUTPUT:
20
EXPERIMENT NO.-8
AIM:
Write a program to implement the naïve Bayesian classifier algorithm.
PROGRAM:
import pandas as pd
from sklearn import tree
from sklearn.preprocessing import LabelEncoder
from sklearn.naive_bayes import GaussianNB
le_PlayTennis = LabelEncoder()
y = le_PlayTennis.fit_transform(y)
print("\nNow the Train output is\n",y)
21
classifier = GaussianNB()
classifier.fit(X_train,y_train)
OUTPUT:
22
EXPERIMENT NO.-9
AIM:
Write a program to implement k-Nearest Neighbour algorithm.
PROGRAM:
dataset=load_iris()
X_train,X_test,y_train,y_test=train_test_split(dataset["data"],dataset["target"],random_state=0)
kn=KNeighborsClassifier(n_neighbors=1)
kn.fit(X_train,y_train)
for i in range(len(X_test)):
x=X_test[i]
x_new=np.array([x])
prediction=kn.predict(x_new)
print("TARGET=",y_test[i],dataset["target_names"][y_test[i]],"PREDICTED=",prediction,datas
et["target_names"][prediction])
print(kn.score(X_test,y_test))
23
OUTPUT:
24
EXPERIMENT NO.-10
AIM:
Build an Artificial Neural Network by implementing the Backpropagation
algorithm and test the same using appropriate data sets.
PROGRAM:
import numpy as np
X = np.array(([2, 9], [1, 5], [3, 6]), dtype=float) # X = (hours sleeping, hours studying)
y = np.array(([92], [86], [89]), dtype=float) # y = score on test
# scale units
X = X/np.amax(X, axis=0) # maximum of X array
y = y/100 # max test score is 100
class Neural_Network(object):
def __init__(self):
# Parameters
self.inputSize = 2
self.outputSize = 1
self.hiddenSize = 3
# Weights
self.W1 = np.random.randn(self.inputSize, self.hiddenSize) # (3x2) weight matrix from
input to hidden layer
self.W2 = np.random.randn(self.hiddenSize, self.outputSize) # (3x1) weight matrix from
hidden to output layer
25
def sigmoidPrime(self, s):
return s * (1 - s) # derivative of sigmoid
NN = Neural_Network()
print ("\nInput: \n" + str(X))
print ("\nActual Output: \n" + str(y))
print ("\nPredicted Output: \n" + str(NN.forward(X)))
print ("\nLoss: \n" + str(np.mean(np.square(y - NN.forward(X))))) # mean sum squared loss)
NN.train(X, y)
OUTPUT:
26