0% found this document useful (0 votes)
18 views45 pages

AD8413 Artificial Intelligence-1

The document outlines the Faculty Lab Manual for the Artificial Intelligence Laboratory course (AD3311) for the academic year 2024-25, detailing the course objectives, experiments, and outcomes. It includes a structured syllabus with specific lab experiments focused on search strategies, game playing techniques, and logical reasoning systems. Additionally, it defines the vision, mission, program outcomes, and program specific outcomes for the Department of Artificial Intelligence and Data Science.
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)
18 views45 pages

AD8413 Artificial Intelligence-1

The document outlines the Faculty Lab Manual for the Artificial Intelligence Laboratory course (AD3311) for the academic year 2024-25, detailing the course objectives, experiments, and outcomes. It includes a structured syllabus with specific lab experiments focused on search strategies, game playing techniques, and logical reasoning systems. Additionally, it defines the vision, mission, program outcomes, and program specific outcomes for the Department of Artificial Intelligence and Data Science.
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/ 45

FACULTY LAB

MANUAL REGULATION – 2021

AD3311 – ARTIFICAL INTELLIGENCE LABORATORY

ACADEMIC YEAR: 2024 – 25 YEAR / SEMESTER: II/ III

Name of the Faculty : Prof. V. RAJARAM, MCA., M.E.,


Designation : Assistant Professor
Department : Artificial Intelligence and Data Science

1
TABLE OF CONTENTS

S.No. Particulars Page No.

1 Institute V/M 3

2 Department V/M/PEO; PO/PSO statements 4

3 Lab course syllabus 6

S.No. Page
Lab Experiments Details CO PO
No.

Implement basic search strategies – 8-Puzzle, 8 - Queens


1 CO1
problem, Cryptarithmetic.

2 Implement A* and memory bounded A* algorithms CO1

Implement Minimax algorithm for game playing (Alpha-


3 CO2
Beta pruning)

4 Solve constraint satisfaction problems CO2

5 Implement propositional model checking algorithms CO3

6 Implement forward chaining, backward chaining, and


CO3
resolution strategies

7 Build Naïve Bayes models CO4

8 Implement Bayesian networks and perform inferences CO4

CO1-
9 Mini-Project
CO4

Content Beyond the Syllabus

10. Solve path planning problem using Breadth First Search CO1

2
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA SCIENCE

Vision
• To be eminent and a technically sound Data Science professional by fulfilling
the dynamic societal needs.

Mission
• Nurture and enrich the students with a rural environment to have a strong
caliber and domain expertise with a successful academic career and
research perspective.

Programme Outcomes (PO):


Apply the knowledge of mathematics, science, engineering
PO1 Engineering
fundamentals, and an engineering specialization to the solution of
knowledge
complex engineering problems.
Identify, formulate, review research literature, and analyze
PO2 complex engineering problems reaching substantiated
Problem analysis
conclusions using first principles of mathematics, natural
sciences, and engineering sciences.
Design solutions for complex engineering problems and design
Design/
PO3 system components or processes that meet the specified needs
development of
with appropriate consideration for the public health and safety,
solutions and the cultural, societal, and environmental considerations.
Conduct
Use research-based knowledge and research methods including
PO4 investigations of
design of experiments, analysis and interpretation of data, and
complex
synthesis of the information to provide valid conclusions.
problems
Create, select, and apply appropriate techniques, resources, and
Modern tool modern engineering and IT tools including prediction and
PO5
usage modelling to complex engineering activities with an
understanding of the limitations.
Apply reasoning informed by the contextual knowledge to assess
PO6 The engineer societal, health, safety, legal and cultural issues and the
and society consequent responsibilities relevant to the professional
engineering practice.
Environment Understand the impact of the professional engineering solutions
PO7 and in societal and environmental contexts, and demonstrate the
sustainability knowledge of, and need for sustainable development.
PO8 Ethics Apply ethical principles and commit to professional ethics and

4
responsibilities and norms of the engineering practice.
PO9 Individual and Function effectively as an individual, and as a member or leader
team work in diverse teams, and in multidisciplinary settings.
Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as,
PO10 Communication being able to comprehend and write effective reports and design
documentation, make effective presentations, and give and
receive clear instructions.
Demonstrate knowledge and understanding of the
Project
PO11 engineering and management principles and apply these to one’s
management
own work, as a member and leader in a team, to manage projects
and finance
and in multidisciplinary environments
Recognize the need for, and have the preparation and ability to
PO12 Life-long
engage in independent and life-long learning in the broadest
learning context of technological change.

Programme Specific Outcomes (PSO):


Arrive at actionable Foresight, Insight, hind sight from data for solving business and
PSO1
engineering problems.
Apply the theoretical knowledge of AI and Data Analytics, develop data analytics and
PSO2 data visualization skills with practical industrial tools and techniques to solve societal
complex projects.
Able to carry out fundamental research to cater for the critical needs of the society
PSO3
through cutting edge technologies of AI.

5
AD3311 ARTIFICIALINTELLIGENCELABORATORY L T P C
0 0 3 1.5

OBJECTIVES:

• To design and implement search strategies


• To implement game playing techniques
• To implement CSP techniques
• To develop systems with logical reasoning
• To develop systems with probabilistic reasoning

LISTOF EXPERIMENTS:

1. Implement basic search strategies – 8-Puzzle, 8 - Queens problem,


Crypt arithmetic.
2. Implement A* and memory bounded A* algorithms
3. Implement Minimax algorithm for game playing (Alpha-Beta pruning)
4. Solve constraint satisfaction problems
5. Implement propositional model checking algorithms
6. Implement forward chaining, backward chaining, and resolution strategies
7. Build naïve Bayes models
8. Implement Bayesian networks and perform inferences
9. Mini-Project
TOTAL: 45 PERIODS

COURSE OUTCOMES:

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

6
CO – PO/PSO Mapping based on Weightage:

CO – PO PO PO PO PO PO PO PO1 PO1 PO1 PSO PSO PSO


