0% found this document useful (0 votes)
50 views54 pages

AI BCAI 551 Lab Manual

Uploaded by

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

AI BCAI 551 Lab Manual

Uploaded by

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

Sl Contents Page Nos

no
1 Write a python program to implement Breadth First Search Traversal 14

2 Write a python program to implement Water Jug Problem 18

3 20
(a) Write a python program to remove punctuations from the given string
(b)Write a python program to sort the sentence in alphabetical order

4 27
Write a program to implement Hangman game using python.

5 Write a program to implement Tic-Tac-Toe game using python 28


6 Write a python program to remove stop words for a given passage from a text file using 44
NLTK
7 Write a python program to implement stemming for a given sentence using 47
NLTK
8 Write a python program to POS (Parts of Speech) tagging for the give sentence 49
using NLTK
9 Write a python program to implement Lemmatization using NLTK 53

10 Write a python program to for Text Classification for the give sentence using NLTK 54

11 Write a python program to implement N queens Problem. 55

12 Convert Speech to text and text to Speech using python 56

13 VIVA Questions with Answers 69


14 References 70
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

1.Write a python program to implement Breadth first

search Traversal? Code:

"""

This file contains an implementation of breadth-first search (BFS) for

traversing a graph, and for getting the shortest path between 2 nodes

of a graph.

"""

# visits all the nodes of a graph (connected component) using BFS

def bfs_connected_component(graph, start):

# keep track of all visited nodes

explored = []

# keep track of nodes to be checked

queue = [start]

# keep looping until there are nodes still to be checked

while queue:

# pop shallowest node (first node) from queue

node = queue.pop(0)

if node not in explored:

# add node to list of checked nodes

explored.append(node)

neighbours = graph[node]

2
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

# add neighbours of node to queue

for neighbour in neighbours:

queue.append(neighbour)

return explored

# finds shortest path between 2 nodes of a graph using BFS

def bfs_shortest_path(graph, start, goal):

# keep track of explored nodes

explored = []

# keep track of all the paths to be checked

queue = [[start]]

# return path if start is goal

if start == goal:

return "That was easy! Start = goal"

# keeps looping until all possible paths have been checked

while queue:

# pop the first path from the queue

path = queue.pop(0)

# get the last node from the path

node = path[-1]

if node not in explored:

neighbours = graph[node]

# go through all neighbour nodes, construct a new path and

# push it into the queue

for neighbour in neighbours:

new_path = list(path)

new_path.append(neighbour)

queue.append(new_path)

3
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

# return path if neighbour is goal

if neighbour == goal:

return new_path

# mark node as explored

explored.append(node)

# in case there's no path between the 2 nodes

return "So sorry, but a connecting path doesn't exist :("

if name == ' main ':

# sample graph represented by a dictionary

