Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views37 pages

AI Lab Record

The document outlines various artificial intelligence experiments implemented in Python, including the 8 Puzzle Problem, 8 Queen Problem, Crypt-Arithmetic Problem, A* Algorithm, and Min-Max Algorithm. Each experiment includes an aim, algorithm, program code, and output results. The document serves as a laboratory manual for AI programming tasks.

Uploaded by

gowthamarvj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views37 pages

AI Lab Record

The document outlines various artificial intelligence experiments implemented in Python, including the 8 Puzzle Problem, 8 Queen Problem, Crypt-Arithmetic Problem, A* Algorithm, and Min-Max Algorithm. Each experiment includes an aim, algorithm, program code, and output results. The document serves as a laboratory manual for AI programming tasks.

Uploaded by

gowthamarvj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

INDEX

Ex.No Date Name Of The Experiment Page.No Staff Sign

1A 8 Puzzle Problem

1B 8 Queen Problem

1C Crypt-Arithmetic Problem

2 A* Algorithm

3 Min-Max Algorithm

4 Constraint Satisfaction Problem

5 Propositional Model Checking Algorithm

6A Forward Chaining

6B Backward Chaining

7 Naive Bayes Model

8 Bayesian Networks And Perform


Inferences

9 Mini-Project- Dog Vs Cat Classification


AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 1

Ex: 1.a 8 PUZZLE PROBLEM

Aim: To implement the 8 Puzzle Problem using python

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

Result : Thus the 8 - Puzzle Problem is solved by Python code.


AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 3

Ex: 1.b 8 QUEEN PROBLEM

Aim: To implement the 8 Queen Problem using python

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

# Taking number of queens as input from user


print ("Enter the number of queens")
N = int(input())

# here we create a chessboard


# NxN matrix with all elements set to 0
board = [[0]*N for _ in range(N)]

def attack(i, j):


#checking vertically and horizontally
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):

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]

Result : Thus the 8 - Puzzle Problem is solved by Python code.


5
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY

Ex: 1.C CRYPT-ARITHMETIC PROBLEM

Aim: To implement the Crypt-Arithmetic Problem using python

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

assigned[char] return num


def is_valid_assignment(word1, word2, result,
assigned): # First letter of any word
cannot be zero.
if assigned[word1[0]] == 0 or assigned[word2[0]] == 0 or
assigned[ result[0]] == 0:
return
False return True

def _solve(word1, word2, result, letters, assigned,


solutions): if not letters:
if is_valid_assignment(word1, word2, result,
assigned): num1 = find_value(word1,
assigned)
num2 = find_value(word2,
assigned) num_result =
find_value(result, assigned) if
num1 + num2 == num_result:
solutions.append((f'{num1} + {num2} = {num_result}',
assigned.copy()))
return
for num in range(10):
if num not in
assigned.values():
cur_letter =
letters.pop()
assigned[cur_letter] =
num
_solve(word1, word2, result, letters, assigned,
solutions) assigned.pop(cur_letter)
letters.append(cur_letter)

def solve(word1, word2, result):


letters = sorted(set(word1) | set(word2) | set(result))
if len(result) > max(len(word1), len(word2)) + 1 or
len(letters) > 10: print('0 Solutions!')
retur
n solutions
= []
_solve(word1, word2, result, letters, {},
solutions) if solutions:
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 7

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

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 Crypt-Arithmetic Problem is solved by Python code.


AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 8

Ex: 2 A* ALGORITHM

Aim: To implement the A* algorithm using python.

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

#distance of starting node from itself is zero


g[start_node] = 0
#start_node is root node i.e it has no parent nodes
#so start_node is set to its own parent node
parents[start_node] = start_node
while len(open_set) > 0:
n = None
#node with lowest f() is found
for v in open_set:
if n == None or g[v] + heuristic(v) < g[n] + heuristic(n):
n=v
if n == stop_node or Graph_nodes[n] == None:
pass
else:
for (m, weight) in get_neighbors(n):
#nodes 'm' not in first and last set are added to first
#n is set its parent
if m not in open_set and m not in closed_set:
open_set.add(m)
parents[m] = n
g[m] = g[n] + weight
#for each node m,compare its distance from start i.e g(m) to the
#from start through n node
else:
if g[m] > g[n] + weight:
#update g(m)
g[m] = g[n] + weight
#change parent of m to n
parents[m] = n
#if m in closed set,remove and add to open
if m in closed_set:
closed_set.remove(m)
open_set.add(m)
if n == None:
print('Path does not exist!')
return None

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 10

