AIDS Lab Manual
AIDS Lab Manual
DEPARTMENT OF
ARTIFICIAL INTELLIGENCE AND DATA
SCIENCE
BACHELOR OF TECHNOLOGY DEGREE COURSE
AD3311
Department :
Reg. No :
Roll No :
PARK COLLEGE OF ENGINEERING AND TECHNOLOGY
KANIYUR, COIMBATORE-641659.
BONAFIDE CERTIFICATE
by Mr. / Ms .............................................................................................. of
department of ......................................................................................................
Signature Signature
Faculty In-Charge Head of the Department
INDEX
Expt.
Date Name of Experiment Marks Signature
No.
2 Implement A* Algorithm
AIM:
To Implement basic search strategies – 8-Puzzle Problem.
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:
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)
cnt = 0
while True:
if len(current_nodes) == 0:
return -1
next_moves = self.find_next(node)
dict[move] = cnt + 1
return cnt + 1
cnt += 1
moves = {
0: [1, 3],
1: [0, 2, 4],
2: [1, 5],
3: [0, 4, 6],
4: [1, 3, 5, 7],
5: [2, 4, 8],
6: [3, 7],
7: [4, 6, 8],
8: [5, 7],
results = []
pos_0 = node.index(0)
new_node = list(node)
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))
OUTPUT:
NO OF MOVES== 4
Result:
Thus the program to implement 8 puzzles search strategy is implemented and executed
successfully.
Exp No: 1(b) Date:
AIM:
To Implement basic search strategies – 8-Queens Problem.
Algorithm:
Program:
N = int(input())
for k in range(0,N):
if board[i][k]==1 or board[k][j]==1:
return True
#checking diagonally
for k in range(0,N):
for l in range(0,N):
if (k+l==i+j) or (k-l==i-j):
if board[k][l]==1:
return True
return False
def N_queens(n):
if n==0:
return True
for i in range(0,N):
for j in range(0,N):
board[i][j] = 1
if N_queens(n-1)==True:
return True
board[i][j] = 0
return False
N_queens(N)
for i in board:
print (i)
OUTPUT:
[1, 0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 0, 1]
[0, 0, 0, 0, 0, 1, 0, 0]
[0, 0, 1, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 0, 0, 1, 0]
[0, 1, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 1, 0, 0, 0, 0]
Result:
Thus the program to implement 8 queens search strategy is implemented and executed
successfully.
Exp No: 1(c) Date:
AIM:
To Implement basic search strategies – Crypt arithmetic.
Algorithm:
Program:
num = 0
num = num * 10
num += assigned[char]
return num
result[0]] == 0:
return False
return True
def _solve(word1, word2, result, letters, assigned, solutions):
if not letters:
return
cur_letter = letters.pop()
assigned[cur_letter] = num
assigned.pop(cur_letter)
letters.append(cur_letter)
print('0 Solutions!')
return
solutions = []
if solutions:
print('\nSolutions:')
for soln in solutions:
print(f'{soln[0]}\t{soln[1]}')
if __name__ == '__main__':
OUTPUT:
CRYPTARITHMETIC PUZZLE SOLVER
WORD1 + WORD2 = RESULT
Enter WORD1: SEND
Enter WORD2: MORE
Enter RESULT: MONEY
Solutions:
9567 + 1085 = 10652 {'Y': 2, 'S': 9, 'R': 8, 'O': 0, 'N': 6, 'M': 1, 'E':
5, 'D': 7}
Result:
Thus the program to implement crypt arithmetic search strategy is implemented and executed
successfully.
Exp No: 2(a) Date:
Implement A* Algorithm
AIM:
To Implement A* Algorithm.
Algorithm:
Program:
class State(object):
self.children = []
self.parent = parent
self.value = value
self.dist = 0
if parent:
self.start = parent.start
self.goal = parent.goal
self.path = parent.path[:]
self.path.append(value)
else:
self.path = [value]
self.start = start
self.goal = goal
def GetDistance(self):
pass
def CreateChildren(self):
pass
# Creating subclass
class State_String(State):
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]
return dist
def CreateChildren(self):
if not self.children:
for i in range(len(self.goal)-1):
val = self.value
self.children.append(child)
class A_Star_Solver:
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))
closesetChild = self.priorityQueue.get()[2]
closesetChild.CreateChildren()
self.vistedQueue.append(closesetChild.value)
count += 1
if not child.dist:
self.path = child.path
break
self.priorityQueue.put((child.dist,count,child))
if not self.path:
return self.path
if __name__ == "__main__":
start1 = "secure"
goal1 = "rescue"
print("Starting....")
a = A_Star_Solver(start1,goal1)
a.Solve()
for i in range(len(a.path)):
print("{0}){1}".format(i,a.path[i]))
OUTPUT:
Starting....
0)secure
1)secrue
2)sercue
3)srecue
4)rsecue
5)rescue
Result:
AIM:
To Implement Minimax algorithm for game playing.
Algorithm:
Program:
return best
else:
best = MAX
# Recur for left and
# right children
for i in range(0, 2):
return best
# Driver Code
if __name__ == "__main__":
OUTPUT:
The optimal value is : 5
Result:
Thus the program to implement Minimax algorithm for game playing is implemented and
executed successfully.
Exp No: 4 Date:
AIM:
To solve constraint satisfaction problems.
Algorithm:
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())
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.
Exp No: 5 Date:
AIM:
To Implement Propositional Model checking Algorithm.
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
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
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:
else:
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)
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=[]
storage.append(str(item[1:]))
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)
def pickX(literals, varList): # This function picks a literal from the variable set and works with it as a node in the tree
for x in varList:
if x not in literals:
break
return x
holder=[]
if x in item:
item.remove(x)
holder.append(item)
return holder
holder=[]
if x in item:
continue
else:
holder.append(item)
return holder
def unitResolution(clauses):
bool
i=0
# This part of the code goes through each and every clause until the all literals in the KB are resolved
newClauses=[]
clause=clauses[i]
if (len(clause) == 1):
literal=str(clause[0])
pattern=re.match("-", literal)
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
if item != clauses[i]:
if (nx in item):
item.remove(nx)
newClauses.append(item)
i=0
clauses=newClauses
# no unit clause
else:
i += 1
literals, cnf=unitResolution(clauses)
if (cnf == []):
return literals
return "notsatisfiable"
else:
# pick a literal which isn't set yet but has an impact on the Kb, and then work on it recursively
while True:
x=pickX(literals, varList)
x=str(x)
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:
result[i]='true'
result[i]='false'
else:
result[i]='free'
A=Literal('A')
B=Literal('B')
C=Literal('C')
D=Literal('D')
print(DPLL(KB))
OUTPUT:
[True, {'B': 'true', 'A': True, 'C': 'free', 'D': 'free'}]
Result:
Thus the program to implement Propositional Model checking Algorithm is implemented and
executed successfully.
Exp No: 6(a) Date:
AIM:
To Implement Forward Chaining Algorithm.
Algorithm:
Program:
def display():
print("*-----Forward--Chaining-----*", end='')
display()
x = int(input())
if x == 1 or x == 2:
elif x == 3 or x == 4:
else:
print(database[x-1], end='')
k = int(input())
print(knowbase[0], end='')
print(knowbase[2], end='')
print(knowbase[1], end='')
print(knowbase[3], end='')
else:
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
successfully.
Exp No: 6(b) Date:
Implement backward Chaining Algorithm
AIM:
To Implement backward chaining algorithm.
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
colour 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():
def main():
print("*-----Backward--Chaining-----*", end='')
display()
x = int(input())
print(" \n", end='')
if x == 1:
elif x == 2:
else:
print(knowbase[x-1], end='')
print("\n1.green \n2.yellow")
k = int(input())
print(color[0], end='')
print(database[0])
print(color[1], end='')
print(database[1])
else:
if __name__ == "__main__":
main()
OUTPUT:
*-----Backward--Chaining-----*
X is
1.frog
2.canary
Select One 1
X is Frog
1.green
2.yellow
Result:
Thus the program to implement backward chaining algorithm is implemented and executed
successfully.
Exp No: 7 Date:
AIM:
To Implement naïve bayes Models.
Algorithm:
Program:
# The dataset
iris = datasets.load_iris()
X = iris.data
Y = iris.target
model = GaussianNB()
model.fit(X_train, Y_train)
# Predictions
model_predictions = model.predict(X_test)
print("\n",model_predictions)
print("\n",Y_test)
# Accuracy of prediction
accuracyScore = accuracy_score(Y_test, model_predictions)
print("\naccuracyScore is",accuracyScore )
cm=confusion_matrix(Y_test,model_predictions)
print("\nconfusion matrix",cm)
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
[ 0 17 0]
[ 0 0 17]]
Result:
Thus the program to implement Naïve Bayes Model is implemented and executed successfully.
Exp No: 8 Date:
AIM:
To Implement Bayesian Networks and perform inferences.
Algorithm:
Program:
import numpy as np
import torch
import torch.nn as nn
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(
out_features=100),
nn.ReLU(),
out_features=3),
cross_entropy_loss = nn.CrossEntropyLoss()
klweight = 0.01
optimizer = optim.Adam(model.parameters(), lr=0.01)
models = model(data_tensor)
kl = klloss(model)
optimizer.zero_grad()
total_cost.backward()
optimizer.step()
_, predicted = torch.max(models.data, 1)
final = target_tensor.size(0)
def draw_graph(predicted):
fig_1 = fig.add_subplot(1, 2, 1)
fig_2 = fig.add_subplot(1, 2, 2)
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)
OUTPUT:
Result:
Thus, the program to implement Bayesian Networks and perform inferences is implemented and
executed successfully.