graph = {'A': ['B', 'C'],

'B': ['A','D'],

'C': ['A','E','F'],

'D': ['B'],

'E': ['C',],

'F': ['C'],

# A
# /\

# / \
# B C

#/ /\
# / /\

# D E F

print("\nHere's the nodes of the graph visited by "

"breadth-first search, starting from node 'A':

",
4
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

bfs_connected_component(graph, 'A'))

print("\nHere's the shortest path between nodes 'D' and 'F':",

bfs_shortest_path(graph, 'D', 'F'))

OUTPUT: -

HERE'S THE NODES OF THE GRAPH VISITED BY BREADTH-FIRST SEARCH,


STARTING FROM NODE 'A': ['A', 'B', 'C', 'D', 'E', 'F']

HERE'S THE SHORTEST PATH BETWEEN NODES 'D' AND 'F': ['D', 'B', 'A', 'C', 'F']

5
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651
2.Write a python program to implement Water Jug Problem?
A Water Jug Problem: You are given two jugs, a 4-gallon one and a 3-gallon one, a
pump which has unlimited water which you can use to fill the jug, and the ground on
which water may be poured. Neither jug has any measuring markings on it. How can
you get exactly 2 gallons of water in the 4-gallon jug?

Let X represent the content of the water in 4-gallon jug.


Let Y represent the content of the water in 3-gallon jug.

Write a program in python to define a set of operators (Rules) that will take us from
one state to another:

Start from initial state (X=0, Y=0)


Reach any of the Goal states
(X=2, Y=0)
(X=2, Y=1)
(X=2, Y=2)
(X=2, Y=3)
Find the minimum number of steps to reach any the above mentioned goal states.

Code:

print("Water Jug Problem")


x=int(input("Enter X:"))
y=int(input("Enter Y:"))
while True:

rno=int(input("Enter the Rule No"))

if rno==1:
if x<4:x=4

if rno==2:
if y<3:y=3

6
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

if rno==5:
if x>0:x=0

if rno==6:
if y>0:y=0

if rno==7:
if x+y>= 4 and y>0:x,y=4,y-(4-x)

if rno==8:
if x+y>=3 and x>0:x,y=x-(3-y),3

if rno==9:
if x+y<=4 and y>0:x,y=x+y,0

if rno==10:
if x+y<=3 and x>0:x,y=0,x+y

print("X =" ,x)


print("Y =" ,y)
if (x==2):
print(" The result is a Goal state")
break

Output:

Water Jug Problem


Enter X:0
Enter Y:0
Enter the Rule No2
X=0
Y=3
Enter the Rule No9
X=3
Y=0
Enter the Rule No2
X=3
Y=3
Enter the Rule No7
X=4
Y=2
Enter the Rule No5
X=0
Y=2

7
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

Enter the Rule No9


X=2
Y=0
The result is a Goal state.

8
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

3. Write a python program to remove punctuations from the


given string? Code:
# define punctuation

punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

my_str = "Hello!!!, he said ---and went."

# To take input from the user

# my_str = input("Enter a string: ")

# remove punctuation from the string

no_punct = ""

for char in my_str:

if char not in punctuations:

no_punct = no_punct + char

# display the unpunctuated string

print(no_punct)

Output:
Enter a string:

Hello he said and went

9
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

4. Write a python program to sort the sentence in


alphabetical order? Code:
# Program to sort alphabetically the words form a string provided by the user

# change this value for a different result

my_str = "Hello this Is an Example With cased letters"

# uncomment to take input from the user

#my_str = input("Enter a string: ")

# breakdown the string into a list of words

10
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

words = my_str.split()

#print(words)

# sort the list

words.sort()

# display the sorted words

print("The sorted words are:")

for word in words:

print(word)

Output:

The sorted words are:

Example

Hello

Is

With

an

cased

letters

this

11
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

5. Write a program to implement Hangman game


using python. Description:
Hangman is a classic word-guessing game. The user should guess the word correctly by
entering alphabets of the user choice. The Program will get input as single alphabet from the
user and it will matchmaking with the alphabets in the original word. If the user given
alphabet matches with the alphabet from the original word then user must guess the
remaining alphabets. Once the user successfully found the word he will be declared as winner
otherwise user lose the game.

Python Code:

def getAvailableLetters(lettersGuessed):

'''

lettersGuessed: list, what letters have been guessed so far

returns: string, comprised of letters that represents what letters have not

yet been guessed.

'''

import string

fullstring = string.ascii_lowercase

lettersLeft = ''

for letter in fullstring:

if letter not in lettersGuessed:

lettersLeft = lettersLeft + letter

return lettersLeft

def getGuessedWord(secretWord, lettersGuessed):

'''

secretWord: string, the word the user is guessing

lettersGuessed: list, what letters have been guessed so far

returns: string, comprised of letters and underscores that represents

what letters in secretWord have been guessed so far.

12
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

'''

wordGuessed = ''

for letter in secretWord:

if letter in lettersGuessed:

wordGuessed = wordGuessed + letter

else:

wordGuessed = wordGuessed + '_ '

return wordGuessed

def isWordGuessed(secretWord, lettersGuessed):

'''

secretWord: string, the word the user is guessing

lettersGuessed: list, what letters have been guessed so far

returns: boolean, True if all the letters of secretWord are in lettersGuessed;

False otherwise

'''

numCorrect = 0

for letter in secretWord:

if letter in lettersGuessed:

numCorrect += 1

else:

return False

return True

def hangman(secretWord):

guessesLeft = 8

lettersGuessed =[]

print('Welcome to the game Hangman!')

13
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

print('I am thinking of a word that is ' + str(len(secretWord)) + ' letters

long.' ) print(' ')

while guessesLeft > 0:

if isWordGuessed(secretWord, lettersGuessed):

return print('Congratulations, you won!')

print('You have ' + str(guessesLeft) + ' guesses left.')

print('Available Letters: ' + getAvailableLetters(lettersGuessed))

user_input = input('Please guess a letter: ')

user_input = str(user_input)

user_input = user_input.lower()

if user_input not in lettersGuessed:

lettersGuessed.append(user_input)

if user_input in secretWord:

print("Good guess: " + getGuessedWord(secretWord,

lettersGuessed)) print(' ')

else:

print("Oops! That letter is not in my word: " + getGuessedWord(secretWord,


lettersGuessed))

print(' ')

guessesLeft -= 1

else:

print("Oops! You've already guessed that letter: " + getGuessedWord(secretWord,


lettersGuessed))

print(' ')

return print("Sorry, you ran out of guesses. The word was " + str(secretWord))

hangman('apple')

14
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

Output:

Welcome to the game Hangman!

I am thinking of a word that is 5 letters long.

You have 8 guesses left.

Available Letters: abcdefghijklmnopqrstuvwxyz

Please guess a letter: a

Good guess: a_ _ _ _

You have 8 guesses left.

Available Letters: bcdefghijklmnopqrstuvwxyz

Please guess a letter: p

Good guess: app_ _

You have 8 guesses left.

Available Letters: bcdefghijklmnoqrstuvwxyz

Please guess a letter: p

Oops! You've already guessed that letter: app_ _

You have 8 guesses left.

Available Letters: bcdefghijklmnoqrstuvwxyz

Please guess a letter: l

Good guess: appl_

You have 8 guesses left.

Available Letters: bcdefghijkmnoqrstuvwxyz

Please guess a letter: e

15
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

Good guess: apple

Congratulations, you won!

16
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

6. Write a program to implement Tic-Tac-Toe game


using python. Description:

In the Tic Tac Toe computer program the player chooses if they want to be X or O. Who
takes the first turn is randomly chosen. Then the player and computer take turns making
moves. The boxes on the left side of the flow chart are what happens during the player’s turn.
The right side shows what happens on the computer's turn. After the player or computer
makes a move, the program checks if they won or caused a tie, and then the game switches
turns. After the game is over, the program asks the player if they want to play again.

Python Code:

# Tic Tac Toe

import random

def drawBoard(board):

# This function prints out the board that it was passed.

# "board" is a list of 10 strings representing the board (ignore index 0)

print(' | |')

print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])

print(' | |')

print(' ')

print(' | |')

print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])

print(' | |')

print(' ')

print(' | |')

print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])

print(' | |')

17
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

def inputPlayerLetter():

# Lets the player type which letter they want to be.

# Returns a list with the player's letter as the first item, and the computer's letter as the
second.

letter = ''

while not (letter == 'X' or letter == 'O'):

print('Do you want to be X or O?')

letter = input().upper()

# the first element in the tuple is the player's letter, the second is the computer's letter.

if letter == 'X':

return ['X', 'O']

else:

return ['O', 'X']

def whoGoesFirst():

# Randomly choose the player who goes first.

if random.randint(0, 1) == 0:

return 'computer'

else:

return 'player'

def playAgain():

# This function returns True if the player wants to play again, otherwise it returns False.

print('Do you want to play again? (yes or no)')

return input().lower().startswith('y')

def makeMove(board, letter, move):

board[move] = letter

def isWinner(bo, le):

# Given a board and a player's letter, this function returns True if that player has won.

18
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

# We use bo instead of board and le instead of letter so we don't have to type as much.

