AD8413 Artificial Intelligence-1
AD8413 Artificial Intelligence-1
1
TABLE OF CONTENTS
1 Institute V/M 3
S.No. Page
Lab Experiments Details CO PO
No.
CO1-
9 Mini-Project
CO4
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.
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.
5
AD3311 ARTIFICIALINTELLIGENCELABORATORY L T P C
0 0 3 1.5
OBJECTIVES:
LISTOF EXPERIMENTS:
COURSE OUTCOMES:
6
CO – PO/PSO Mapping based on Weightage:
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
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
# This will store the parent node to the current node And helps in tracing the
# path when the solution is visible
self.parent = parent
9
# Store no. of moves so far
self.levels = levels
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
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):
# 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):
# 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()
11
minimum.empty_tile_posi[1] + cols[i], ]
if isSafe(new_tile_posi[0], new_tile_posi[1]):
# Main Code
# Initial configuration
# Value 0 is taken here as an empty space
initial = [ [ 1, 2, 3 ],
[ 5, 6, 0 ],
[ 7, 8, 4 ] ]
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())
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.
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:
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]]]
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
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)
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):
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
return False
return True
open = []
closed = []
open.append(start_node)
current_node = open.pop(0)
closed.append(current_node)
if current_node == goal_node:
path = []
24
path.append(current_node.name + ': ' + str(current_node.g))
current_node = current_node.parent
return path[::-1]
neighbors = graph.get(current_node.name)
if(neighbor in closed):
continue
neighbor.h = heuristics.get(neighbor.name)
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}
print(path)
Output:
['a: 0', 'c: 3', 'd: 10', 'e: 12', 'z: 17']
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 init_assignment(csp):
assignment = {}
for var in csp[VARIABLES]:
assignment[var] = None
26
return assignment
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"])
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
# 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)
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:
Algorithm:
Step 2: Define the class Classifier and define the following functions:
Program:
'''
probability(class) = How many times it appears in column
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])
c.calculate_conditional_probabilities(c.hypothesis)
c.classify()
33
Output:
Result:
Thus the Naïve Bayes model was implemented successfully.
heartDisease = pd.read_csv('heart.csv')
heartDisease = heartDisease.replace('?',np.nan)
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)
35
print('\n 1. Probability of HeartDisease given evidence= restecg')
q1=HeartDiseasetest_infer.query(variables=['heartdisease'],evidence={'restecg':1})
print(q1)
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
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 2: Define the function addEdge to add the edges to the graph.
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)
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