Ad3311 - Ai Lab Manual
Ad3311 - Ai Lab Manual
Ad3311 - Ai Lab Manual
1
Vision and Mission of the Institute
VISION
To be an Institute of repute in the field of Engineering and Technology by implementing the best educational
practices akin to global standards for fostering domain knowledge and developing research attitude among
students to make them globally competent
MISSION
Achieving excellence in Teaching Learning process using state-of-the-art resources
Extending opportunity to upgrade faculty knowledge and skills
Implementing the best student training practices for requirements of industrial scenario of the state
Motivating faculty and students in research activity for real time application
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences and
engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and design system
components or processes that meet the specified needs with appropriate consideration for the public health, safety,
cultural, societal and environmental considerations.
2
PO4 Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis, and interpretation of data and synthesis of the information to provide
valid conclusions.
PO5 Modern tool usage: Create, select, apply appropriate techniques, resources, modern engineering and IT
tools including prediction and modeling to complex engineering activities with an understanding of the
limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health,
safety, legal, cultural issues and the consequent responsibilities relevant to the professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering solutions in
societal, environmental contexts, demonstrate the knowledge and need for sustainable development.
PO8 Ethics: Apply ethical principles, commit to professional ethics, responsibilities and norms of the engineering
practice.
PO9 Individual and team work: Function effectively as an individual, as a member or leader in diverse teams
and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the engineering
community with society at large being able to comprehend, write effective reports, design documentation, make
effective presentations and receive clear instructions.
PO11 Project management and finance: Demonstrate knowledge, understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to manage projects
and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need, ability to engage in independent and life-long learning in the
broadest context of technological change.
3
Program Educational Objective (PEOs)
PEO1 – Graduates will be able to demonstrate their technical skills and competency in various applications by
providing creative and novel technological solutions.
PEO2 – Graduates will be able to ensure the effective contribution to the society through critical thinking,
innovations and research with the broad spectrum of skills in frontline technologies.
PEO3 – Graduates will be equipped with multidisciplinary initiatives and visions towards the growth of society
with respect to ethical and lifelong learning.
COURSE OUTCOME:
At the end of this course, the students will be able to:
CO1: Design and implement search strategies
CO2: Implement game playing and CSP techniques
CO3: Develop logical reasoning systems
CO4: Develop probabilistic reasoning systems
4
EX.No. 1 IMPLEMENT BASIC SEARCH STRATEGIES 8-PUZZLE PROBLEM
DATE:
AIM
ALGORITHM
1. The code starts by creating a Solution class and then defining the method solve.
2. The function takes in a board as an argument, which is a list of tuples representing the
positions on the board.
3. It iterates through each position in the list and creates a dictionary with that position's value
set to 0.
4. Then it iterates through all possible moves for that position and returns their number of
occurrences in dict.
5. After this, it loops over all nodes on the board until it finds one where there are no more
moves left to make (i.e., when len(current_nodes) == 0).
6. This node will be returned as -1 if found or else its index will be stored into pos_0 so that we
can find out what move was made at that point later on.
7. The next step is finding out what move was made at every node by looping over all possible
moves for each node using self's find_next function, which takes in a single node as an
argument and returns any other nodes connected to it via path-finding algorithms like DFS or
BFS (see below).
8. For example, if pos_0 = 1 then self would call: moves = { 0: [1], 1:
9. The code will print the number of paths in a solution.
PROGRAM
class Solution:
def solve(self, board):
dict = {}
flatten = []
for i in range(len(board)):
flatten += board[i]
flatten = tuple(flatten)
dict[flatten] = 0
if flatten == (0, 1, 2, 3, 4, 5, 6, 7, 8):
return 0
return self.get_paths(dict)
def get_paths(self, dict):
cnt = 0
while True:
current_nodes = [x for x in dict if dict[x] == cnt]
if len(current_nodes) == 0:
5
return -1
results = []
pos_0 = node.index(0)
for move in moves[pos_0]:
new_node = list(node)
new_node[move], new_node[pos_0] = new_node[pos_0], new_node[move]
results.append(tuple(new_node))
return results
ob = Solution()
matrix = [
[3, 1, 2],
[4, 7, 5],
[6, 8, 0]
]
print("NO OF MOVES==",ob.solve(matrix))
6
OUTPUT
NO OF MOVES== 4
RESULT:
Thus the program to implement 8 puzzles search strategy is implemented and executed successfully.
7
EX.No. 2 Implement basic search strategies – 8-Queens Problem
DATE:
AIM
ALGORITHM
PROGRAM
def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
if (not(attack(i,j))) and (board[i][j]!=1):
board[i][j] = 1
8
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
OUTPUT
RESULT
Thus the program to implement 8 queens search strategy is implemented and executed successfully.
9
EX.No.3 Implement basic search strategies – Crypt arithmetic
DATE:
AIM
To implement basic search strategies – Crypt arithmetic.
ALGORITHM
10
32. Then, the code creates a list called solutions and iterates through each solution in order to print out its contents.
33. The first line says "CRYPTARITHMETIC PUZZLE SOLVER".
34. This is just an example of what you might see on your screen after running this program.
35. The code will print 0 Solutions!
36. If the input is not a word or number.
37. The code above will then iterate through the list of solutions and print them out.
PROGRAM
11
print('\nSolutions:')
for soln in solutions:
print(f'{soln[0]}\t{soln[1]}')
if __name__ == '__main__':
print('CRYPTARITHMETIC PUZZLE SOLVER')
print('WORD1 + WORD2 = RESULT')
word1 = input('Enter WORD1: ').upper()
word2 = input('Enter WORD2: ').upper()
result = input('Enter RESULT: ').upper()
if not word1.isalpha() or not word2.isalpha() or not result.isalpha():
raise TypeError('Inputs should ony consists of alphabets.')
solve(word1, word2, result)
OUTPUT
RESULT
Thus the program to implement crypt arithmetic search strategy is implemented and executed successfully
12
EX.No. 4 Implement A* Algorithm
DATE:
AIM
To Implement A* Algorithm.
ALGORITHM
13
PROGRAM
def GetDistance(self):
pass
def CreateChildren(self):
pass
# 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)
# Creating a class that hold the final magic
class A_Star_Solver:
def __init__(self, start, goal):
14
self.path = []
self.vistedQueue =[]
self.priorityQueue = PriorityQueue()
self.start = start
self.goal = goal
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
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
15
OUTPUT
Starting....
0)secure
1)secrue
2)sercue
3)srecue
4)rsecue
5)rescue
RESULT
16
EX.No. 5 Implement Mini-Max algorithm for game playing (Alpha-Beta pruning)
DATE:
AIM
ALGORITHM
17
PROGRAM
else:
best = MAX
# Recur for left and
# right children
for i in range(0, 2):
val = minimax(depth + 1, nodeIndex * 2 + i,True, values, alpha, beta)
best = min(best, val)
beta = min(beta, best)
# Alpha Beta Pruning
if beta <= alpha:
break
return best
# Driver Code
if __name__ == "__main__":
values = [3, 5, 6, 9, 1, 2, 0, -1]
print("The optimal value is :", minimax(0, 0, True, values, MIN, MAX))
18
OUTPUT
The optimal value is : 5
RESULT
Thus the program to implement Minimax algorithm for game playing is implemented and executed
successfully
19
EX.No.6 Solve constraint satisfaction problems
DATE:
AIM
ALGORITHM
20
PROGRAM
def backtrack(assignment):
#"""Runs backtracking search to find an assignment."""
# Check if assignment is complete
if len(assignment) == len(VARIABLES):
return assignment
var = select_unassigned_variable(assignment)
for value in DOMAIN:
if consistent(var, value, assignment):
assignment[var] = value
result = backtrack(assignment)
if result is not None:
return result
return None
def select_unassigned_variable(assignment):
# """Chooses a variable not yet assigned, in order."""
for var in VARIABLES:
if var not in assignment.keys():
return var
solution = backtrack(dict())
21
print(solution)
OUTPUT
{'csc': 'Monday', 'maths': 'Tuesday', 'phy': 'Tuesday', 'che': 'Monday', 'tam': 'MoMonday', 'eng': 'Wednesday',
'bio': 'Tuesday'}
RESULT
Thus the program to solve constraint satisfaction problem is implemented and executed successfully.
22
EX.No. 7 Propositional Model Checking Algorithms
DATE:
AIM
ALGORITHM
1. Class Literal, it has attributes name and sign to denote whether the literal is positive or negative in use.
2. The __neg__ function returns a new literal with the same name but the opposite sign of its parent literal.
3. The __repr__ function returns the string of the literal name,( or the string with a negative sign) each time the
instance of the literal is called.
4. The CNFConvert function converts the KiB from a list of sets to a list of list for easier computing
5. The VariableSet function finds all the used literals in the KB, and in order to assist with running the DPLL.
6. The Negativeofx function is for holding the negative form of the literal, for use in the DPLL algorithm
7. The pickX function picks a literal from the variable set and works with it as a node in the tree.
8. Now define the functions splitfalseliterals() and splitTrueLiteral().
9. Create the function dpll() that performs the dpll algorithm recursively.
10. Finally call the function to execute the code.
PROGRAM
import re
class Literal:
# Class Literal, it has attributes name and sign to denote whether the literal is positive or negative in use
def __init__(self, name, sign=True):
self.name = str(name)
self.sign = sign
def __neg__(self): # returns a new literal with the same name but the opposite sign of its parent literal
return Literal(self.name, False)
def __str__(self):
return str(self.name)
def __repr__(self):
# returns the string of the literal name,( or the string with a negative sign) each time the instance of the literal is
called
if self.sign:
return '%r' % str(self.__str__())
else:
return '%r' % str("-" + self.__str__())
def CNFconvert(KB):
# This function converts the Kb from a list of sets to a list of list for easier computing
storage=[]
for i in KB:
i=list(i)
for j in i:
j=str(j)
23
storage.append(i)
return storage
def VariableSet(KB):
# This function finds all the used literals in the KB, and in order to assist with running the DPLL
KB=eval((CNFconvert(KB).__str__()))
storage=[]
for obj in KB:
for item in obj:
if item[0] == '-' and item[1:] not in storage:
storage.append(str(item[1:]))
elif item not in storage and item[0] != '-':
storage.append(str(item))
return storage
def Negativeofx(x):
# This function is for holding the negative form of the literal, for use in the DPLL algorithm
check=re.match("-", str(x))
if (check):
return str(x[1:])
else:
return "-"+str(x)
24
return holder
def unitResolution(clauses):
literalholder={} # dictionary for holding the literal holder and their
bool
i=0
# This part of the code goes through each and every clause until the all literals in the KB are resolved
while i < len(clauses): # for each clause
newClauses=[]
clause=clauses[i]
# picks a clause to work on
if (len(clause) == 1):
literal=str(clause[0])
pattern=re.match("-", literal)
# Populates the dictionary
if (pattern):
nx=literal[1:]
literalholder[nx]=False
else:
nx="-"+literal
literalholder[literal]=True
# Checks for all other appearances o the literal or its opposite int he KB
for item in clauses:
if item != clauses[i]:
if (nx in item):
item.remove(nx)
newClauses.append(item)
i=0
clauses=newClauses
# no unit clause
else:
i += 1
return literalholder, clauses
25
nx=Negativeofx(x)
ncnf=splitTrueLiteral(cnf, x)
ncnf=splitFalseLiterals(ncnf, nx)
if ncnf == cnf:
varList.remove(x)
else:
break
# does the same dpll recursively, but follows the true path for that variable
case1=dpll(ncnf, varList)
if (case1 != "notsatisfiable"):
copy=case1.copy()
copy.update(literals)
copy.update({x: True})
return copy
# does the dpll recursively, but follows the false path for that variable
case1=dpll(ncnf, varList)
if not case1:
copy=case1.copy()
copy.update(literals)
copy.update({x: False})
return copy
else:
return "notsatisfiable"
def DPLL(KB):
# Finally restructures the output to fit the required output by the assignment description
KB=eval((CNFconvert(KB).__str__()))
varList=VariableSet(KB)
result=dpll(KB, varList)
if result == 'notsatisfiable':
False
else:
for i in varList:
if i in result and result[i] == True:
result[i]='true'
elif i in result and result[i] == False:
result[i]='false'
else:
result[i]='free'
return [True, result]
A=Literal('A')
B=Literal('B')
C=Literal('C')
D=Literal('D')
KB=[{A, B}, {A, -C}, {-A, B, D}]
print(DPLL(KB))
26
OUTPUT
RESULT
Thus the program to implement Propositional Model checking Algorithm is implemented and executed
successfully.
27
EX.No. 8 Implement Forward Chaining Algorithm
DATE:
AIM
ALGORITHM
PROGRAM
def main():
print("*-----Forward--Chaining-----*", end='')
display()
x = int(input())
print(" \n", end='')
if x == 1 or x == 2:
print(" Chance Of Frog ", end='')
elif x == 3 or x == 4:
print(" Chance of Canary ", end='')
else:
print("\n-------In Valid Option Select --------", end='')
if x >= 1 and x <= 4:
print("\n X is ", end='')
28
print(database[x-1], end='')
print("\n Color Is 1.Green 2.Yellow", end='')
print("\n Select Option ", end='')
k = int(input())
if k == 1 and (x == 1 or x == 2): # frog0 and green1
print(" yes it is ", end='')
print(knowbase[0], end='')
print(" And Color Is ", end='')
print(knowbase[2], end='')
elif k == 2 and (x == 3 or x == 4): # canary1 and yellow3
print(" yes it is ", end='')
print(knowbase[1], end='')
print(" And Color Is ", end='')
print(knowbase[3], end='')
else:
print("\n---InValid Knowledge Database", end='')
if __name__ == "__main__":
main()
OUTPUT
*-----Forward--Chaining-----*
X is
1.Croaks
2.Eat Flies
3.shrimps
4.Sings
Select One 1
Chance Of Frog
X is Croaks
Color Is
1.Green
2.Yellow
Select Option 1
yes it is Frog And Color Is Green
RESULT
Thus the program to implement Forward Chaining Algorithm is implemented and executed successful
29
EX.No. 9 Implement backward Chaining Algorithm
DATE:
AIM
ALGORITHM
1. The code starts with a function called display () which prints out the text "X is 1.frog 2.canary"
2. And then asks for input from the user, asking them to select one of two options: Chance of eating flies or
Chance of shrimping.
3. If they choose either option, it will print out what that option would be in green or yellow color respectively.
4. The next line is x = int (input ()) which takes the value entered by the user and assigns it to variable x.
5. The if statement checks whether x equals 1 or 2
6. So if they enter 1 as their answer, it will print out "Chance of eating flies"
7. Otherwise it will print "Chance of shrimping".
PROGRAM
def display():
print("\n X is \n1.frog \n2.canary ", end='')
print("\n Select One ", end='')
def main():
print("*-----Backward--Chaining-----*", end='')
display()
x = int(input())
print(" \n", end='')
if x == 1:
print(" Chance Of eating flies ", end='')
elif x == 2:
print(" Chance of shrimping ", end='')
else:
print("\n-------In Valid Option Select --------", end='')
if x >= 1 and x <= 2:
print("\n X is ", end='')
print(knowbase[x-1], end='')
print("\n1.green \n2.yellow")
k = int(input())
if k == 1 and x == 1: # frog0 and green1
print(" yes it is in ", end='')
30
print(color[0], end='')
print(" colour and will ", end='')
print(database[0])
elif k == 2 and x == 2: # canary1 and yellow3
print(" yes it is in", end='')
print(color[1], end='')
print(" Colour and will ", end='')
print(database[1])
else:
print("\n---InValid Knowledge Database", end='')
if __name__ == "__main__":
main()
OUTPUT
*-----Backward--Chaining-----*
X is
1.frog
2.canary
Select One 1
Chance Of eating flies
X is Frog
1.green
2.yellow
1
yes it is in Green colour and will Croak
RESULT
Thus the program to implement backward chaining algorithm is implemented and executed successfully.
31
EX.No. 10 Implement Naïve Bayes Models
DATE:
AIM
ALGORITHM
PROGRAM
32
OUTPUT
[0 2 1 1 0 0 2 2 1 2 1 0 1 2 0 2 2 0 2 1 1 2 2 0 1 0 0 2 2 0 0 2 0 1 1 1 1
1 2 1 1 0 0 2 1 0 1 0 2 2]
[0 2 1 1 0 0 2 2 1 2 1 0 1 2 0 2 2 0 2 1 1 2 2 0 1 0 0 2 2 0 0 2 0 1 1 1 1
1 2 1 1 0 0 2 1 0 1 0 2 2]
accuracyScore is 1.0
confusion matrix [[16 0 0]
[ 0 17 0]
[ 0 0 17]]
RESULT
Thus the program to implement Naïve Bayes Model is implemented and executed successfully.
33
EX.No. 11 Implement Bayesian Networks and perform inferences
DATE:
AIM:
To Implement Bayesian Networks and perform inferences.
ALGORITHM:
34
19. Next, it calculates the cross entropy loss between target and predicted values.
20. Then, it calculates the cost function which is then minimized using Adam optimizer.
21. Finally, it prints out the predicted value and total cost after every iteration of optimization process.
22. The code starts by defining a function called draw_graph that takes in a predicted value.
23. The code then creates two subplots on the same figure, one for each of the predictions.
24. The first subplot is created with fig_1 and has an index of 1, which means it's the second plot in this figure.
25. This plot will have two axes: x-axis and y-axis.
26. The x-axis represents time, while the y-axis represents accuracy percentage (0% to 100%).
27. The second subplot is created with fig_2 and has an index of 2, which means it's the third plot in this figure.
28. This plot will also have two axes: x-axis and y-axis but they represent different values than those on fig_1 .
29. The code is a function that takes in an input of predicted and returns the accuracy, cross entropy, and KL
values.
30. The first line of code calculates the size of the tensor using target_tensor.size(0) which will be equal to 1
because it is a one-dimensional tensor.
31. Next, we have the function draw_graph which draws a graph with two subplots; one for accuracy and one for
cross entropy.
32. The last line prints out some statistics on how accurate this prediction was.
PROGRAM
import numpy as np
from sklearn import datasets
import torch
import torch.nn as nn
import torch.optim as optim
import torchbnn as bnn
import matplotlib.pyplot as plt
dataset = datasets.load_iris()
data = dataset.data
target = dataset.target
data_tensor = torch.from_numpy(data).float()
target_tensor = torch.from_numpy(target).long()
model = nn.Sequential(bnn.BayesLinear(prior_mu=0, prior_sigma=0.1, in_features=4, out_features=100),
nn.ReLU(), bnn.BayesLinear(prior_mu=0, prior_sigma=0.1, in_features=100, out_features=3), )
cross_entropy_loss = nn.CrossEntropyLoss()
35
klloss = bnn.BKLLoss(reduction='mean', last_layer_only=False)
klweight = 0.01
optimizer = optim.Adam(model.parameters(), lr=0.01)
for step in range(3000):
models = model(data_tensor)
cross_entropy = cross_entropy_loss(models, target_tensor)
kl = klloss(model)
total_cost = cross_entropy + klweight*kl
optimizer.zero_grad()
total_cost.backward()
optimizer.step()
_, predicted = torch.max(models.data, 1)
final = target_tensor.size(0)
correct = (predicted == target_tensor).sum()
print('- Accuracy: %f %%' % (100 * float(correct) / final))
print('- CE : %2.2f, KL : %2.2f' % (cross_entropy.item(), kl.item()))
def draw_graph(predicted):
fig = plt.figure(figsize=(16, 8))
fig_1 = fig.add_subplot(1, 2, 1)
fig_2 = fig.add_subplot(1, 2, 2)
z1_plot = fig_1.scatter(data[:, 0], data[:, 1], c=target, marker='v')
z2_plot = fig_2.scatter(data[:, 0], data[:, 1], c=predicted)
plt.colorbar(z1_plot, ax=fig_1)
plt.colorbar(z2_plot, ax=fig_2)
fig_1.set_title("REAL")
fig_2.set_title("PREDICT")
plt.show()
models = model(data_tensor)
_, predicted = torch.max(models.data, 1)
draw_graph(predicted)
36
OUTPUT
RESULT
Thus, the program to implement Bayesian Networks and perform inferences is implemented and executed
successfully.
37