return ((bo[7] == le and bo[8] == le and bo[9] == le) or # across the top

(bo[4] == le and bo[5] == le and bo[6] == le) or # across the middle

(bo[1] == le and bo[2] == le and bo[3] == le) or # across the bottom

(bo[7] == le and bo[4] == le and bo[1] == le) or # down the left side

(bo[8] == le and bo[5] == le and bo[2] == le) or # down the middle

(bo[9] == le and bo[6] == le and bo[3] == le) or # down the right side

(bo[7] == le and bo[5] == le and bo[3] == le) or # diagonal

(bo[9] == le and bo[5] == le and bo[1] == le)) # diagonal

def getBoardCopy(board):

# Make a duplicate of the board list and return it the duplicate.

dupeBoard = []

for i in board:

dupeBoard.append(i)

return dupeBoard

def isSpaceFree(board, move):

# Return true if the passed move is free on the passed board.

return board[move] == ' '

def getPlayerMove(board):

# Let the player type in his move.

move = ' '

while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):

print('What is your next move? (1-9)')

move = input()

return int(move)

19
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

def chooseRandomMoveFromList(board, movesList):

# Returns a valid move from the passed list on the passed board.

# Returns None if there is no valid move.

possibleMoves = []

for i in movesList:

if isSpaceFree(board, i):

possibleMoves.append(i)

if len(possibleMoves) != 0:

return random.choice(possibleMoves)

else:

return None

def getComputerMove(board, computerLetter):

# Given a board and the computer's letter, determine where to move and return that move.

if computerLetter == 'X':

playerLetter = 'O'

else:

playerLetter = 'X'

# Here is our algorithm for our Tic Tac Toe AI:

# First, check if we can win in the next move

for i in range(1, 10):

copy = getBoardCopy(board)

if isSpaceFree(copy, i):

makeMove(copy, computerLetter, i)

if isWinner(copy, computerLetter):

return i

# Check if the player could win on his next move, and block them.

for i in range(1, 10):

20
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

copy = getBoardCopy(board)

if isSpaceFree(copy, i):

makeMove(copy, playerLetter, i)

if isWinner(copy, playerLetter):

return i

# Try to take one of the corners, if they are free.

move = chooseRandomMoveFromList(board, [1, 3, 7, 9])

if move != None:

return move

# Try to take the center, if it is free.

if isSpaceFree(board, 5):

return 5

# Move on one of the sides.

return chooseRandomMoveFromList(board, [2, 4, 6, 8])

def isBoardFull(board):

# Return True if every space on the board has been taken. Otherwise return

False. for i in range(1, 10):

if isSpaceFree(board, i):

return False

return True

print('Welcome to Tic Tac Toe!')

while True:

# Reset the board

theBoard = [' '] * 10

playerLetter, computerLetter = inputPlayerLetter()

turn = whoGoesFirst()

print('The ' + turn + ' will go first.')

21
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

gameIsPlaying = True

while gameIsPlaying:

if turn == 'player':

# Player's turn.

drawBoard(theBoard)

move = getPlayerMove(theBoard)

makeMove(theBoard, playerLetter, move)

if isWinner(theBoard, playerLetter):

drawBoard(theBoard)

print('Hooray! You have won the game!')

gameIsPlaying = False

else:

if isBoardFull(theBoard):

drawBoard(theBoard)

print('The game is a tie!')

break

else:

turn = 'computer'

else:

# Computer's turn.

move = getComputerMove(theBoard, computerLetter)

makeMove(theBoard, computerLetter, move)

if isWinner(theBoard, computerLetter):

drawBoard(theBoard)

print('The computer has beaten you! You lose.')

gameIsPlaying = False

22
DEPARTMENT OF CSE-AIML
ARTIFICIAL INTELLIGENCE LABORATORY
KAI651

else:

if isBoardFull(theBoard):

drawBoard(theBoard)

print('The game is a tie!')

break

else:

turn = 'player'

if not playAgain():

break

OUTPUT: -

WELCOME TO TIC TAC TOE!

DO YOU WANT TO BE X OR O?

THE PLAYER WILL GO FIRST.

| |

| |

| |

| |

| |

| |

| |

| |

| |

WHAT IS YOUR NEXT MOVE? (1-9)

23
DEPARTMENT OF CSE-AIML
lOMoARcPSD|28872081

AI Lab
Manual

| |

| |

| |

| |

|X |

| |

| |

O| |

| |

WHAT IS YOUR NEXT MOVE? (1-9)

| |

O| |

| |

| |

|X |

| |

| |

O| | X

| |

WHAT IS YOUR NEXT MOVE? (1-9)


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

| |

O| |

| |

|
|

X|X
|O

|
|

| |

O| |X

| |

WHAT IS YOUR NEXT MOVE? (1-9)

WHAT IS YOUR NEXT MOVE? (1-9)

| |

O|X|

| |

|
|

X|
X|
O

|
|

|
|
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY


O|
O|
X

|
|
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

WHAT IS YOUR NEXT MOVE? (1-9)

WHAT IS YOUR NEXT MOVE? (1-9)

WHAT IS YOUR NEXT MOVE? (1-9)

| |

O|X|X

| |

|
|

X|
X|
O

|
|

| |

O|O|X

| |

THE GAME IS A TIE!

DO YOU WANT TO PLAY AGAIN? (YES OR NO)


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

7. Write a python program to remove stop words for a given


passage from a text file using NLTK?

Code:

import nltk

from nltk.corpus import stopwords

f1 = open("file1.txt","r")

f2 = open("file2.txt","w")

stop = stopwords.words('english')

for line in f1:

w = line.split(" ")

for word in w:

if word not in stop:

f2.write(word)

f2.write(" ")

f1.close()

f2.close()

Output:
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

8.Write a python program to implement stemming for a given


sentence using NLTK?
Code:
from nltk.stem import PorterStemmer

from nltk.tokenize import word_tokenize

ps= PorterStemmer()

example_words = [" python,pythonly,phythoner,pythonly"]

for w in example_words:

print(ps.stem(w))

Output:

python,pythonly,phythoner,pythonli
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

9.Write a python program to POS (Parts of Speech) tagging for


the give sentence using NLTK?
Code:

import nltk

text = nltk.word_tokenize('ive into NLTK: Part-of-speech tagging and POS Tagger')

pos = nltk.pos_tag(text)

print(text)

print(pos)
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

Output:

['ive', 'into', 'NLTK', ':', 'Part-of-speech', 'tagging', 'and', 'POS', 'Tagger']

[('ive', 'JJ'), ('into', 'IN'), ('NLTK', 'NNP'), (':', ':'), ('Part-of-speech', 'JJ'), ('tagging',
'NN'), ('and', 'CC'), ('POS', 'NNP'), ('Tagger', 'NNP')]
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

10. Write a python program to implement Lemmatization using


NLTK?

Code:
from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print(lemmatizer.lemmatize("cats"))

print(lemmatizer.lemmatize("cacti"))

print(lemmatizer.lemmatize("geese"))

print(lemmatizer.lemmatize("rocks"))

print(lemmatizer.lemmatize("pyth"))

print(lemmatizer.lemmatize("cats"))

Output:

cat

cactus

goose

rock

pyth

cat
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

11. Write a python program to for Text Classification for the


give sentence using NLTK?
Code:

import nltk

import random
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

from nltk.corpus import movie_reviews

documents = [(list(movie_reviews.words(fileid)), category) for

category in movie_reviews.categories()

for fileid in movie_reviews.fileids(category)]

random.shuffle(documents)

print(documents[1])

all_words = []

for w in movie_reviews.words():

all_words.append(w.lower())

all_words = nltk.FreqDist(all_words)

print(all_words.most_common(15))

print(all_words["stupid"])

Output:

([u'making', u'your', u'first', u'feature', u'film', u'ain', u"'", u't', u'easy', u'.', u'assemble',
u'a', u'decent', u',', u'if', u'not', u',', u'strong', u'cast', u',', u'as', u'writer', u'/', u'director',
u'robert', u'moresco', u'has', u'done', u'with', u'one', u'eyed', u'king', u',', u'and', u'you',
u"'", u're', u'already', u'ahead', u'of', u'the', u'game', u'.', u'but', u'rehash', u'old', u'plot',
u'lines', u',', u'tired', u'dialogue', u',', u'and', u'standard', u'clich', u'?', u's', u',', u'and',
u'a', u'well', u'-', u'intentioned', u'effort', u'such', u'as', u'this', u'one', u'could',
u'jeopardize', u'your', u'chance', u'at', u'a', u'second', u'feature', u'film', u'.', u'how',
u'many', u'more', u'movies', u'do', u'we', u'need', u'about', u'a', u'rough', u'neighborhood', u'full',
u'of', u'lifelong', u'friends', u'hopelessly', u'turned', u'to', u'crime', u'or', u'worse', u'?', u'the',
u'enormous', u'catalog', u'of', u'such', u'movies',
u'might', u'dissuade', u'a', u'filmmaker', u'from', u'making', u'yet', u'another', u',', u'but', u'here',
u'we', u'have', u'it', u'.', u'again', u'.', u'five', u'irish', u'kids', u'in', u'nyc',
u"'", u's', u'hell', u"'", u's', u'kitchen', u'make', u'an', u'overemotional', u'pact', u'over',
u'some', u'stolen', u'rings', u'on', u'an', u'anonymous', , u'and', u'slow', u'motion', u'.',
u'in', u'the', u'film', u"'", u's', u'first', u'scene', u'.', , '], u'neg')

12. Write a program to implement N –Queens


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

Problem.
Python program to solve N Queen
# Problem using backtracking

global N
N =4

def printSolution(board):
for i in range(N):
for j in range(N):
print (board[i][j],end=' ')
print()

# A utility function to check if a queen can


# be placed on board[row][col]. Note that this
# function is called when "col" queens are
# already placed in columns from 0 to col -1.
# So we need to check only left side for
# attacking queens
def isSafe(board, row, col):

# Check this row on left side


for i in range(col):
if board[row][i] == 1:
return False

# Check upper diagonal on left side


for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False

# Check lower diagonal on left side


for i, j in zip(range(row, N, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False

return True

def solveNQUtil(board, col):


# base case: If all queens are placed
# then return true
if col >= N:
return True

# Consider this column and try placing


# this queen in all rows one by one
for i in range(N):

if isSafe(board, i, col):
# Place this queen in board[i][col]
board[i][col] = 1
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

# recur to place rest of the queens


if solveNQUtil(board, col + 1) == True:
return True

# If placing queen in board[i][col


# doesn't lead to a solution, then
# queen from board[i][col]
board[i][col] = 0

# if the queen can not be placed in any row in


# this column col then return false
return False

# This function solves the N Queen problem using


# Backtracking. It mainly uses solveNQUtil() to
# solve the problem. It returns false if queens
# cannot be placed, otherwise return true and
# placement of queens in the form of 1s.
# note that there may be more than one
# solutions, this function prints one of the
# feasible solutions.
def solveNQ():
board = [ [0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]
]

if solveNQUtil(board, 0) == False:
print ("Solution does not exist")
return False

printSolution(board)
return True

# driver program to test above function


solveNQ()

OUTPUT
0 0 1 0
1 0 0 0
0 0 0 1
0 1 0 0
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

13. Write a Python program to


translate speech to text and text to
speech
#Python program to translate
#speech to text and text to speech

import speech_recognition as sr
import pyttsx3

# Initialize the recognizer


r = sr.Recognizer()

# Function to convert text to


# speech
def SpeakText(command):

# Initialize the engine


engine = pyttsx3.init()
engine.say(command)
engine.runAndWait()

# Loop infinitely for user to


# speak

while(1):

# Exception handling to handle


# exceptions at the runtime
try:

# use the microphone as source for input.


with sr.Microphone() as source2:

# wait for a second to let the recognizer


# adjust the energy threshold based on
# the surrounding noise level
r.adjust_for_ambient_noise(source2, duration=0.2)

#listens for the user's input


audio2 = r.listen(source2)

# Using google to recognize audio


MyText = r.recognize_google(audio2)
MyText = MyText.lower()

print("Did you say ",MyText)


SpeakText(MyText)

except sr.RequestError as e:
print("Could not request results; {0}".format(e))

except sr.UnknownValueError:
print("unknown error occurred")
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

Input: voice speech (Hi buddy how are you)

Output: Did you say hi buddy how are you

VIVA Questions with Answers

1) What do you understand by Artificial Intelligence?

Artificial intelligence is computer science technology that emphasizes creating intelligent machine that can
mimic human behavior. 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) Give some real-world applications of AI.

There are various real-world applications of AI, and some of them are given below:

 Google Search Engine: When we start writing something on the google search engine, we immediately get the
relevant recommendations from google, and this is because of different AI technologies.
 Ridesharing Applications: Different ride-sharing applications such as Uber uses AI and machine learning to
determine the type of ride, minimize the time once the car is hailed by the user, price of the ride, etc.
 Spam Filters in Email: The AI is also used for email spam filtering so that you can get the important and relevant
emails only in your inbox. As per the studies, Gmail successfully filters 99.9% of spam mails.
 Social Networking: Different social networking sites such as Facebook, Instagram, Pinterest, etc., use the AI
technology for different purposes such as face recognition and friend suggestions, when you upload a photograph
on Facebook, understanding the contextual meaning of an emoji in Instagram, and so on.
 Product recommendations: When we search for a product on Amazon, we get the recommendation for similar
products, and this is because of different ML algorithms. Similarly, on Netflix, we get personalized
recommendations for movies and web series.

4) How Artificial intelligence, Machine Learning, and Deep Learning differ from each other?

The difference between AI, ML, and Deep Learning is given in the below table:

Artificial Intelligence Machine Learning Deep Learning


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

The term Artificial intelligence was The term ML was first coined
The term DL was first coined in the year 2000 Igor
first coined in the year 1956 by Johnin the year 1959 by Arthur
Aizenberg.
McCarthy. Samuel.
It is a technology that is used to It is a subset of AI that learns It is the subset of machine learning and AI that is
create intelligent machines that can from past data and inspired by the human brain cells, called neurons, and
mimic human behavior. experiences. imitates the working of the human brain.
AI completely deals with structured, ML deals with structured and Deep learning deals with structured and unstructured
semi-structured data. semi-structured data. data.
It can work with less amount
It requires a huge amount of data to It requires a huge amount of the data compared to the
of data compared to deep
work. ML.
learning and AI.
The goal of AI is to enable the The goal of ML is to enable The goal of deep learning is to solve the complex
machine to think without any human the machine to learn from past problems as the human brain does, using various
intervention. experiences. algorithms.

5) What are the types of AI?

