AI Lab File
AI Lab File
NAME-
REG. No.-
1|Page
BONAFIDE CERTIFICATE
Registration no.
2|Page
INDEX
Date of
Exp
Page Date of Completion Teacher’s
. Title of Experiment
No. No. Experiment of Signature
Experiment
Implementation of Toy problem
1 Example-Implement water jug problem
13
3|Page
Experiment 1
Aim – Implementation of Toy problem
Example-Implement water jug problem.
Algorithm –
Rule State Process
(4,Y)
1 (X,Y | X<4)
{Fill 4-gallon jug}
(X,3)
2 (X,Y |Y<3)
{Fill 3-gallon jug}
(0,Y)
3 (X,Y |X>0)
{Empty 4-gallon jug}
(X,0)
4 (X,Y | Y>0)
{Empty 3-gallon jug}
(4,Y-(4-X))
(X,Y | X+Y>=4 ^
5 {Pour water from 3-gallon jug into 4-gallon jug until 4-gallon
Y>0)
jug is full}
(X-(3-Y),3)
(X,Y | X+Y>=3
6 {Pour water from 4-gallon jug into 3-gallon jug until 3-gallon
^X>0)
jug is full}
(2,0)
9 (0,2)
{Pour 2 gallon water from 3 gallon jug into 4 gallon jug}
Code –
print("Water jug problem")
x=int(input("Enter X : "))
y=int(input("Enter Y : "))
while True:
rn=int(input("Enter the rule no. : "))
if rn==2:
if y<3:
x=0
y=3
if rn==3:
if x>0:
x=0
y=3
if rn==5:
4|Page
if x+y>4:
x=4
y=y-(4-x)
if rn==7:
if x+y<4:
x=x+y
y=0
if rn==9:
x=2
y=0
print("X=",x)
print("Y=",y)
if x==2:
print("The result is a goal state")
break
Result –
5|Page
Experiment 2
Aim – Developing Agent Program for Real World Problem.
Algorithm –
Code –
import random
class Environment(object):
def __init__(self):
self.locationCondition = {'A': '0', 'B': '0'}
self.locationCondition['A'] = random.randint(0, 1)
self.locationCondition['B'] = random.randint(0, 1)
class SimpleReflexVacuumAgent(Environment):
def __init__(self, Environment):
print (Environment.locationCondition)
Score = 0
vacuumLocation = random.randint(0, 1)
if vacuumLocation == 0:
print ("Vacuum is randomly placed at Location A")
if Environment.locationCondition['A'] == 1:
print ("Location A is Dirty. ")
Environment.locationCondition['A'] = 0;
Score += 1
print ("Location A has been Cleaned. :D")
if Environment.locationCondition['B'] == 1:
print ("Location B is Dirty.")
print ("Moving to Location B...")
Score -= 1
Environment.locationCondition['B'] = 0;
Score += 1
print ("Location B has been Cleaned :D.")
else:
if Environment.locationCondition['B'] == 1:
print ("Location B is Dirty.")
Score -= 1
print ("Moving to Location B...")
Environment.locationCondition['B'] = 0;
Score += 1
print ("Location B has been Cleaned. :D")
elif vacuumLocation == 1:
print ("Vacuum is randomly placed at Location B. ")
if Environment.locationCondition['B'] == 1:
print ("Location B is Dirty")
Environment.locationCondition['B'] = 0;
Score += 1
6|Page
print ("Location B has been Cleaned")
if Environment.locationCondition['A'] == 1:
print ("Location A is Dirty")
Score -= 1
print ("Moving to Location A")
Environment.locationCondition['A'] = 0;
Score += 1
print ("Location A has been Cleaned")
else:
if Environment.locationCondition['A'] == 1:
print ("Location A is Dirty")
print ("Moving to Location A")
Score -= 1
Environment.locationCondition['A'] = 0;
Score += 1
print ("Location A has been Cleaned")
print (Environment.locationCondition)
print ("Performance Measurement: " + str(Score))
theEnvironment = Environment()
theVacuum = SimpleReflexVacuumAgent(theEnvironment)
Result –
7|Page
Experiment 3
Aim – Implementation of Constraint satisfaction problem
Example: Implement N- queen Problem
Algorithm –
while there are untried configurations
{
generate the next configuration
if queens don't attack in this configuration then
{
print this configuration;
}
}
Code –
global N
N=int(input("enter no of queens : "))
def printSolution(board):
for i in range(N):
for j in range(N):
print(board[i][j],end=" ")
print(" ")
def isSafe(board,row,col):
for i in range(col):
if board[row][i]=='Q':
return False
return True
def solveNQUtil(board,col):
if col>=N:
return True
for i in range(N):
if isSafe(board,i,col):
board[i][col]='Q'
if solveNQUtil(board,col+1) == True:
return True
board[i][col]=0
8|Page
return False
def solveNQ():
board = [[0 for i in range(N)] for j in range(N)]
if solveNQUtil(board,0)==False:
print("Solution does not exist")
return False
printSolution(board)
return True
solveNQ()
Result –
9|Page
Experiment 4
Aim – To Implementation and Analysis of BFS and DFS for Application.
Algorithm –
1. Create a node list (Queue) that initially contains the first node N and mark it as visited.
2. Visit the adjacent unvisited vertex of N and insert it in a queue.
3. If there are no remaining adjacent vertices left, remove the first vertex from the queue mark it
as visited, display it.
4. Repeat step 1 and step 2 until the queue is empty or the desired node is found.
Code –
graph = {
'S': ['A', 'B'],
'A': ['C', 'D'],
'B': ['G','H'],
'C': ['E','F'],
'D': [],
'G': ['I'],
'H': [],
'E': ['K'],
'F': [],
'I': [],
'K': []
}
visited =[]
queue=[]
def bfs(visited,graph,node):
visited.append(node)
queue.append(node)
while queue:
P=queue.pop(0)
print(P,end=" ")
avisit=set()
def dfs(avisit,graph,node):
if node not in avisit:
print(node,end=" ")
avisit.add(node)
for neighbour in graph[node]:
dfs(avisit,graph,neighbour)
10 | P a g e
print("Breadth first search")
bfs(visited,graph,'S')
print("\nDepth first search")
dfs(avisit,graph,'S')
Result –
11 | P a g e
Experiment 5
Aim-To implement Best First Search and A* algorithm.
Algorithm-
1. Best First Search-
Step 1: Place the starting node into the OPEN list.
Step 2: If the OPEN list is empty, Stop and return failure.
Step 3: Remove the node n, from the OPEN list which has the lowest value of h(n),
and places it in the CLOSED list.
If node n is goal then return
else
Step 4: Expand the node n, and generate and check the successors of node n. and find
whether any node is a goal node or not. If any successor node is goal node, then
return success and terminate the search, else proceed to Step 5.
Step 5: For each successor node, algorithm checks for evaluation function f(n), and
then check if the node has been in either OPEN or CLOSED list. If the node has not
been in both list, then add it to the OPEN list.
Step 6: Return to Step 2.
2. A*-
Step1: Place the starting node in the OPEN list.
Step 2: Check if the OPEN list is empty or not, if the list is empty then return failure
and stops.
Step 3: Select the node from the OPEN list which has the smallest value of evaluation
function (g+h), if node n is goal node then return success and stop, otherwise
Step 4:Expand node n and generate all of its successors, and put n into the closed list.
For each successor n', check whether n' is already in the OPEN or CLOSED list, if
not then compute evaluation function for n' and place into Open list.
Step 5: Else if node n' is already in OPEN and CLOSED, then it should be attached to
the back pointer which reflects the lowest g(n') value.
Step 6: Return to Step 2.
Code-
1. Best First Search-
# This class represent a graph
class Graph:
# Initialize the class
def __init__(self, graph_dict=None, directed=True):
self.graph_dict = graph_dict or {}
self.directed = directed
if not directed:
self.make_undirected()
# Create an undirected graph by adding symmetric edges
def make_undirected(self):
for a in list(self.graph_dict.keys()):
for (b, dist) in self.graph_dict[a].items():
12 | P a g e
self.graph_dict.setdefault(b, {})[a] = dist
# Add a link from A and B of given distance, and also add the inverse link if the
graph is undirected
def connect(self, A, B, distance=1):
self.graph_dict.setdefault(A, {})[B] = distance
if not self.directed:
self.graph_dict.setdefault(B, {})[A] = distance
# Get neighbors or a neighbor
def get(self, a, b=None):
links = self.graph_dict.setdefault(a, {})
if b is None:
return links
else:
return links.get(b)
# Return a list of nodes in the graph
def nodes(self):
s1 = set([k for k in self.graph_dict.keys()])
s2 = set([k2 for v in self.graph_dict.values() for k2, v2 in v.items()])
nodes = s1.union(s2)
return list(nodes)
# This class represent a node
class Node:
# Initialize the class
def __init__(self, name:str, parent:str):
self.name = name
self.parent = parent
self.g = 0 # Distance to start node
self.h = 0 # Distance to goal node
self.f = 0 # Total cost
# Compare nodes
def __eq__(self, other):
return self.name == other.name
# Sort nodes
def __lt__(self, other):
return self.f < other.f
# Print node
def __repr__(self):
return ('({0},{1})'.format(self.position, self.f))
# Best-first search
def best_first_search(graph, heuristics, start, end):
13 | P a g e
# Create a start node and an goal node
start_node = Node(start, None)
goal_node = Node(end, None)
# Add the start node
open.append(start_node)
14 | P a g e
def add_to_open(open, neighbor):
for node in open:
if (neighbor == node and neighbor.f >= node.f):
return False
return True
# The main entry point for this module
def main():
# Create a graph
graph = Graph()
# Create graph connections (Actual distance)
graph.connect('Jaipur', 'Gurugram', 111)
graph.connect('Jaipur', 'Mumbai', 85)
graph.connect('Gurugram', 'Noida', 104)
graph.connect('Gurugram', 'Sitapur', 140)
graph.connect('Gurugram', 'Delhi', 183)
graph.connect('Mumbai', 'Noida', 230)
graph.connect('Mumbai', 'Kolkata', 67)
graph.connect('Kolkata', 'Bilaspur', 191)
graph.connect('Kolkata', 'Sitapur', 64)
graph.connect('Noida', 'Delhi', 171)
graph.connect('Noida', 'Madurai', 170)
graph.connect('Noida', 'Pondicherry', 220)
graph.connect('Sitapur', 'Delhi', 107)
graph.connect('Bilaspur', 'Bern', 91)
graph.connect('Bilaspur', 'Zurich', 85)
graph.connect('Bern', 'Zurich', 120)
graph.connect('Zurich', 'Memmingen', 184)
graph.connect('Memmingen', 'Delhi', 55)
graph.connect('Memmingen', 'Madurai', 115)
graph.connect('Madurai', 'Delhi', 123)
graph.connect('Madurai', 'Pondicherry', 189)
graph.connect('Madurai', 'Raipur', 59)
graph.connect('Raipur', 'Shimla', 81)
graph.connect('Pondicherry', 'Lucknow', 102)
graph.connect('Shimla', 'Lucknow', 126)
# Make graph undirected, create symmetric connections
graph.make_undirected()
# Create heuristics (straight-line distance, air-travel distance)
heuristics = {}
heuristics['Bilaspur'] = 204
heuristics['Bern'] = 247
heuristics['Jaipur'] = 215
heuristics['Kolkata'] = 137
heuristics['Lucknow'] = 318
15 | P a g e
heuristics['Mumbai'] = 164
heuristics['Madurai'] = 120
heuristics['Memmingen'] = 47
heuristics['Noida'] = 132
heuristics['Pondicherry'] = 257
heuristics['Raipur'] = 168
heuristics['Sitapur'] = 75
heuristics['Shimla'] = 236
heuristics['Gurugram'] = 153
heuristics['Zurich'] = 157
heuristics['Delhi'] = 0
# Run search algorithm
path = best_first_search(graph, heuristics, 'Jaipur', 'Delhi')
print(path)
print()
# Tell python to run main method
if __name__ == "__main__": main()
2. A*-
from queue import PriorityQueue
else:
self.path = [value]
self.start = start
self.goal = goal
def GetDistance(self):
pass
def CreateChildren(self):
pass
16 | P a g e
# Creating subclass
class State_String(State):
def __init__(self, value, parent, start = 0, goal = 0 ):
super(State_String, self).__init__(value, parent, start, goal)
self.dist = self.GetDistance()
def GetDistance(self):
if self.value == self.goal:
return 0
dist = 0
for i in range(len(self.goal)):
letter = self.goal[i]
dist += abs(i - self.value.index(letter))
return dist
def CreateChildren(self):
if not self.children:
for i in range(len(self.goal)-1):
val = self.value
val = val[:i] + val[i+1] + val[i] + val[i+2:]
child = State_String(val, self)
self.children.append(child)
def Solve(self):
startState = State_String(self.start,0,self.start,self.goal)
count = 0
self.priorityQueue.put((0,count, startState))
while(not self.path and self.priorityQueue.qsize()):
closesetChild = self.priorityQueue.get()[2]
closesetChild.CreateChildren()
self.vistedQueue.append(closesetChild.value)
for child in closesetChild.children:
if child.value not in self.vistedQueue:
count += 1
17 | P a g e
if not child.dist:
self.path = child.path
break
self.priorityQueue.put((child.dist,count,child))
if not self.path:
print("Goal Of is not possible !" + self.goal )
return self.path
Result-
1. Best First Search-
2. A*-
18 | P a g e
19 | P a g e
Experiment 6
Aim – To implement Minimax Algorithm.
Algorithm –
function minimax(node, depth, Player)
1.if depth ==0 or node is a terminal node then
return value(node)
2.If Player =‘Max’ // for Maximizer Player
set α = -∞ //worst case value for MAX
for each child of node do
value= minimax(child, depth-1, ’MIN’)
α= max(α, Value) //gives Maximum of the values
return (α)
else // for Minimizer player
set α = +∞ //worst case value for MIN
for each child of node do
value= minimax(child, depth-1, ’MAX’)
α = min(α, Value) //gives minimum of the values
return (α)
Code –
import math
def minimax (curDepth, nodeIndex, maxTurn, scores,targetDepth) :
if(curDepth==targetDepth):
return scores[nodeIndex]
if(maxTurn):
return max(minimax(curDepth+1,
nodeIndex*2,False,scores,targetDepth),minimax(curDepth+1,
nodeIndex*2+1,False,scores,targetDepth))
else:
return min(minimax(curDepth+1,
nodeIndex*2,True,scores,targetDepth),minimax(curDepth+1,
nodeIndex*2+1,True,scores,targetDepth))
scores=[-1,4,2,6,-3,-5,0,7]
treeDepth=math.log(len(scores),2)
print("Optimal value is : ",end=" ")
print(minimax(0,0,True,scores,treeDepth))
20 | P a g e
Result –
21 | P a g e
Experiment 7
Aim – Implementation of unification and resolution for real world problems.
Algorithm–
Prolog unification
When programming in Prolog, we spend a lot of time thinking about how variables and rules "match" or
"are assigned." There are actually two aspects to this. The first, "unification," regards how terms are
matched and variables assigned to make terms match. The second, "resolution," is described in separate
notes. Resolution is only used if rules are involved. You may notice in these notes that no rules are
involved since we are only talking about unification.
Terms
Two terms unify if they can be matched. Two terms can be matched if:
woman(mia).
loves(vincent, angela).
loves(franklin, mia).
We saw in the Prolog notes that we can "query" the knowledge base and get, say, all the people who
love mia. When we query with loves(X, mia). we are asking Prolog to give us all the values for X that
unify. These values are, essentially, the people who love mia.
Rule :
22 | P a g e
term1 and term2 unify whenever:
1. If term1 and term2 are constants, then term1 and term2 unify if and only if they are the same
atom, or the same number.
2. If term1 is a variable and term2 is any type of term, then term1 and term2 unify, and term1 is
instantiated to term2. (And vice versa.) (If they are both variables, they're both instantiated to
each other, and we say that they share values.)
3. If term1 and term2 are complex terms, they unify if and only if:
a. They have the same functor and arity. The functor is the "function" name (this functor
is foo: foo(X, bar)). The arity is the number of arguments for the functor (the arity for foo(X,
bar) is 2).
c. The variable instantiations are compatible (i.e., the same variable is not given two different
unifications/values).
1. Two terms unify if and only if they unify for one of the above three reasons (there are no reasons
left unstated).
Example
We'll use the = predicate to test if two terms unify. Prolog will answer "Yes" if they do, as well as any
sufficient variable assignments to make the unification work.
1.
?- mia = mia.
2.
?- mia = X.
3.
?- X = Y.
23 | P a g e
4.
o/p No, these two terms do not unify because arity of s(g) do not match with the arity of s(g,X) due to
which rule 3 fails in recursion.
24 | P a g e
Experiment 8
Aim – Implementation of knowledge representation schemes – use cases.
Semantic relations –
25 | P a g e
b. 1. Gita likes all kinds of food.
2. Mango and chapati are food.
3. Gita eats almond and is still alive.
4. Anything eaten by anyone and is still alive is food.
26 | P a g e
c. 1. Jerry is a cat.
2. Jerry is a mammal
3. Jerry is owned by Priya.
4. Jerry is brown colored.
5. All Mammals are animal.
27 | P a g e
d. 1. Ritz is a car.
2. Car has 4 wheels.
3. Car is a vehicle.
4. Car has engine.
5. Car has battery.
6. Ritz has power steering.
28 | P a g e
Experiment 9
Aim – Implementation of uncertain methods for an application.
we can find the probability of an uncertain event by using the below formula.
Problem1:- Calculate the Probability of finding how many students got the 60 marks for
given data set .
import numpy as np
import collections
arraySize=npArray.size
proba=(nbOfOccurrences/arraySize)*100
29 | P a g e
Problem2:- If In class 80 students and 60 students got 60 % marks then Calculate the
Probability of finding how many students got the 60 marks for given data set .
#!/usr/bin/env python3
"""reducer.py"""
import sys
Marksprob = {}
line = line.strip()
# Create function that returns probability percent rounded to one decimal place
return round(probability, 1)
30 | P a g e
# Sample Space
ClassA = 30
Marks = 15
print(str(grade_probability) + '%')
Output:- 28.57
31 | P a g e
Experiment 10
Aim – Implementation of block world problem.
Algorithm –
1. MOVE(B,A)- To lift block from B to A.
2. ON(B,A)- To place block B on A.
3. CLEAR(B)- To lift block B from the table.
4. PLACE(B)- To put the block B on table.
Code –
class Strips(object):
def __init__(self, name, preconds, effects, cost=1):
self.name = name
self.preconds = preconds
self.effects = effects
self.cost = cost
def __repr__(self):
return self.name
class STRIPS_domain(object):
def __init__(self, feats_vals, actions):
self.feats_vals = feats_vals
self.actions = actions
class Planning_problem(object):
def __init__(self, prob_domain, initial_state, goal):
self.prob_domain = prob_domain
self.initial_state = initial_state
self.goal = goal
boolean = {True, False}
### blocks world
def move(x,y,z):
"""string for the 'move' action"""
return 'move_'+x+'_from_'+y+'_to_'+z
def on(x):
"""string for the 'on' feature"""
return x+'_is_on'
def clear(x):
"""string for the 'clear' feature"""
return 'clear_'+x
def create_blocks_world(blocks = {'a','b','c','d'}):
blocks_and_table = blocks | {'table'}
stmap = {Strips(move(x,y,z),{on(x):y, clear(x):True, clear(z):True},
{on(x):z, clear(y):True, clear(z):False})}
for x in blocks:
for y in blocks_and_table:
for z in blocks:
if x!=y and y!=z and z!=x:
stmap.update({Strips(move(x,y,'table'), {on(x):y, clear(x):True},
32 | P a g e
{on(x):'table', clear(y):True})})
for x in blocks:
for y in blocks:
for z in blocks:
if x!=y:
feats_vals = {on(x):blocks_and_table-{x} for x in blocks}
feats_vals.update({clear(x):boolean for x in blocks_and_table})
33 | P a g e
EXP-11
AIM-(Implementation of Learning Algo)
# Machine Learning
import numpy as np
def perceptron_single_step_update(
feature_vector,
label,
current_theta,
current_theta_0):
theta = current_theta
theta_0 = current_theta_0
if label*(np.matmul(current_theta, feature_vector) +
current_theta_0) <= 0:
[m,n] = np.shape(feature_matrix)
tt = np.zeros(n)
tt_0 = 0
34 | P a g e
for t in range(T):
for i in range(m):
vec = feature_matrix[i]
EXP-12
35 | P a g e
AIM-Development of ensemble model
import pandas as pd
df = pd.read_csv("train_data.csv")
target = df["target"]
train = df.drop("target")
model_1 = LinearRegression()
36 | P a g e
model_2 = xgb.XGBRegressor()
model_3 = RandomForestRegressor()
model_1.fit(X_train, y_target)
model_2.fit(X_train, y_target)
model_3.fit(X_train, y_target)
pred_1 = model_1.predict(X_test)
pred_2 = model_2.predict(X_test)
pred_3 = model_3.predict(X_test)
pred_final = (pred_1+pred_2+pred_3)/3.0
# printing the root mean squared error between real value and predicted
value
print(mean_squared_error(y_test, pred_final))
37 | P a g e