# if the current node is the stop_node


# then we begin reconstructin the path from it to the start_node
if n == stop_node:
path = []
while parents[n] != n:
path.append(n)
n = parents[n]
path.append(start_node)
path.reverse()
print('Path found: {}'.format(path))
return path
# remove n from the open_list, and add it to closed_list
# because all of his neighbors were inspected
open_set.remove(n)
closed_set.add(n)
print('Path does not exist!')
return None

#define fuction to return neighbor and its distance


#from the passed node
def get_neighbors(v):
if v in Graph_nodes:
return Graph_nodes[v]
else:
return None

Output
Path found: ['A', 'F', 'G', 'I', 'J']

Result : Thus the A* algorithm is implemented by Python code.

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 11

Ex: 3 MIN-MAX ALGORITHM

Aim: To implement Minimax algorithm for game playing (Alpha-Beta pruning)

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

 value of root := minimum 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
Define a function height() . This will take root
if root is null, then
o return 0
return 1 + (maximum of height(left of root) , height(right of root))
From the main method, do the following −
h := height(root)
helper(root, h, 0)
return root

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

root.val = min(root.left.val, root.right.val)


elif root.left:
root.val = root.left.val
elif root.right:
root.val = root.right.val
def height(self, root):
if not root:
return 0
return 1 + max(self.height(root.left), self.height(root.right))
def solve(self, root):
h = self.height(root)
self.helper(root, h, 0)
return root
def print_tree(root):
if root is not None:
print_tree(root.left)
print(root.val, end = ', ')
print_tree(root.right)
ob = Solution()
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)
print_tree(ob.solve(root))

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,

Result : Thus the MinMax algorithm is implemented using python

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 15

Ex: 4 CONSTRAINT SATISFACTION PROGRAM

Aim: To solve constraint satisfaction problem using python.

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()

# We're using .addVariables() this time since we're adding


# multiple variables that have the same interval.
# Since Strings are arrays of characters we can write
# "TF" instead of ['T','F'].
problem.addVariables("TF", range(1, 10))
problem.addVariables("WOUR", range(10))

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 16

# Telling Python that we need TWO + TWO = FOUR


def sum_constraint(t, w, o, f, u, r):
if 2*(t*100 + w*10 + o) == f*1000 + o*100 + u*10 + r:
return True

# Adding our custom constraint. The


# order of variables is important!
problem.addConstraint(sum_constraint, "TWOFUR")

# All the characters must represent different digits,


# there's a built-in constraint for that
problem.addConstraint(constraint.AllDifferentConstraint())

solutions = problem.getSolutions()
print("Number of solutions found: {}\n".format(len(solutions)))

# .getSolutions() returns a dictionary


for s in solutions:
print("T = {}, W = {}, O = {}, F = {}, U = {}, R = {}"
.format(s['T'], s['W'], s['O'], s['F'], s['U'], s['R']))

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

Result : Thus the constraint satisfaction problem is resolved successfully.

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 17

Ex: 5 PROPOSITIONAL MODEL CHECKING ALGORITHM

Aim: To implement the Proportional Model Checking Algorithm

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]

# Now we are concating characters,rooms,and weapons in symbols.


symbols=charecters+rooms+wreapons
# we are checking the model and get some truth value

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)

# They are the clue