Artificial intelligence can be divided into different types on the basis of capabilities and functionalities.

Based on Capabilities:

 Weak AI or Narrow AI: Weak AI is capable of performing some dedicated tasks with intelligence. Siri is an
example of Weak AI.
 General AI: The intelligent machines that can perform any intellectual task with efficiency as a human.
 Strong AI: It is the hypothetical concept that involves the machine that will be better than humans and will surpass
human intelligence.

Based on Functionalities:

 Reactive Machines: Purely reactive machines are the basic types of AI. These focus on the present actions and
cannot store the previous actions. Example: Deep Blue.
 Limited Memory: As its name suggests, it can store the past data or experience for the limited duration. The self-
driving car is an example of such AI types.
 Theory of Mind: It is the advanced AI that is capable of understanding human emotions, people, etc., in the real
world.
 Self-Awareness: Self Awareness AI is the future of Artificial Intelligence that will have their own consciousness,
emotions, similar to humans.

6) What are the different domains/Subsets of AI?

AI covers lots of domains or subsets, and some main domains are given below:

 Machine Learning
 Deep Learning
 Neural Network
 Expert System
 Fuzzy Logic
 Natural Language Processing
 Robotics
 Speech Recognition.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

7) What are the types of Machine Learning?

Machine Learning can be mainly divided into three types:

1. Supervised Learning: Supervised learning is a type of Machine learning in which the machine needs external
supervision to learn from data. The supervised learning models are trained using the labeled dataset. Regression
and Classification are the two main problems that can be solved with Supervised Machine Learning.
2. Unsupervised Learning: It is a type of machine learning in which the machine does not need any external
supervision to learn from the data, hence called unsupervised learning. The unsupervised models can be trained
using the unlabelled dataset. These are used to solve the Association and Clustering problems.
3. Reinforcement Learning: In Reinforcement learning, an agent interacts with its environment by producing
actions, and learn with the help of feedback. The feedback is given to the agent in the form of rewards, such as for
each good action, he gets a positive reward, and for each bad action, he gets a negative reward. There is no
supervision provided to the agent. Q-Learning algorithm is used in reinforcement learning.

8) Explain the term "Q-Learning."

Q-learning is a popular algorithm used in reinforcement learning. It is based on the Bellman equation. In this
algorithm, the agent tries to learn the policies that can provide the best actions to perform for maximining the
rewards under particular circumstances. The agent learns these optimal policies from past experiences.

In Q-learning, the Q is used to represent the quality of the actions at each state, and the goal of the agent is to
maximize the value of Q.

9) What is Deep Learning, and how is it used in real-world?

Deep learning is a subset of Machine learning that mimics the working of the human brain. It is inspired by the
human brain cells, called neurons, and works on the concept of neural networks to solve complex real-world
problems. It is also known as the deep neural network or deep neural learning.

Some real-world applications of deep learning are:

 Adding different colors to the black&white images


 Computer vision
 Text generation
 Deep-Learning Robots, etc.

10) Which programming language is used for AI?

Below are the top five programming languages that are widely used for the development of Artificial
Intelligence:

 Python
 Java
 Lisp
 R
 Prolog

Among the above five languages, Python is the most used language for AI development due to its simplicity and
availability of lots of libraries, such as Numpy, Pandas, etc.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