PO6 PO7
PO/PSO 1 2 3 4 5 8 9 0 1 2 1 2 3

C208.1 3 3 3 3 3 _ 2 _ _ _ 3 3 3 3 3

C208.2 3 3 3 3 3 3 _ _ 3 _ 3 3 3 3 3

C208.3 3 3 3 3 1 3 _ _ 1 _ _ 3 3 3 3

C208.4 3 3 3 3 1 3 3 _ _ _ _ 3 3 3 3
C208
(Averag 3 3 3 3 2 3 3 _ 1 _ 3 3 3 3 3
e)
Contributions: 1- Low, 2- Medium, 3- High

7
Ex: No: 1a) 8 PUZZLE PROBLEM

Aim:
To write a Python Program to solve an 8-Puzzle Problem.
Algorithm:
1. Import the 'copy' for deepcopy method
2. Import the heap methods from the python library for the Priority Queue
3. Initialize the values for rows and columns.
4. Create a class for the priority queue and for structure of a node.
5. In the class for priority queue, define the functions for the following:
- For initializing the Priority Queue
- For inserting a new key
- For removing the minimum element from the Priority Queue
- To Check if the Queue is empty or not
6. In the class for structure of a node, define the functions for the following:
- Initialize the parent node, current node, matrix, empty space tile, order the
nodes based on costs
- Create new nodes
- To print N by N Matrix
- To know if (x,y) is a valid or invalid
- To print the path from the root node to the final node
- Solving the Puzzle using Branch and Bound Method

7. In the Main Code , Initialize the Matrix with value 0 assigned as an empty space.
8. Invoke the function solve() to solve the puzzle
9. Stop the Program

Program:
# Python code to display the way from the root node to the final
# destination node for N*N-1 puzzle
# algorithm by the help of Branch and Bound technique

# Importing the 'copy' for deepcopy method


import copy

# Importing the heap methods from the python


# library for the Priority Queue
from heapq import heappush, heappop

8
# This particular var can be changed to transform the program from 8 puzzle(n=3) int
o 15 puzzle(n=4) and so on ...
n=3

# bottom, left, top, right


rows = [ 1, 0, -1, 0 ]
cols = [ 0, -1, 0, 1 ]

# creating a class for the Priority Queue


class priorityQueue:

# Constructor for initializing a


# Priority Queue
def init (self):
self.heap = []

# Inserting a new key 'key'


def push(self, key):
heappush(self.heap, key)

# funct to remove the element that is minimum,


# from the Priority Queue
def pop(self):
return heappop(self.heap)

# funct to check if the Queue is empty or not


def empty(self):
if not self.heap:
return True
else:
return False

# structure of the node


class nodes:

def init (self, parent, mats, empty_tile_posi,costs, levels):

# This will store the parent node to the current node And helps in tracing the
# path when the solution is visible
self.parent = parent

# Useful for Storing the matrix


self.mats = mats

# useful for Storing the position where the


# empty space tile is already existing in the matrix
self.empty_tile_posi = empty_tile_posi

# Store no. of misplaced tiles


self.costs = costs

9
# Store no. of moves so far
self.levels = levels

# This func is used in order to form the priority queue based on


# the costs var of objects
def lt (self, nxt):
return self.costs < nxt.costs

# method to calc. the no. of


# misplaced tiles, that is the no. of non-blank
# tiles not in their final posi
def calculateCosts(mats, final) -> int:

count = 0
for i in range(n):
for j in range(n):
if ((mats[i][j]) and
(mats[i][j] != final[i][j])):
count += 1

return count

def newNodes(mats, empty_tile_posi, new_empty_tile_posi,


levels, parent, final) -> nodes:

# Copying data from the parent matrixes to the present matrixes


new_mats = copy.deepcopy(mats)

# Moving the tile by 1 position


x1 = empty_tile_posi[0]
y1 = empty_tile_posi[1]
x2 = new_empty_tile_posi[0]
y2 = new_empty_tile_posi[1]
new_mats[x1][y1], new_mats[x2][y2] = new_mats[x2][y2], new_mats[x1][y1]

# Setting the no. of misplaced tiles


costs = calculateCosts(new_mats, final)

new_nodes = nodes(parent, new_mats, new_empty_tile_posi,


costs, levels)
return new_nodes

# func to print the N by N matrix


def printMatsrix(mats):

for i in range(n):
for j in range(n):
print("%d " % (mats[i][j]), end = " ")

print()

10
# func to know if (x, y) is a valid or invalid matrix coordinates
def isSafe(x, y):

return x >= 0 and x < n and y >= 0 and y < n

# Printing the path from the root node to the final node
def printPath(root):

if root == None:
return

printPath(root.parent)
printMatsrix(root.mats)
print()

# method for solving N*N - 1 puzzle algo by utilizing the Branch and Bound technique.
empty_tile_posi is
# the blank tile position initially.
def solve(initial, empty_tile_posi, final):

# Creating a priority queue for storing the live


# nodes of the search tree
pq = priorityQueue()

# Creating the root node


costs = calculateCosts(initial, final)
root = nodes(None, initial,empty_tile_posi, costs, 0)

# Adding root to the list of live nodes


pq.push(root)

# Discovering a live node with min. cost and adding its children to the list of live
# nodes and finally deleting it from the list.
while not pq.empty():

# Finding a live node with min. estimatsed costs and deleting it form the list of the
# live nodes
minimum = pq.pop()

# If the min. is ans node


if minimum.costs == 0:

# Printing the path from the root to


# destination;
printPath(minimum)
return

# Generating all feasible children


for i in range(n):
new_tile_posi = [
minimum.empty_tile_posi[0] + rows[i],

11
minimum.empty_tile_posi[1] + cols[i], ]

if isSafe(new_tile_posi[0], new_tile_posi[1]):

# Creating a child node


child = newNodes(minimum.mats,
minimum.empty_tile_posi,
new_tile_posi,
minimum.levels + 1,
minimum, final,)

# Adding the child to the list of live nodes


pq.push(child)