knowledge_base.add(And(
Not(mustard),Not(kitchen),Not(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

Result : Thus the Proportional Model Checking Algorithm is implemented by Python


code.

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 20

Ex: 6.a FORWARD CHAINING

Aim: To implement the Forward Chaining program in python code.


Algorithm

1. Initialize rules and facts.


2. Evaluate each rule using the evaluate_rule method.
3. If all premises are true, add the conclusion to the facts.
4. Repeat until no new facts are derived.
5. Forward-chaining class encapsulates rules and facts.
6. Evaluate method iterates through rules until convergence.
7. Evaluate_rule method checks premises and adds conclusions.
8. The input is Knowledge Base (KB): Set of rules (premises → conclusion)
Initial Facts: Known facts
Derived Facts: List of facts derived from the KB
9. Time Complexity: O(n^2), where n is the number of rules.
10. Space Complexity: O(n), where n is the number of rules and facts

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

def evaluate_rule(self, rule):


T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 21

premises = rule['premises']
conclusion = rule['conclusion']

if all(premise in self.facts for premise in premises):


if conclusion not in self.facts:
self.facts.append(conclusion)
return True
return False

# Define rules
rules = [
{'premises': ['A', 'B'], 'conclusion': 'C'},
{'premises': ['C', 'D'], 'conclusion': 'E'},
{'premises': ['E'], 'conclusion': 'F'}
]

# Define initial facts


facts = ['A', 'B', 'D']

# Create Forward Chaining instance


fc = ForwardChaining(rules, facts)

# Evaluate rules
result = fc.evaluate()

print("Derived Facts:", result)

OUTPUT
Derived Facts: ['A', 'B', 'D', 'C', 'E', 'F']

Result : Thus the Forward Chaining is is implemented by Pythoncode.

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 22

Ex: 6.b BACKWARD CHAINING

Aim: To implement the Forward Chaining program in python code.

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

def backward_chain(self, goal):


for rule in self.rules:
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 23

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']

# Define initial facts


initial_facts = ['G', 'H', 'I']

# Create Backward Chaining instance


bc = BackwardChaining(rules, goals)
bc.facts = initial_facts

# Evaluate rules
result = bc.evaluate()

print("Derived Facts:", result)

OUTPUT
Derived Facts: ['G', 'H', 'I', 'A', 'B', 'C', 'D', 'E', 'F']

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 24

Result : Thus the Backward Chaining is is implemented by Pythoncode.

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 25

Ex: 7 NAIVE BAYES MODELS

Aim: To implement the Naive Bayes Model using python

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

# eg: yes and no encoded to 1 and 0


def encode_class(mydata):
classes = []
for i in range(len(mydata)):
if mydata[i][-1] not in classes:
classes.append(mydata[i][-1])
for i in range(len(classes)):
for j in range(len(mydata)):
if mydata[j][-1] == classes[i]:
mydata[j][-1] = i
return mydata

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 26

# Splitting the data


def splitting(mydata, ratio):
train_num = int(len(mydata) * ratio)
train = []
# initially testset will have all the dataset

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

# Group the data rows under each class yes or


# no in dictionary eg: dict[yes] and dict[no]
def groupUnderClass(mydata):
dict = {}
for i in range(len(mydata)):
if (mydata[i][-1] not in dict):
dict[mydata[i][-1]] = []
dict[mydata[i][-1]].append(mydata[i])
return dict

# Calculating Mean

def mean(numbers):
return sum(numbers) / float(len(numbers))

# Calculating Standard Deviation


def std_dev(numbers):
avg = mean(numbers)
variance = sum([pow(x - avg, 2) for x in numbers]) / float(len(numbers) - 1)
return math.sqrt(variance)

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

# find Mean and Standard Deviation under each class


def MeanAndStdDevForClass(mydata):
info = {}
dict = groupUnderClass(mydata)
for classValue, instances in dict.items():
info[classValue] = MeanAndStdDev(instances)
return info

# Calculate Gaussian Probability Density Function


def calculateGaussianProbability(x, mean, stdev):
expo = math.exp(-(math.pow(x - mean, 2) / (2 * math.pow(stdev, 2))))
return (1 / (math.sqrt(2 * math.pi) * stdev)) * expo

# Calculate Class Probabilities


def calculateClassProbabilities(info, test):
probabilities = {}
for classValue, classSummaries in info.items():
probabilities[classValue] = 1

for i in range(len(classSummaries)):
mean, std_dev = classSummaries[i]
x = test[i]
probabilities[classValue] *= calculateGaussianProbability(x, mean, std_dev)
return probabilities

# Make prediction - highest probability is the prediction


def predict(info, test):
probabilities = calculateClassProbabilities(info, test)
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 28

bestLabel, bestProb = None, -1


for classValue, probability in probabilities.items():
if bestLabel is None or probability > bestProb:
bestProb = probability
bestLabel = classValue
return bestLabel

# returns predictions for a set of examples


def getPredictions(info, test):
predictions = []
for i in range(len(test)):
result = predict(info, test[i])
predictions.append(result)
return predictions

# 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

# add the data path in your system


filename = r'E:\user\MACHINE LEARNING\machine learning algos\Naive
bayes\filedata.csv'

# load the file and store it in mydata list


mydata = csv.reader(open(filename, "rt"))
mydata = list(mydata)
mydata = encode_class(mydata)
for i in range(len(mydata)):
mydata[i] = [float(x) for x in mydata[i]]
T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 29

# split ratio = 0.7


# 70% of data is training data and 30% is test data used for testing
ratio = 0.7
train_data, test_data = splitting(mydata, ratio)
print('Total number of examples are: ', len(mydata))
print('Out of these, training examples are: ', len(train_data))
print("Test examples are: ", len(test_data))

# 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

Total number of examples are: 200


Out of these, training examples are: 140
Test examples are: 60
Accuracy of your model is: 71.2376788

Result : Thus the Naive Bayes Model using python is implemented.

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 30

Ex: 8 BAYESIAN NETWORKS AND PERFORM INFERENCES

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 corresponding directed acyclic graph is depicted in below figure.

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

import pylab as plt

# Defining Bayesian Structure


model = BayesianNetwork([('Guest', 'Host'), ('Price', 'Host')])

# Defining the CPDs:


cpd_guest = TabularCPD('Guest', 3, [[0.33], [0.33], [0.33]])
cpd_price = TabularCPD('Price', 3, [[0.33], [0.33], [0.33]])
cpd_host = TabularCPD('Host', 3, [[0, 0, 0, 0, 0.5, 1, 0, 1, 0.5],
[0.5, 0, 1, 0, 0, 0, 1, 0, 0.5],
[0.5, 1, 0, 1, 0.5, 0, 0, 0, 0]],
evidence=['Guest', 'Price'], evidence_card=[3, 3])

# Associating the CPDs with the network structure.


model.add_cpds(cpd_guest, cpd_price, cpd_host)

model.check_model()

# Infering the posterior probability


from pgmpy.inference import VariableElimination

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

Ex: 9 MINI-PROJECT DOG VS CAT CLASSIFICATION

Aim: To implement the Dog- Cat classification system using python

Procedure & Program


The Asirra (Dogs VS Cats) dataset:
The Asirra (animal species image recognition for restricting access) dataset was
introduced in 2013 for a machine learning competition. The dataset includes 25,000
images with equal numbers of labels for cats and dogs.

Download
https://www.kaggle.com/c/dogs-vs-cats/data

8. Import the libraries:


import numpy as np
import pandas as pd
from keras.preprocessing.image import ImageDataGenerator,load_img
from keras.utils import to_categorical
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import random
import os

9. Define image properties:


Image_Width=128
Image_Height=128
Image_Size=(Image_Width,Image_Height)

T
AD3311 - ARTIFICIAL INTELLIGENCE LABORATORY 34

Image_Channels=3

10. Prepare dataset for training


model: filenames=os.listdir("./dogs-vs-
cats/train")categories=[]
for f_name in filenames:
category=f_name.split('.')[0]
if category=='dog':
categories.append(1)
else:
categories.append(0)
df=pd.DataFrame({
'filename':filenames,
'category':categories
})

11. Create the neural net model:


from keras.models import Sequential
from keras.layers import Conv2D,MaxPooling2D,\
Dropout,Flatten,Dense,Activation,\
BatchNormalization
model=Sequential()
model.add(Conv2D(32,(3,3),activation='relu',input_shape=(Image_Width,Image_Hei
ght,Image_Channels)))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(64,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Conv2D(128,(3,3),activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Dropout(0.25))
model.add(Flatten())

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'])

12. Analyzing model:


. model.summary()

13. Test data preparation:

test_filenames = os.listdir("./dogs-vs-cats/test1")
test_df = pd.DataFrame({
'filename': test_filenames
})
nb_samples = test_df.shape[0]

14. Make categorical prediction:

predict = model.predict_generator(test_generator,
steps=np.ceil(nb_samples/batch_size))
15. Convert labels to categories:

test_df['category'] = np.argmax(predict, axis=-1)


label_map = dict((v,k) for k,v in train_generator.class_indices.items())

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

Result : Thus Cat – Dog prediction is implemented using Python.

You might also like