11) What is the intelligent agent in AI, and where are they used?

The intelligent agent can be any autonomous entity that perceives its environment through the sensors and act on
it using the actuators for achieving its goal.

These Intelligent agents in AI are used in the following applications:

 Information Access and Navigations such as Search Engine


 Repetitive Activities
 Domain Experts
 Chatbots, etc.

12) How is machine learning related to AI?

Machine learning is a subset or subfield of Artificial intelligence. It is a way of achieving AI. As both are the two
different concepts and the relation between both can be understood as "AI uses different Machine learning
algorithms and concepts to solve the complex problems."

13) What is Markov's Decision process?

The solution for a reinforcement learning problem can be achieved using the Markov decision process or MDP.
Hence, MDP is used to formalize the RL problem. It can be said as the mathematical approach to solve a
reinforcement learning problem. The main aim of this process is to gain maximum positive rewards by choosing
the optimum policy.

MDP has four elements, which are:


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

 A set of finite states S


 A set of finite actions A
 Rewards
 Policy Pa

In this process, the agent performs an action A to take a transition from state S1 to S2 or from the start state to the
end state, and while doing these actions, the agent gets some rewards. The series of actions taken by the agent
can be defined as the policy.

14) What do you understand by the reward maximization?

Reward maximization term is used in reinforcement learning, and which is a goal of the reinforcement learning
agent. In RL, a reward is a positive feedback by taking action for a transition from one state to another. If the
agent performs a good action by applying optimal policies, he gets a reward, and if he performs a bad action, one
reward is subtracted. The goal of the agent is to maximize these rewards by applying optimal policies, which is
termed as reward maximization.

15) What are parametric and non-parametric model?

In machine learning, there are mainly two types of models, Parametric and Non-parametric. Here parameters are
the predictor variables that are used to build the machine learning model. The explanation of these models is
given below:

Parametric Model: The parametric models use a fixed number of the parameters to create the ML model. It
considers strong assumptions about the data. The examples of the parametric models are Linear regression,
Logistic Regression, Naïve Bayes, Perceptron, etc.

Non-Parametric Model: The non-parametric model uses flexible numbers of parameters. It considers a few
assumptions about the data. These models are good for higher data and no prior knowledge. The examples of the
non-parametric models are Decision Tree, K-Nearest Neighbour, SVM with Gaussian kernels, etc.

16) What do you understand by the hyperparameter?

In machine learning, hyperparameter is the parameters that determine and control the complete training process.
The examples of these parameters are Learning rate, Hidden Layers, Hidden units, Activation functions, etc.
These parameters are external from the model. The selection of good hyperparameters makes a better algorithm.

17) Explain the Hidden Markov model.

Hidden Markov model is a statistical model used for representing the probability distributions over a chain of
observations. In the hidden markov model, hidden defines a property that it assumes that the state of a process
generated at a particular time is hidden from the observer, and Markov defines that it assumes that the process
satisfies the Markov property. The HMM models are mostly used for temporal data.

The HMM is used in various applications such as reinforcement learning, temporal pattern recognition, etc.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

18) What is Strong AI, and how is it different from the Weak AI?

Strong AI: Strong AI is about creating real intelligence artificially, which means a human-made intelligence that
has sentiments, self-awareness, and emotions similar to humans. It is still an assumption that has a concept of
building AI agents with thinking, reasoning, and decision-making capabilities similar to humans.

Weak AI: Weak AI is the current development stage of artificial intelligence that deals with the creation of
intelligent agents and machines that can help humans and solve real-world complex problems. Siri and Alexa
are examples of Weak AI programs.

19) Give a brief introduction to the Turing test in AI?

Turing test is one of the popular intelligence tests in Artificial intelligence. The Turing test was introduced by
Alan Turing in the year 1950. It is a test to determine that if a machine can think like a human or not. According
to this test, a computer can only be said to be intelligent if it can mimic human responses under some particular
conditions.

In this test, three players are involved, the first player is a computer, the second player is a human responder, and
the third player is the human interrogator, and the interrogator needs to find which response is from the machine
on the basis of questions and answers.

20) Which assessment is used to test the intelligence of the machine?

Turing Test.

21) What is overfitting? How can it be overcome in Machine Learning?

When the machine learning algorithm tries to capture all the data points, and hence, as a result, captures noise
also, then overfitting occurs in the model. Due to this overfitting issue, the algorithm shows the low bias, but the
high variance in the output. Overfitting is one of the main issues in machine learning.

Methods to avoid Overfitting in ML:

 Cross-Validation
 Training With more data
 Regularization
 Ensembling
 Removing Unnecessary Features
 Early Stopping the training.

22) Tell one technique to avoid overfitting in neural networks?

Dropout Technique: The dropout technique is one of the popular techniques to avoid overfitting in the neural
network models. It is the regularization technique, in which the randomly selected neurons are dropped during
training.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

23) What is NLP? What are the various components of NLP?

NLP stands for Natural Language Processing, which is a branch of artificial intelligence. It enables machines to
understand, interpret, and manipulate the human language.

Components of NLP:

There are mainly two components of Natural Language processing, which are given below:

1. Natural Language Understanding (NLU):


It involves the below tasks:
o To map the input to useful representations.
o To analyze the different aspects of the language.
2. Natural Language Generation (NLG)
o Text Planning
o Sentence Planning
o Text Realization

24) What are the different components of the Expert System?

An expert system mainly contains three components:

1. User Interface: It enables a user to interact or communicate with the expert system to find the solution for a
problem.
2. 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.
3. Knowledge Base: The knowledge base is a type of storage area that stores the domain-specific and high-quality
knowledge.

25) What is the use of computer vision in AI?

Computer vision is a field of Artificial Intelligence that is used to train the computers so that they can interpret
and obtain information from the visual world such as images. Hence, computer vision uses AI technology to
solve complex problems such as image processing, object detections, etc.

26) Explain the minimax algorithm along with the different terms.