# Main Code

# Initial configuration
# Value 0 is taken here as an empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]

# Final configuration that can be solved


# Value 0 is taken as an empty space
final = [ [ 1, 2, 3 ],
[ 5, 8, 6 ],
[ 0, 7, 4 ] ]

# Blank tile coordinates in the


# initial configuration
empty_tile_posi = [ 1, 2 ]

# Method call for solving the puzzle


solve(initial, empty_tile_posi, final)

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 7 4

12
Result:
Thus Python program to solve an 8-Puzzle problem is implemented successfully.

13
Ex: No: 1b) 8 QUEENS PROBLEM

Aim:
To write a Python Program to solve an 8-Puzzle Problem.
Algorithm:
1. Get the number of queens as an input from the user
2. Create a Chessboard NxN matrix with all elements set to 0
3. Define the function attack() to check the arrangement of queens vertically, horizontally
or diagonally.
4. Define the function N_queens() to place the n queens in their appropriate position in
the chess board
5. Invoke the function N_queens(N) and print the result.
6. Stop the program
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):
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
14
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 Python program to solve an 8-Queens problem is implemented successfully.

15
Ex: No: 1c CRYPTARITHMETIC

Aim:
To write a Python Program to solve an 8-Puzzle Problem.
Algorithm:
1. Import the module itertools
2. Define the function solve2()
3. Assign the values to the array letters
4. Assign a sequence of numbers from 0 to 9 to the variable digits
5. Substitute digits for the letters of the puzzle to form a valid calculation for the given
input
6. Perform permutation of the digits to the letters and then compute the expressions for
each word(send,more,money) and return the value
7. Invoke the function solve2() and print the result.
8. Stop the program
Program:
import itertools
def solve2():
letters = ('s', 'e', 'n', 'd', 'm', 'o', 'r', 'y')
digits = range(10)
for perm in itertools.permutations(digits, len(letters)):
sol = dict(zip(letters, perm))
if sol['s'] == 0 or sol['m'] == 0:
continue
send = 1000 * sol['s'] + 100 * sol['e'] + 10 * sol['n'] + sol['d']
more = 1000 * sol['m'] + 100 * sol['o'] + 10 * sol['r'] + sol['e']
money = 10000 * sol['m'] + 1000 * sol['o'] + 100 * sol['n'] + 10 *
sol['e'] + sol['y']
if send + more == money:
print(" send"," more"," money")
return send, more, money
print(solve2())

Output:
send more money
(9567, 1085, 10652)

Result:
Thus Python program to perform Crypt arithmetic is implemented successfully.

16
Ex: No: 2 TIC TAC TOE USING MINMAX ALGORITHM WITH ALPH BETA PRUNING

Aim : To write a Python program to solve tic tac toe gaming using MINIMAX with
ALPHA-BETA Pruning
Algorithm:

1. First, generate the entire game tree starting with the current position of the
game all the way up to the terminal states.
2. Apply the utility function to get the utility values for all the terminal states.

3. Determine the utilities of the higher nodes with the help of the utilities of the
terminal nodes. For instance, in the diagram below, we have the utilities for the
terminal states written in the squares.

4. Calculate the utility values with the help of leaves considering one layer at a
time until the root of the tree.

5. Eventually, all the backed-up values reach to the root of the tree, i.e., the
topmost point. At that point, MAX has to choose the highest value.

Alpha Beta Pruning:

The two-parameter can be defined as:

6. Alpha: The best (highest-value) choice we have found so far at any point along
the path of Maximizer. The initial value of alpha is -∞.

7. Beta: The best (lowest-value) choice we have found so far at any point along the
path of Minimizer. The initial value of beta is +∞. The Alpha-beta pruning to a
standard minimax algorithm returns the same move as the standard algorithm
does, but it removes all the nodes which are not really affecting the final
decision but making algorithm slow. Hence by pruning these nodes, it makes
the algorithm fast.

Program:

#tic tac toe with alpha beta pruning


from random import choice
from math import inf
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def Gameboard(board):
chars = {1: 'X', -1: 'O', 0: ' '}
for x in board:

17
for y in x:
ch = chars[y]
print(f'| {ch} |', end='')
print('\n' + '---------------')
print('===============')

def Clearboard(board):
for x, row in enumerate(board):
for y, col in enumerate(row):
board[x][y] = 0
def winningPlayer(board, player):
conditions = [[board[0][0], board[0][1], board[0][2]],
[board[1][0], board[1][1], board[1][2]],
[board[2][0], board[2][1], board[2][2]],
[board[0][0], board[1][0], board[2][0]],
[board[0][1], board[1][1], board[2][1]],
[board[0][2], board[1][2], board[2][2]],
[board[0][0], board[1][1], board[2][2]],
[board[0][2], board[1][1], board[2][0]]]

if [player, player, player] in conditions:


return True
return False

def gameWon(board):
return winningPlayer(board, 1) or winningPlayer(board, -1)

def printResult(board):
if winningPlayer(board, 1):
print('X has won! ' + '\n')
elif winningPlayer(board, -1):
print('O\'s have won! ' + '\n')
else:
print('Draw' + '\n')

def blanks(board):
blank = []
for x, row in enumerate(board):
for y, col in enumerate(row):
if board[x][y] == 0:
blank.append([x, y])
return blank

def boardFull(board):
if len(blanks(board)) == 0:

18
return True
return False
def setMove(board, x, y, player):
board[x][y] = player

def playerMove(board):
e = True
moves = {1: [0, 0], 2: [0, 1], 3: [0, 2],
4: [1, 0], 5: [1, 1], 6: [1, 2],
7: [2, 0], 8: [2, 1], 9: [2, 2]}
while e:
try:
move = int(input('Enter a number between 1-9: '))
if move < 1 or move > 9:
print('Invalid Move! Try again!')
elif not (moves[move] in blanks(board)):
print('Invalid Move! Try again!')
else:
setMove(board, moves[move][0], moves[move][1], 1)
Gameboard(board)
e = False
except(KeyError, ValueError):
print('Enter a number!')

