AI Lab Record
AI Lab Record
1A 8 Puzzle Problem
1B 8 Queen Problem
1C Crypt-Arithmetic Problem
2 A* Algorithm
3 Min-Max Algorithm
6A Forward Chaining
6B Backward Chaining
Algorithm
START
1. In order to maintain the list of live nodes, algorithm LCSearch employs the
functions Least() and Add().
2. Least() identifies a live node with the least c(y), removes it from the list, and
returns it.
3. Add(y) adds y to the list of live nodes.
4. Add(y) implements the list of live nodes as a min-heap.
END
Program
from collections import deque
def solve_puzzle(start):
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
queue = deque([(start, [])])
visited = set()
while queue:
state, path = queue.popleft()
if state == goal:
return path + [state]
if tuple(state) in visited:
continue
visited.add(tuple(state))
for i in range(9):
if state[i] == 0:
for j in range(9):
if abs(i - j) in [3, 1] and i // 3 == j // 3 or abs(i - j) in [3, 1] and i % 3 == j % 3:
new_state = list(state)
new_state[i], new_state[j] = new_state[j], new_state[i]
queue.append((new_state, path + [state]))
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 2
return None
start = [1, 2, 3, 4, 5, 6, 7, 0, 8]
solution = solve_puzzle(start)
if solution:
for state in solution:
print(state)
else:
print("No solution found")
Output
1 2 3
5 6 0
7 8 4
1 2 3
5 0 6
7 8 4
1 2 3
5 8 6
7 0 4
1 2 3
5 8 6
0 4 7
Algorithm
START
1. begin from the leftmost column
2. if all the queens are placed,
return true/ print configuration
3. check for all rows in the current column
a) if queen placed safely, mark row and column; and
recursively check if we approach in the current
configuration, do we obtain a solution or not
b) if placing yields a solution, return true
c) if placing does not yield a solution, unmark and
try other rows
4. if all rows tried and solution not obtained, return
false and backtrack
END
Program
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 4
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):
if (not(attack(i,j))) and (board[i][j]!=1):
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
Enter the number of queens
8
[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]
Algorithm
1. The code starts by declaring a variable called num.
2. It is initialized to 0 and then it starts looping through the word, assigning a value of 10 for each letter
in the word.
3. The assignment statement assigns an integer value to every character in the string.
4. The code continues by checking if any of the first letters are zero or if any of the last letters are
zero.
5. If either one is true, then that means there was no valid assignment and so this function returns
false which will cause our program to stop running at that point.
6. The code begins by declaring two variables, num and assigned.
7. The first variable, num, will store the number of times that letter appears in the word.
8. The second variable, assigned, stores the letters in the word with their corresponding values.
9. Next, a for loop is created which iterates through each character in the word.
10. In this loop we check if any letter has been set to zero or not assigned at all.
11. If either condition is true then it returns false and stops iterating through characters within that
iteration of the loop.
12. Otherwise it increments num by 10 and assigns its value to assigned [char].
13. This process repeats until all characters have been checked for
14. The code is a function that takes in three arguments: word1, word2, and result.
15.The function is called solve and it returns the solutions to the equation of word1 + word2 = result
Program
def find_value(word,
assigned): num = 0
for char in word:
num = num * 10
num +=
6
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY
OUTPUT
Ex: 2 A* ALGORITHM
Algorithm
1. Add the starting square (or node) to the open list.
2. Repeat the following:
A) Look for the lowest F cost square on the open list. We refer to this as the current
square.
B). Switch it to the closed list.
C) For each of the 8 squares adjacent to this current square …
If it is not walk able or if it is on the closed list, ignore it. Otherwise do the
following.
If it isn’t on the open list, add it to the open list. Make the current square the
parent of this square. Record the F, G, and H costs of the square.
If it is on the open list already, check to see if this path to that square is
better, using G cost as the measure. A lower G cost means that this is a
better path. If so, change the parent of the square to the current square, and
recalculate the G and F scores of the square. If you are keeping your open
list sorted by F score, you may need to resort the list to account for the
change.
D) Stop when you:
Add the target square to the closed list, in which case the path has been
found, or
Fail to find the target square, and the open list is empty. In this case, there is
no path.
3. Save the path. Working backwards from the target square, go from each square to its
parent square until you reach the starting square. That is your path.
Program
def aStarAlgo(start_node, stop_node):
open_set = set(start_node)
closed_set = set()
g = {} #store distance from starting node
parents = {} # parents contains an adjacency map of all nodes
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 9
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 10
Output
Path found: ['A', 'F', 'G', 'I', 'J']
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 11
Algorithm
Define a function helper() . This will take root, h, currentHeight
if root is empty, then
o return
helper(left of root, h, currentHeight + 1)
helper(right of root, h, currentHeight + 1)
if currentHeight < h, then
o if currentHeight is even, then
if left of root and right of root are not null, then
value of root := maximum of value of left of root, value
ofright of root
otherwise when left of root is not null, then
value of root := value of left of root
otherwise when right of root is not null, then
value of root := value of right of root
o otherwise,
if left of root and right of root are not null, then
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 12
Program
class TreeNode:
def init (self, data, left = None, right = None):
self.val = data
self.left = left
self.right = right
class Solution:
def helper(self, root, h, currentHeight):
if not root:
return
self.helper(root.left, h, currentHeight + 1)
self.helper(root.right, h, currentHeight + 1)
if currentHeight < h:
if currentHeight % 2 == 0:
if root.left and root.right:
root.val = max(root.left.val, root.right.val)
elif root.left:
root.val = root.left.val
elif root.right:
root.val = root.right.val
else:
if root.left and root.right:
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 13
Input
root = TreeNode(0)
root.left = TreeNode(3)
root.right = TreeNode(0)
root.right.left = TreeNode(0)
root.right.right = TreeNode(0)
root.right.left.left = TreeNode(-3)
root.right.right.right = TreeNode(4)
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 14
Output
3, 3, -3, -3, -3, 4, 4,
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 15
Algorithm:
1. The code starts by defining some variables.
2. The first variable, assignment, is a list of strings.
3. The second variable, VARIABLES, is a list of five strings.
4. Next, the code defines some constraints.
5. Finally, the last constraint is that each string in DOMAIN must be associated with
at least one variable in VARIABLES.
6. The code then starts to search for an assignment that meets all the constraints.
7. If there are no more variables to select, then the code returns none.
8. Otherwise it backtracks through the assignment looking for a consistent
combination of values for each selected variable.
9. If successful, it assigns those values to corresponding variables in result and returns this
as solution.
10. The code first looks for a variable not yet assigned in the VARIABLES list.
11. If an assignment is found, the code checks to see if the variables are consistent with each
other.
12. If they are not, the code backtracks and tries again with a different variable.
Program
import constraint
problem = constraint.Problem()
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 16
solutions = problem.getSolutions()
print("Number of solutions found: {}\n".format(len(solutions)))
Output
Number of solutions found: 7
T = 7, W = 6, O = 5, F = 1, U = 3, R = 0
T = 7, W = 3, O = 4, F = 1, U = 6, R = 8
T = 8, W = 6, O = 7, F = 1, U = 3, R = 4
T = 8, W = 4, O = 6, F = 1, U = 9, R = 2
T = 8, W = 3, O = 6, F = 1, U = 7, R = 2
T = 9, W = 2, O = 8, F = 1, U = 5, R = 6
T = 9, W = 3, O = 8, F = 1, U = 7, R = 6
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 17
Algorithm
Problem Statement
Doctor Black has just been found dead in his mansion yesterday. Yesterday, there were
only Three People in Doctor Black’s mansion.
They are the prime suspects:
1. Col. Mustard
2. Prof. Plum
3. Ms. Scarlet
Police found Three Weapons in the mansion:
1. Knife
2. Revolver
3. Wrench
The murder has happened in one of the Three Rooms of the mansion:
1. Ballroom
2. Kitchen
3. Library
We have to find who the murderer of Dr. Black is. We can start creating the
knowledge base of our game engine by adding the above information. We will make
our game engine knowledgeable by implementing propositional logic. We will also
receive further clues during the investigation. That will be also added to the knowledge
base.
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 18
Program
import termcolor
# we have imported the logic file
from logic import *
#Now we are symboling all the characters,rooms,weapons
mustard=Symbol("col.mustard")
plum=Symbol("ProfPlum")
scarlet=Symbol("MsScarlet")
charecters=[mustard,plum,scarlet]
ballroom=Symbol("ballroom")
kitchen=Symbol("kitchen")
library=Symbol("library")
rooms=[ballroom,kitchen,library]
revolber=Symbol("revolber")
knife=Symbol("knife")
wrench=Symbol("wrench")
wreapons=[revolber,knife,wrench]
def check_knowledge(knowledge_base):
for symbol in symbols:
if model_check(knowledge_base,symbol):
termcolor.cprint(f"{symbol}:YES","green")
elif not model_check(knowledge_base,Not(symbol)):
print(f"{symbol}:Maybe")
# Createing knowledge base
knowledge_base=And(
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 19
Or(mustard,plum,scarlet),
Or(ballroom,kitchen,library),
Or(knife,revolber,wrench)
knowledge_base.add(Or(
Not(scarlet),Not(library),Not(wrench)
))
knowledge_base.add(Not(plum))
knowledge_base.add(Not(ballroom))
knowledge_base.add(Not(revolber))
check_knowledge(knowledge_base)
Output
MsScalket : Yes
Library : Yes
Knife : Yes
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 20
PROGRAM
class ForwardChaining:
def __init__(self, rules, facts):
self.rules = rules
self.facts = facts
def evaluate(self):
new_facts = True
while new_facts:
new_facts = False
for rule in self.rules:
if self.evaluate_rule(rule):
new_facts = True
return self.facts
premises = rule['premises']
conclusion = rule['conclusion']
# Define rules
rules = [
{'premises': ['A', 'B'], 'conclusion': 'C'},
{'premises': ['C', 'D'], 'conclusion': 'E'},
{'premises': ['E'], 'conclusion': 'F'}
]
# Evaluate rules
result = fc.evaluate()
OUTPUT
Derived Facts: ['A', 'B', 'D', 'C', 'E', 'F']
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 22
Algorithm
1. Initialize rules, goals, and facts.
2. Evaluate each goal using the backward_chain method.
3. Recursively traverse rules to find premises that support the goal.
4. Add derived facts to the facts list.
5. Backward Chaining class encapsulates rules, goals, and facts.
6. evaluate method iterates through goals and calls backward_chain.
7. backward_chain method recursively explores rules to derive facts.
8. The Knowledge Base (KB): Set of rules (premises → conclusion)
Goals: Target conclusions to prove
Initial Facts: Known facts
Derived Facts: List of facts derived from the KB
9. Time Complexity: O(n^d), where n is the number of rules and d is the maximum depth of the
rule chain.
10. Space Complexity: O(n), where n is the number of rules and facts.
PROGRAM
class BackwardChaining:
def __init__(self, rules, goals):
self.rules = rules
self.goals = goals
self.facts = []
def evaluate(self):
for goal in self.goals:
self.backward_chain(goal)
return self.facts
if rule['conclusion'] == goal:
premises = rule['premises']
for premise in premises:
if premise not in self.facts:
self.backward_chain(premise)
self.facts.append(goal)
# Define rules
rules = [
{'premises': ['A', 'B'], 'conclusion': 'C'},
{'premises': ['C', 'D'], 'conclusion': 'E'},
{'premises': ['E'], 'conclusion': 'F'},
{'premises': ['G'], 'conclusion': 'A'},
{'premises': ['H'], 'conclusion': 'B'},
{'premises': ['I'], 'conclusion': 'D'}
]
# Define goals
goals = ['F']
# Evaluate rules
result = bc.evaluate()
OUTPUT
Derived Facts: ['G', 'H', 'I', 'A', 'B', 'C', 'D', 'E', 'F']
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 24
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 25
Algorithm
1. The code starts by loading the data set.
2. The data is then split into a training and test set of equal size.
3. Next, a Gaussian Naive Bayes classifier is trained using the training set.
4. Then predictions are made on the test set with accuracy scores calculated for each
prediction.
5. Finally, a confusion matrix is created to show how well each prediction was classified
as correct or incorrect
6. The code is used to train a Gaussian Naive Bayes classifier and then use it to make
predictions.
7. The code prints the model's predictions, as well as the test set's output for comparison.
Program
# Importing library
import math
import random
import csv
# the categorical class names are changed to numberic data
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 26
test = list(mydata)
while len(train) < train_num:
# index generated randomly from range 0
# to length of testset
index = random.randrange(len(test))
# from testset, pop data rows and put it in train
train.append(test.pop(index))
return train, test
# Calculating Mean
def mean(numbers):
return sum(numbers) / float(len(numbers))
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 27
def MeanAndStdDev(mydata):
info = [(mean(attribute), std_dev(attribute)) for attribute in zip(*mydata)]
# eg: list = [ [a, b, c], [m, n, o], [x, y, z]]
# here mean of 1st attribute =(a + m+x), mean of 2nd attribute = (b + n+y)/3
# delete summaries of last class
del info[-1]
return info
for i in range(len(classSummaries)):
mean, std_dev = classSummaries[i]
x = test[i]
probabilities[classValue] *= calculateGaussianProbability(x, mean, std_dev)
return probabilities
# Accuracy score
def accuracy_rate(test, predictions):
correct = 0
for i in range(len(test)):
if test[i][-1] == predictions[i]:
correct += 1
return (correct / float(len(test))) * 100.0
# driver code
# prepare model
info = MeanAndStdDevForClass(train_data)
# test model
predictions = getPredictions(info, test_data)
accuracy = accuracy_rate(test_data, predictions)
print("Accuracy of your model is: ", accuracy)
Input
Dataset Download
https://gist.github.com/ktisha/c21e73a1bd1700294ef790c56c8aec1f
Output
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 30
Aim: To implement the Bayesian networks and perform inferences using python
Algorithm
A Bayesian network is a directed acyclic graph in which each edge corresponds to a
conditional dependency, and each node corresponds to a unique random variable.
Bayesian network consists of two major parts: a directed acyclic graph and a set of
conditional probability distributions
The directed acyclic graph is a set of random variables represented by nodes.
The conditional probability distribution of a node (random variable) is defined
for every possible outcome of the preceding causal node(s).
The goal is to calculate the posterior conditional probability distribution of each of the
possible unobserved causes given the observed evidence, i.e. P [Cause | Evidence].
Program
from pgmpy.models import BayesianNetwork
from pgmpy.factors.discrete import TabularCPD
import networkx as nx
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 31
model.check_model()
infer = VariableElimination(model)
posterior_p = infer.query(['Host'], evidence={'Guest': 2, 'Price': 2})
print(posterior_p)
nx.draw(model, with_labels=True)
plt.savefig('model.png')
plt.close()
Input
Datset Download
https://drive.google.com/file/d/17vwRLAY8uR-6vWusM5prn08it-BEGp-f/view
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 32
Output
Result : Thus the Bayesian networks and perform inferences using python is
implemented.
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 33
Download
https://www.kaggle.com/c/dogs-vs-cats/data
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 34
Image_Channels=3
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 35
model.add(Dense(512,activation='relu'))
model.add(BatchNormalization())
model.add(Dropout(0.5))
model.add(Dense(2,activation='softmax'))
model.compile(loss='categorical_crossentropy',
optimizer='rmsprop',metrics=['accuracy'])
test_filenames = os.listdir("./dogs-vs-cats/test1")
test_df = pd.DataFrame({
'filename': test_filenames
})
nb_samples = test_df.shape[0]
predict = model.predict_generator(test_generator,
steps=np.ceil(nb_samples/batch_size))
15. Convert labels to categories:
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 36
test_df['category'] = test_df['category'].replace(label_map)
test_df['category'] = test_df['category'].replace({ 'dog': 1, 'cat': 0 })
16. Visualize the prediction results:
sample_test = test_df.head(18)
sample_test.head()
plt.figure(figsize=(12, 24))
for index, row in sample_test.iterrows():
filename = row['filename']
category = row['category']
img = load_img("./dogs-vs-cats/test1/"+filename, target_size=Image_Size)
plt.subplot(6, 3, index+1)
plt.imshow(img)
plt.xlabel(filename + '(' + "{}".format(category) + ')' )
plt.tight_layout()
plt.show()
Output