Minimax algorithm is a backtracking algorithm used for decision making in game theory. This algorithm
provides the optimal moves for a player by assuming that another player is also playing optimally.

This algorithm is based on two players, one is called MAX, and the other is called the MIN.

Following terminologies that are used in the Minimax Algorithm:

 Game tree: A tree structure with all possible moves.


 Initial State: The initial state of the board.
 Terminal State: Position of the board where the game finishes.
 Utility Function: The function that assigns a numeric value for the outcome of the game.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

27) What is game theory? How is it important in AI?

Game theory is the logical and scientific study that forms a model of the possible interactions between two or
more rational players. Here rational means that each player thinks that others are just as rational and have the
same level of knowledge and understanding. In the game theory, players deal with the given set of options in a
multi-agent situation, it means the choice of one player affects the choice of the other or opponent players.

Game theory and AI are much related and useful to each other. In AI, the game theory is widely used to enable
some of the key capabilities required in the multi-agent environment, in which multiple agents try to interact with
each other to achieve a goal.

Different popular games such as Poker, Chess, etc., are the logical games with the specified rules. To play these
games online or digitally, such as on Mobile, laptop, etc., one has to create algorithms for such games. And these
algorithms are applied with the help of artificial intelligence.

28) What are some misconceptions about AI?

There are lots of misconceptions about artificial intelligence since starting its evolution. Some of these
misconceptions are given below:

 AI does not require humans: The first misconception about AI is that it does not require human. But in reality,
each AI-based system is somewhere dependent on humans and will remain. Such as it requires human gathered
data to learn about the data.
 AI is dangerous for humans: AI is not inherently dangerous for humans, and still, it has not reached the super AI
or strong AI, which is more intelligent than humans. Any powerful technology cannot be harmful if it is not
misused.
 AI has reached its peak stage: Still, we are so far away from the peak stage of the AI. It will take a very long
journey to reach its peak.
 AI will take your job: It is one of the biggest confusions that AI will take most of the jobs, but in reality, it is
giving us more opportunities for new jobs.
 AI is new technology: Although some people think that it is a new technology, this technology actually first
thought in the year 1840 through an English newspaper.

29) What are the eigenvalues and eigenvectors?

Eigenvectors and eigenvalues are the two main concepts of Linear algebra.

Eigenvectors are unit vectors that have a magnitude equal to 1.0.

Eigenvalues are the coefficients that are applied to the eigenvectors, or these are the magnitude by which the
eigenvector is scaled.

30) What is an Artificial neural network? Name some commonly used Artificial Neural networks.

Artificial neural networks are the statistical model inspired by the functioning of human brain cells called
neurons. These neural networks include various AI technologies such as deep learning and machine learning.

An Artificial neural network or ANN consists of multiple layers, including the Input layer, Output Layer, and
hidden layers.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

ANN, with the help of various deep learning techniques, is the AI tools to solve various complex problems like
pattern recognition, facial recognition, and so on.

Some commonly used Artificial neural networks:

 Feedforward Neural Network


 Convolutional Neural Network
 Recurrent Neural Network
 Autoencoders

31) Give a brief introduction of partial, alternate, artificial, and compound keys?

Partial Keys: A set of attributes that uniquely identifies weak entities, which are related to the same owner
entity.

Alternate Keys: All candidate keys except the primary key are known as alternate keys.

Compound Key: It has multiple fields that enable the user to uniquely recognize a specific record.

Artificial Key: It is the extra attribute added to the table when there are no stands alone or compounds key is
available. It is created by assigning a number to each record in the table.

32) What is a Chatbot?

A chatbot is Artificial intelligence software or agent that can simulate a conversation with humans or users using
Natural language processing. The conversation can be achieved through an application, website, or messaging
apps. These chatbots are also called as the digital assistants and can interact with humans in the form of text or
through voice.

The AI chatbots are broadly used in most businesses to provide 24*7 virtual customer support to their customers,
such as HDFC Eva chatbot, Vainubot, etc.

33) 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
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

34) What are the various techniques of knowledge representation in AI?

Knowledge representation techniques are given below:

 Logical Representation
 Semantic Network Representation
 Frame Representation
 Production Rules

35) Which programming language is not generally used in AI, and why?

Perl Programming language is not commonly used language for AI, as it is the scripting language.

36) What is reinforcement learning?

Reinforcement learning is a type of machine learning. In this, an agent interacts with its environment by
producing actions, and learn with the help of feedback. The feedback is given to the agent in the form of rewards,
such as for each good action, he gets a positive reward, and for each bad action, he gets a negative reward. There
is no any labeled data or supervision is provided to the agent. In RL, the agent continuously does three
things(performing actions, changing state, and getting the feedback) to explore the environment.

The popular reinforcement learning algorithms are:

 Q-Learning
 SARSA(State Action Reward State Action)
 Deep Q Neural Network

37) How does RL work?

The working of reinforcement learning can be understood by the below diagram:


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

The RL-based system mainly consists of the following components:

 Environment: The environment is the surrounding of the agent, where he needs to explore and act upon.
 Agent: The agent is the AI program that has sensors and actuators and the ability to perceive the environment.
 State: It is the situation that is returned by the environment to the agent.
 Reward: The feedback received to the agent after doing each action.

In RL, the agent interacts with the environment in order to explore it by doing some actions. On each action, the
state of agent gets changed or sometimes remains the same, and based on the type of action, and he gets a reward.
The reward is feedback, which may be negative or positive based on the action.

The goal of the agent is to maximize the positive reward and to achieve the goal of the problem.

38) What are the different areas where AI has a great impact?

Following are some areas where AI has a great impact:

 Autonomous Transportation
 Education-system powered by AI.
 Healthcare
 Predictive Policing
 Space Exploration
 Entertainment, etc.

39) What are the different software platforms for AI development?

1. Google Cloud AI platform


2. Microsoft Azure AI platform
3. IBM Watson
4. TensorFlow
5. Infosys Nia
6. Rainbird
7. Dialogflow

40) Kindly explain different ways to evaluate the performance of the ML model.