def getScore(board):
if winningPlayer(board, 1):
return 10
elif winningPlayer(board, -1):
return -10

else:
return 0

def abminimax(board, depth, alpha, beta, player):


row = -1
col = -1
if depth == 0 or gameWon(board):
return [row, col, getScore(board)]
else:
for cell in blanks(board):
setMove(board, cell[0], cell[1], player)
score = abminimax(board, depth - 1, alpha, beta, -player)
if player == 1:
# X is always the max player
if score[2] > alpha:

19
alpha = score[2]
row = cell[0]
col = cell[1]
else:
if score[2] < beta:
beta = score[2]
row = cell[0]
col = cell[1]
setMove(board, cell[0], cell[1], 0)
if alpha >= beta:
break

if player == 1:
return [row, col, alpha]
else:
return [row, col, beta]

def o_comp(board):
if len(blanks(board)) == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
setMove(board, x, y, -1)
Gameboard(board)
else:
result = abminimax(board, len(blanks(board)), -inf, inf, -1)
setMove(board, result[0], result[1], -1)
Gameboard(board)
def x_comp(board):
if len(blanks(board)) == 9:
x = choice([0, 1, 2])
y = choice([0, 1, 2])
setMove(board, x, y, 1)
Gameboard(board)
else:
result = abminimax(board, len(blanks(board)), -inf, inf, 1)
setMove(board, result[0], result[1], 1)
Gameboard(board)

def makeMove(board, player, mode):


if mode == 1:
if player == 1:
playerMove(board)
else:
o_comp(board)
else:

20
if player == 1:
o_comp(board)
else:
x_comp(board)

def pvc():
while True:
try:
order = int(input('Enter to play 1st or 2nd: '))
if not (order == 1 or order == 2):
print('Please pick 1 or 2')
else:
break
except(KeyError, ValueError):
print('Enter a number')

Clearboard(board)
if order == 2:
currentPlayer = -1
else:
currentPlayer = 1
while not (boardFull(board) or gameWon(board)):
makeMove(board, currentPlayer, 1)
currentPlayer *= -1
printResult(board)

# Driver Code
print("=================================================")
print("TIC-TAC-TOE using MINIMAX with ALPHA-BETA Pruning")
print("=================================================")
pvc()

Output:
=================================================
TIC-TAC-TOE using MINIMAX with ALPHA-BETA Pruning
=================================================
Enter to play 1st or 2nd: 2
| || || |

| || || O |

| || || |

===============
Enter a number between 1-9: 5

21
| || || |

| || X || O |

| || || |

===============
| O || || |

| || X || O |

| || || |

===============
Enter a number between 1-9: 2
| O || X || |

| || X || O |

| || || |

===============
| O || X || |

| || X || O |

| || O || |

===============
Enter a number between 1-9: 8
Invalid Move! Try again!
Enter a number between 1-9:

Result:
Thus Python program to solve Tic Tac Toe problem using Minmax algorithm with
Alpha Beta Pruning is implemented successfully.

22
Ex: No: 3 IMPLEMENTATION OF A* ALGORITHM

Aim:
To implement A* algorithm for shortest path problem using Python.

Algorithm:
Step 1: Define a Class Node and initialize the nodes
Step 2: In the class Node, define the methods for the following:
• initialization of nodes, assigning names to the nodes
• find its neighbours and create a link to the existing nodes.
• to create a graph.
Step 3: Define the method astar_search() to perform the following:
• Create an empty lists for open and closed
• Add all the nodes to the open list.
• Assign a start node and a goal node
• Add the start node to the closed list
• Loop until the open list is empty:
->Get the neighbouring nodes, determine the lowest costnode by applying
heuristics
->Check if the neighbour to be added, if so append it the closed list
->Check if we have reached the goal, return the path (From Current Node to Start
Node By Node.parent)
Step 4: In the main Program, Assign the values for the nodes and heuristics.
Step 5: Invoke the method astar_search() and run the A* algorithm
Step 6: Display the shortest path from start node to the goal node.
Step 7: Stop the program.

Program:
def get(graph, a, b=None):

links = graph.setdefault(a, {})

if b is None:

return links

else:

return get(links,b)
class Node:

23
def init (self, name:str, parent:str):

self.name = name

self.parent = parent

self.g = 0
self.h = 0

self.f = 0

def eq (self, other):

return self.name == other.name

def lt (self, other):

return self.f < other.f

def repr (self):

return ('({0},{1})'.format(self.name, self.f))

def add_to_open(open, neighbor):


for node in open:

if (neighbor == node and neighbor.f > node.f):

return False
return True

def astar_search(graph, heuristics, start, end):

open = []
closed = []

start_node = Node(start, None)

goal_node = Node(end, None)

open.append(start_node)

while len(open) > 0:


open.sort()

current_node = open.pop(0)

closed.append(current_node)

if current_node == goal_node:

path = []

while current_node != start_node:

24
path.append(current_node.name + ': ' + str(current_node.g))

current_node = current_node.parent

path.append(start_node.name + ': ' + str(start_node.g))

return path[::-1]

neighbors = graph.get(current_node.name)

for key, value in neighbors.items():

neighbor = Node(key, current_node)

if(neighbor in closed):

continue

neighbor.g = current_node.g + get(graph,current_node.name, neighbor.name)

neighbor.h = heuristics.get(neighbor.name)

neighbor.f = neighbor.g + neighbor.h

if(add_to_open(open, neighbor) == True):

open.append(neighbor)

return None

g={'a':{'b':4,'c':3},'b':{'f':5,'e':12},'c':{'e':10,'d':7},'d':{'e':2},'e':{'z':5},'f':{'z':16},'z':{}}

h={'a':14,'b':12,'c':11,'d':6,'e':4,'f':11,'z':0}

path = astar_search(g, h, 'a', 'z')

print(path)
Output:

['a: 0', 'c: 3', 'd: 10', 'e: 12', 'z: 17']

Result:Thus A* algorithm has been implemented using Python successfully.

25
Ex: No: 4 CONSTRAINT SATISFACTION PROBLEM

Aim:
To Solve Map Coloring Problem using Backtracking by formulating the problem as a
Constraint Satisfaction Problem.

Algorithm:
Step 1: Define the functions for the following:
- is_complete()
- select_unassigned_variable()
- is_consistent()
- init_assignment()
- recursive_backtracking()
Step 2: Define a dictionary my_csp
Step 3: Invoke the function recursive_backtracking()
Step 4: Print the result.
Step 5: Stop the program.

Program:
counter = 0

DOMAINS = "DOMAINS"
VARIABLES = "VARIABLES"
CONSTRAINTS = "CONSTRAINTS"
FAILURE = "FAILURE"

def is_complete(assignment):
return None not in (assignment.values())

def select_unassigned_variable(variables, assignment):


for var in variables:
if assignment[var] is None:
return var

def is_consistent(assignment, constraints):


global counter
counter += 1
for constraint_violated in constraints:
if constraint_violated(assignment):
return False
return True

def init_assignment(csp):
assignment = {}
for var in csp[VARIABLES]:
assignment[var] = None

26
return assignment

def recursive_backtracking(assignment, csp):


if is_complete(assignment):
return assignment
var = select_unassigned_variable(csp[VARIABLES], assignment)
for value in csp[DOMAINS]:
assignment[var] = value
if is_consistent(assignment, csp[CONSTRAINTS]):
result = recursive_backtracking(assignment, csp)
if result != FAILURE:
return result
assignment[var] = None
return FAILURE

counter = 0

def eq(a, b): return a is not None and b is not None and a == b
def wa_nt(asmt): return eq(asmt["WA"], asmt["NT"])
def wa_sa(asmt): return eq(asmt["WA"], asmt["SA"])
def nt_sa(asmt): return eq(asmt["NT"], asmt["SA"])
def nt_q(asmt): return eq(asmt["NT"], asmt["Q"])
def sa_q(asmt): return eq(asmt["SA"], asmt["Q"])
def sa_nsw(asmt): return eq(asmt["SA"], asmt["NSW"])
def sa_v(asmt): return eq(asmt["SA"], asmt["V"])
def q_nsw(asmt): return eq(asmt["Q"], asmt["NSW"])
def v_t(asmt): return eq(asmt["V"], asmt["T"])

my_csp = {VARIABLES: ["WA", "NT", "Q", "NSW", "V", "SA", "T"],


DOMAINS: ["red", "green", "blue"],
CONSTRAINTS: [wa_nt, wa_sa, nt_sa, nt_q, sa_q, sa_nsw, sa_v, q_nsw, v_t]}

result = recursive_backtracking(init_assignment(my_csp), my_csp)


[counter, result]

Output:
[12, {'NSW': 'green', 'NT': 'green', 'Q': 'red', 'SA': 'blue', 'T': 'green', 'V': 'red', 'WA':
'red'}]

Result:
Thus a Map Coloring using Constraint Satisfaction problem using Python was
implemented successfully.

27
Ex: No: 5 PROPOSITIONAL MODEL CHECKING ALGORITHM

Aim:
To implement Propositional Model Checking Algorithm using Python.

Algorithm:

Step 1: Import the necessary packages from the module utils, logic, notebook.
Step 2: Implement the following Operations:
- Define a simple expression from Expr class with the function Symbol
- Define multiple symbols at the same time with the function symbols
- Combine Exprs with the regular Python infix and prefix operators
- Implement Expr class with overloading operators like S and others
- Represent the expressions with nested Expr
- DefinE a sentence with an implication arrow
Step 3: Stop the program.

Program:
from utils import *
from logic import *
from notebook import psource

#Simplest type of Expression defined with the function Symbol


In [2]:Symbol('x')
Out[2]:x

# define multiple symbols at the same time with the function symbols
In [3]:(x, y, P, Q, f) = symbols('x, y, P, Q, f')
In [4]:P S ~Q
Out[4]:(P S ~Q)

#Defining a Sentence
In [5]:sentence = P S ~Q
sentence.op
Out[5]:'S'

In [6]:sentence.args
Out[6]:(P, ~Q)

In [7]:P.op
Out[7]:'P'

In [8]:P.args
Out[8]:()

In [9]:Pxy = P(x, y)

28
Pxy.op
Out[9]:'P'

In [10]:Pxy.args
Out[10]:(x, y)

# Defined a Nested Expression


In [11]:3 * f(x, y) + P(y) / 2 + 1
Out[11]:(((3 * f(x, y)) + (P(y) / 2)) + 1)

In [12]:~(P S Q) |'==>'| (~P |~Q)


Out[12]:(~(P S Q) ==> (~P | ~Q))

In [13]:expr('~(P S Q) ==> (~P | ~Q)')


Out[13]:(~(P S Q) ==> (~P | ~Q))

In [14]:expr('sqrt(b ** 2 - 4 * a * c)')
Out[14]:sqrt(((b ** 2) - ((4 * a) * c)))

Result:
Thus Propositional Model Checking Algorithm using Python was implemented
successfully.

29
Ex: No: 6 a FORWARD CHAINING

Aim:
To implement Forward Chaining for a list of input parameters.

Algorithm:
Step 1: Define list facts to define the input parameters like the name and type of living
Beings.
Step 2:Define the function asser_fact() to construct a context mapping.
Step 3: Describe the actions of the engine.
Step 4: Print the result.
Step 5: Stop the program.
Program:
#Forward Chaining
global facts
global is_changed

is_changed = True
facts = [["vertebrate","duck"],["flying","duck"],["mammal","cat"]]

def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True

while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "mammal":
assert_fact(["vertebrate",A1[1]])
if A1[0] == "vertebrate":
assert_fact(["animal",A1[1]])
if A1[0] == "vertebrate" and ["flying",A1[1]] in facts:
assert_fact(["bird",A1[1]])

print(facts)

Output:
[['vertebrate', 'duck'], ['flying', 'duck'], ['mammal', 'cat'], ['animal', 'duck'], ['bird',
'duck'], ['vertebrate', 'cat'], ['animal', 'cat']]

Result:
Thus Forward Chaining has been implemented successfully.

30
Ex: No: 6 b BACKWARD CHAINING

Aim:
To implement Backward Chaining for a list of input parameters.

Algorithm:
Step 1: Define list facts to define the input parameters like the name and type fruits.
Step 2: Define the function asser_fact() to construct a context mapping.
Step 3: Describe the actions of the engine.
Step 4: Print the result.
Step 5: Stop the program.

Program:

#Backward Chaining

global facts
global is_changed

is_changed = True
facts = [["plant","mango"],["eating","mango"],["seed","sprouts"]]

def assert_fact(fact):
global facts
global is_changed
if not fact in facts:
facts += [fact]
is_changed = True

while is_changed:
is_changed = False
for A1 in facts:
if A1[0] == "seed":
assert_fact(["plant",A1[1]])
if A1[0] == "plant":
assert_fact(["fruit",A1[1]])
if A1[0] == "plant" and ["eating",A1[1]] in facts:
assert_fact(["human",A1[1]])

print(facts)
Output:
[['plant', 'mango'], ['eating', 'mango'], ['seed', 'sprouts'], ['fruit', 'mango'], ['human',
'mango'], ['plant', 'sprouts'], ['fruit', 'sprouts']]

Result:
Thus Backward Chaining has been implemented successfully.

31
Ex: No: 7 NAÏVE BAYES MODEL

Aim:

To build a Naïve Bayes model for Weather Prediction.

Algorithm:

Step 1: Import the necessary modules

Step 2: Define the class Classifier and define the following functions:

- Define the constructor function to calculate probability


- Define calculate_prior() to calculate the individual probabilities
- Define get_cp() to calculate Likelihood of Evidence
- Define calculate_conditional_probabilities() to calculate the conditional
probabilities
- Define classify() to print the result

Step 3: Invoke the function calculate_conditional_probabilities() and classify()

Step 4: Stop the program

Program:

from functools import reduce


import pandas as pd
import pprint
class Classifier():
data = None
class_attr = None
priori = {}
cp = {}
hypothesis = None

def init (self,filename=None, class_attr=None ):


self.data = pd.read_csv(filename, sep=',', header =(0))
self.class_attr = class_attr

'''
probability(class) = How many times it appears in column

count of all class attribute


'''
def calculate_priori(self):
class_values = list(set(self.data[self.class_attr]))
class_data = list(self.data[self.class_attr])
for i in class_values:

32
self.priori[i] = class_data.count(i)/float(len(class_data))
print ("Priori Values: ", self.priori)

'''
Here we calculate the individual probabilities
P(outcome|evidence) = P(Likelihood of Evidence) x Prior prob of outcome

P(Evidence)
'''
def get_cp(self, attr, attr_type, class_value):
data_attr = list(self.data[attr])
class_data = list(self.data[self.class_attr])
total =1
for i in range(0, len(data_attr)):
if class_data[i] == class_value and data_attr[i] == attr_type:
total+=1
return total/float(class_data.count(class_value))

'''
Here we calculate Likelihood of Evidence and multiple all individual probabilities with priori
(Outcome|Multiple Evidence) = P(Evidence1|Outcome) x P(Evidence2|outcome) x ... x
P(EvidenceN|outcome) x P(Outcome)
scaled by P(Multiple Evidence)
'''
def calculate_conditional_probabilities(self, hypothesis):
for i in self.priori:
self.cp[i] = {}
for j in hypothesis:
self.cp[i].update({ hypothesis[j]: self.get_cp(j, hypothesis[j], i)})
print ("\nCalculated Conditional Probabilities: \n")
pprint.pprint(self.cp)

def classify(self):
print ("Result: ")
for i in self.cp:
print (i, " ==> ", reduce(lambda x, y: x*y, self.cp[i].values())*self.priori[i])

if name == " main ":


c = Classifier(filename="F:\AI LAB EXPTS\weather_data.csv", class_attr="Play" )
c.calculate_priori()
c.hypothesis = {"Outlook":'Rainy', "Temp":"Mild", "Humidity":'Normal' , "Windy":'t'}

c.calculate_conditional_probabilities(c.hypothesis)
c.classify()

33
Output:

Priori Values: {'no': 0.35714285714285715, 'yes': 0.6428571428571429}

Calculated Conditional Probabilities:

{'no': {'Mild': 0.6, 'Normal': 0.4, 'Rainy': 0.8, 't': 0.8},


'yes': {'Mild': 0.5555555555555556,
'Normal': 0.7777777777777778,
'Rainy': 0.3333333333333333,
't': 0.4444444444444444}}
Result:
no ==> 0.05485714285714286
yes ==> 0.04115226337448559

Result:
Thus the Naïve Bayes model was implemented successfully.

Ex: No: 8 BAYESIAN NETWORK MODEL WITH INFERENCE


34
Aim:
To implement a Bayesian Network with inference for a heart disease data set using
Python.
Algorithm:
Step 1: Import necessary packages.
Step 2: Import a Heart disease dataset
Step 3: Invoke MaximumLikelihoodEstimator and inference the Bayesian network using
VariableElimination()
Step 4: Calculate the Probability of Heart disease with given evidence.
Step 5: Stop the Program
Program:
import numpy as np
import pandas as pd
import csv
from pgmpy.estimators import MaximumLikelihoodEstimator
from pgmpy.models import BayesianModel
from pgmpy.inference import VariableElimination

heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)

print('Sample instances from the dataset are given below')


print(heartDisease.head())

print('\n Attributes and datatypes')


print(heartDisease.dtypes)

model= BayesianModel([('age','heartdisease'),('sex','heartdisease'),
('exang','heartdisease'),('cp','heartdisease'),('heartdisease','restecg'),
('heartdisease','chol')])
print('\nLearning CPD using Maximum likelihood estimators')
model.fit(heartDisease,estimator=MaximumLikelihoodEstimator)

print('\n Inferencing with Bayesian Network:')


HeartDiseasetest_infer = VariableElimination(model)

35
print('\n 1. Probability of HeartDisease given evidence= restecg')
q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'restecg':1})
print(q1)

print('\n 2. Probability of HeartDisease given evidence= cp ')


q2=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'cp':2})
print(q2)

Output:

Result:
Thus a Bayesian Network with an inference was built and implemented successfully.
Ex: No: 9 MINI PROJECT - AI CHATBOT

36
Aim:
To implement an AI based Chatbot.
Algorithm:
Step 1: Import the necessary libraries.
Step 2: Create chatbot.txt and open the file in read mode.
Step 3: Apply tokenization to convert a list of sentences and to list of words.
Step 4: Perform Preprocessing and Keyword Matching
Step 5: Define the functions for greetings and response
Step 6: Get the input from the user.
Step 7: If the response is “bye”, Robo Quit the Chat with the user
Step 8: Else Robo response to the user accordingly by invoking the function response()
Step 9 : Stop the program.
Program:
#Meet Robo: your friend
#import necessary libraries
import io
import random
import string # to process standard python strings
import warnings
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
import warnings
warnings.filterwarnings('ignore')
import nltk
from nltk.stem import WordNetLemmatizer
nltk.download('popular', quiet=True) # for downloading packages

# uncomment the following only the first time


#nltk.download('punkt') # first-time use only
#nltk.download('wordnet') # first-time use only
#Reading in the corpus
with open('chatbot.txt','r', encoding='utf8', errors ='ignore') as fin:
raw = fin.read().lower()
#Tokenisation
sent_tokens = nltk.sent_tokenize(raw)# converts to list of sentences
word_tokens = nltk.word_tokenize(raw)# converts to list of words
# Preprocessing
lemmer = WordNetLemmatizer()
def LemTokens(tokens):
return [lemmer.lemmatize(token) for token in tokens]
remove_punct_dict = dict((ord(punct), None) for punct in string.punctuation)

37
def LemNormalize(text):
return LemTokens(nltk.word_tokenize(text.lower().translate(remove_punct_dict)))
# Keyword Matching
GREETING_INPUTS = ("hello", "hi", "greetings", "sup", "what's up","hey",)
GREETING_RESPONSES = ["hi", "hey", "*nods*", "hi there", "hello", "I am glad! You are
talking to me"]
def greeting(sentence):
"""If user's input is a greeting, return a greeting response"""
for word in sentence.split():
if word.lower() in GREETING_INPUTS:
return random.choice(GREETING_RESPONSES)

# Generating response
def response(user_response):
robo_response=''
sent_tokens.append(user_response)
TfidfVec = TfidfVectorizer(tokenizer=LemNormalize, stop_words='english')
tfidf = TfidfVec.fit_transform(sent_tokens)
vals = cosine_similarity(tfidf[-1], tfidf)
idx=vals.argsort()[0][-2]
flat = vals.flatten()
flat.sort()
req_tfidf = flat[-2]
if(req_tfidf==0):
robo_response=robo_response+"I am sorry! I don't understand you"
return robo_response
else:
robo_response = robo_response+sent_tokens[idx]
return robo_response
flag=True
print("ROBO: My name is Robo. I will answer your queries about Chatbots. If you want
to exit, type Bye!")
while(flag==True):
user_response = input()
user_response=user_response.lower()
if(user_response!='bye'):
if(user_response=='thanks' or user_response=='thank you' ):
flag=False
print("ROBO: You are welcome..")
else:
if(greeting(user_response)!=None):
print("ROBO: "+greeting(user_response))
else:
print("ROBO: ",end="")
print(response(user_response))

38
sent_tokens.remove(user_response)
else:
flag=False
print("ROBO: Bye! take care..")
Output:

ROBO: My name is Robo. I will answer your queries about Chatbots. If you want to exit,
type Bye!
hello
ROBO: hey
hai
ROBO: I am sorry! I don't understand you
hi
ROBO: hello
sup
ROBO: hi
bye
ROBO: Bye! take care..

Result:
Thus an AI chatbot has been successfully implemented.

39
CONTENT BEYOND THE SYLLABUS
Ex: No: 10 PATH PLANNING PROBLEM USING BREADTH FIRST SEARCH

Aim:
To solve the path planning problem using Breadth First Search

Algorithm:

Step 1: Import the necessary modules

Step 2: Define the function addEdge to add the edges to the graph.

Step 3: Define the function bfs to perform Breadth First Search

Step 4: Invoke the function bfs() and print the result

Step 5: Stop the program.

Program:
from collections import defaultdict

graph=defaultdict(list)

def addEdge(u,v):

graph[u].append(v)

addEdge('T','H')
addEdge('T','I')

addEdge('H','V')

addEdge('H','Y')

addEdge('H','T')

addEdge('I','A')

addEdge('I','T')

addEdge('V','H')

addEdge('Y','H')

addEdge('A','I')

def bfs(initial_node):

q=list()

visited=list()

visited.append(initial_node)

q.append(initial_node)

40
while q:

temp=q.pop(0)

print(temp, end=" ")

for i in graph[temp]:

if i not in visited:

q.append(i)

visited.append(i)

bfs('T')

Output:

THIVYA

Result:
Thus the path planning problemusing Breadth First Search was implemented
successfully.

41
VIVA- VOCE
1. What do you understand by Artificial Intelligence?
Artificial intelligence is computer science technology that emphasizes creating intelligent
machine that can mimic human behaviour. Here intelligent machines can be defined as the
machine that can behave like a human, think like a human, and also capable of decision
making. It is made up of two words, "Artificial" and "Intelligence," which means the "man-
made thinking ability."
With artificial intelligence, we do not need to pre-program the machine to perform a task;
instead, we can create a machine with the programmed algorithms, and it can work on its
own.
2. Why do we need Artificial Intelligence?
The goal of Artificial intelligence is to create intelligent machines that can mimic human
behavior. We need AI for today's world to solve complex problems, make our lives more
smoothly by automating the routine work, saving the manpower, and to perform many more
other tasks.
3. What are the various areas where AI (Artificial Intelligence) can be used?
Artificial Intelligence can be used in many areas like Computing, Speech recognition, Bio-
informatics, Humanoid robot, Computer software, Space and Aeronautics’s etc.
4. What does a production rule consist of?
The production rule comprises of a set of rule and a sequence of steps.
5. Which search method takes less memory?
The “depth first search” method takes less memory.
6. Which is the best way to go for Game playing problem?
Heuristic approach is the best way to go for game playing problem, as it will use the
technique based on intelligent guesswork. For example, Chess between humans and
computers as it will use brute force computation, looking at hundreds of thousands of
positions.
7. A* algorithm is based on which search method?
A* algorithm is based on best first search method, as it gives an idea of optimization and
quick choose of path, and all characteristics lie in A* algorithm.
8. What does a hybrid Bayesian network contain?
A hybrid Bayesian network contains both a discrete and continuous variables.

42
9. What is agent in artificial intelligence?
Anything perceives its environment by sensors and acts upon an environment by effectors
are known as Agent. Agent includes Robots, Programs, and Humans etc.
10. What does Partial order or planning involve?
In partial order planning, rather than searching over possible situation it involves searching
over the space of possible plans. The idea is to construct a plan piece by piece.
11. What are the two different kinds of steps that we can take in constructing a plan?
a. Add an operator (action)
b. Add an ordering constraint between operators
12. Which property is considered as not a desirable property of a logical rule-based system?
“Attachment” is considered as not a desirable property of a logical rule based system.
13. What is Neural Network in Artificial Intelligence?
In artificial intelligence, neural network is an emulation of a biological neural system, which
receives the data, processes the data and gives the output based on the algorithm and
empirical data.
14. What is a heuristic function?
A heuristic function ranks alternatives, in search algorithms, at each branching step based on
the available information to decide which branch to follow.
15. What is the function of the third component of the planning system?
In a planning system, the function of the third component is to detect when a solution to
problem has been found.
16. Mention the difference between breadth first search and best first search in artificial
intelligence?
These are the two strategies which are quite similar. In best first search, we expand the
nodes in accordance with the evaluation function. While, in breadth first search a node is
expanded in accordance to the cost function of the parent node.
17. To answer any query how the Bayesian network can be used?
If a Bayesian Network is a representative of the joint distribution, then by summing all the
relevant joint entries, it can solve any query.
18. How logical inference can be solved in Propositional Logic?
In Propositional Logic, Logical Inference algorithm can be solved by using
a. Logical Equivalence
b. Validity
c. Satisfying ability

43
19. What are the different components of the Expert System?
An expert system mainly contains three components:
a) User Interface: It enables a user to interact or communicate with the expert system to
find the solution for a problem.
b) Inference Engine: It is called the main processing unit or brain of the expert system. It
applies different inference rules to the knowledge base to draw a conclusion from it.
The system extracts the information from the KB with the help of an inference engine.
c) Knowledge Base: The knowledge base is a type of storage area that stores the
domain-specific and high-quality knowledge.
20. What is knowledge representation in AI?
Knowledge representation is the part of AI, which is concerned with the thinking of AI
agents. It is used to represent the knowledge about the real world to the AI agents so that
they can understand and utilize this information for solving the complex problems in AI.
Following elements of Knowledge that are represented to the agent in the AI system:
Objects
Events
Performance
Meta-Knowledge
Facts
Knowledge-base
21. What is the inference engine, and why it is used in AI?
In artificial intelligence, the inference engine is the part of an intelligent system that derives
new information from the knowledge base by applying some logical rules.
It mainly works in two modes:
Backward Chaining: It begins with the goal and proceeds backward to deduce the facts that
support the goal.
Forward Chaining: It starts with known facts, and asserts new facts.
22. What is a Bayesian network, and why is it important in AI?
Bayesian networks are the graphical models that are used to show the probabilistic
relationship between a set of variables. It is a directed cycle graph that contains multiple
edges, and each edge represents a conditional dependency.
Bayesian networks are probabilistic, because these networks are built from a probability
distribution, and also use probability theory for prediction and anomaly detection. It is
important in AI as it is based on Bayes theorem and can be used to answer the probabilistic
questions

44
23. List the various search strategies.
a. BFS
b. Uniform cost search
c. DFS
d. Depth limited search
e. Iterative deepening search
f. Bidirectional search
24. List the various informed search strategy.
Best first search –greedy search, A* search Memory bounded search-Iterative deepening
A*search -simplified memory bounded A*search Iterative improvement search –hill climbing
-simulated annealing.
25. Differentiate BFS S DFS.
BFS means breath wise search. Space complexity is more. Do not give optimal solution
Queuing fn is same as that of queue operator DFS means depth wise search. Space
complexity is less Gives optimal solution Queuing functionn is somewhat different from
queue operator.
26. Define CSP.
A constraint satisfaction problem is a special kind of problem satisfies some additional
structural properties beyond the basic requirements for problem in general. In a CSP; the
states are defined by the values of a set of variables and the goal test specifies a set of
constraint that the value must obey.
27. Give the drawback of DFS.
The drawback of DFS is that it can get stuck going down the wrong path. Many problems
have very deep or even infinite search tree. So DFS will never be able to recover from an
unlucky choice at one of the nodes near the top of the tree. So DFS should be avoided for
search trees with large or infinite maximum depths.
28. Define Prior Probability?
P(a) for the Unconditional or Prior Probability Is That the Proposition A is True. It is
important to remember that P(a) can only be used when there is no other information.
29. Define conditional probability?
Once the agents has obtained some evidence concerning the previously unknown
propositions making up the domain conditional or posterior probabilities with the notation
p(A/B) is used. This is important that p(A/B) can only be used when all be is known.

45

You might also like