Some popular ways to evaluate the performance of the ML model are:

 Confusion Matrix: It is N*N table with different sets of value that is used to determine the performance of the
classification model in machine learning.
 F1 score: It is the harmonic mean of precision and recall, which is used as one of the best metrics to evaluate the
ML model.
 Gain and lift charts: Gain & Lift charts are used to determine the rank ordering of the probabilities.
 AUC-ROC curve: The AUC-ROC is another performance metric. The ROC is the plot between the sensitivity.
 Gini Coefficient: It is used in the classification problems, also known as the Gini Index. It determines the
inequality between the values of variables. The high value of the Gini represents a good model.
 Root mean squared error: It is one of the most popular metrics used for the evaluation of the regression model. It
works by assuming that errors are unbiased and have a normal distribution.
 Cross-Validation: It is another popular technique for evaluating the performance of the machine learning model.
In this, the models are trained on subsets of the input data and evaluated on the complementary subset of the data.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

41) Explain rational agents and rationality?

A rational agent is an agent that has clear preferences, model uncertainty, and that performs the right actions
always. A rational agent is able to take the best possible action in any situation.

Rationality is a status of being reasonable and sensible with a good sense of judgment.

42) What is tensor flow, and how it is used in AI?

Tensor flow is the open-source library platform developed by the Google Brain team. It is a math library used for
several machine learning applications. With the help of tensor flow, we can easily train and deploy the machine
learning models in the cloud.

43) Which algorithm is used by Facebook for face recognition? Explain its working.

Facebook uses the DeepFace tool that uses the deep learning algorithms for the face verification that allows the
photo tag suggestions to you when you upload a photo on Facebook. The deep face identifies the faces in the
digital images using neural network models. The working of DeepFace is given in below steps:

 It first scans the uploaded images. It makes the 3-D model of the image, and then rotate that image into different
angles.
 After that, it starts matching. To match that image, it uses a neural network model to determine the high-level
similarities between other photos of a person. It checks for the different features such as the distance between the
eyes, the shape of the nose, eyes color, etc.
 Then it does the recursive checking for 68 landmark testing, as each human face consists of 68 specific facial
points.
 After mapping, it encodes the image and searches for the information of that person.

44) What is a market-basket analysis?

The market-basket analysis is a popular technique to find the associations between the items. It is frequently used
by big retailers in order to get maximum profit. In this approach, we need to find combinations of items that are
frequently bought together.

For example, if a person buys bread, there are most of the chances that he will buy butter also. Hence,
understanding such correlations can help retailers to grow their business by providing relevant offers to their
customers.

45) How can AI be used in fraud detection?

The artificial intelligence can be broadly helpful in fraud detection using different machine learning algorithms,
such as supervised and unsupervised learning algorithms. The rule-based algorithms of Machine learning helps to
analyze the patterns for any transaction and block the fraudulent transactions.

Below are the steps used in fraud detection using machine learning:
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

 Data extraction: The first step is data extraction. Data is gathered through a survey or with the help of web
scraping tools. The data collection depends on the type of model, and we want to create. It generally includes the
transaction details, personal details, shopping, etc.
 Data Cleaning: The irrelevant or redundant data is removed in this step. The inconsistency present in the data may
lead to wrong predictions.
 Data exploration & analysis: This is one of the most crucial steps in which we need to find out the relation
between different predictor variables.
 Building Models: Now, the final step is to build the model using different machine learning algorithms depending
on the business requirement. Such as Regression or classification.

46) Give the steps for A* algorithm?

A* algorithm is the popular form of the Best first search. It tries to find the shortest path using the heuristic
function with the cost function to reach the end node. The steps for A* algorithms are given below:

Step 1: Put the first node in the OPEN list.

Step 2: Check if the OPEN list is empty or not; if the list is empty, then return failure and stops.

Step 3: Select the node from the OPEN list which has the smallest value of evaluation function (g+h), if node n
is goal node then return success and stop, otherwise

Step 4: Expand node n and generate all of its successors, and put n into the closed list. For each successor n',
check whether n' is already in the OPEN or CLOSED list; if not, then compute evaluation function for n' and
place into Open list.

Step 5: Else if node n' is already in OPEN and CLOSED list, then it should be attached to the back pointer,
which reflects the lowest g(n') value.

Step 6: Return to Step 2.

47) 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.

48) What do you understand by the fuzzy logic?

Fuzzy logic is a method of reasoning applied to the AI, which resembles human reasoning. Here the word
"fuzzy" defines things that are not clear, it means the situations where it is difficult to decide if the state is True
or False. It involves all the possibilities that occur between Yes and NO.

The below diagram shows the difference between fuzzy logic and Boolean logic
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

Since it resembles human reasoning, hence it can be used in neural networks.

49) 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.

50) What is a heuristic function, and where is it used?

The heuristic function is used in Informed Search, and it finds the most promising path. It takes the current state
of the agent as its input and produces the estimation of how close the agent is from the goal. The heuristic
method, however, might not always give the best solution, but it guaranteed to find a good solution in a
reasonable time. Heuristic function estimates how close a state is to the goal. It is represented by h(n), and it
calculates the cost of an optimal path between the pair of states. The value of the heuristic function is always
positive.

Admissibility of the heuristic function is given as:

h(n) <= h*(n)

Here h(n) is heuristic cost, and h*(n) is the estimated cost. Hence heuristic cost should be less than or equal to the
estimated cost.
lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY


lOMoARcPSD|28872081

ARTIFICIAL INTELLIGENCE LABORATORY

REFERENCES

List of Text Books


1.Gerhard Weiss, ―Multi Agent Systems‖, Second Edition, MIT Press, 2013.
List of Reference Books
1. S. Russell and P. Norvig, “Artificial Intelligence: A Modern Approach‖, Prentice
Hall, Third Edition, 2009

List of URLs, Text Books, Notes, Multimedia Content, etc


1. https://www.tutorialspoint.com/artificial_intelligence/index.html
2. https://intellipaat.com/blog/tutorial/artificial-intelligence-tutorial/

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy