0% found this document useful (0 votes)
21 views63 pages

Ai Record Final

Uploaded by

sydhasan003
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)
21 views63 pages

Ai Record Final

Uploaded by

sydhasan003
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/ 63

18CSC305JARTIFICIAL INTELLIGENCE

DATE: IMPLEMENTATION OF TOY PROBLEMS


EX.NO: 1

AIM:

To Write a Program to Play Tic TAC Toe with the player

ALGORITHIM:

1. We will make the board using dictionary in which keys will be the location (i.e: top-left, mid-
right, etc.) and initially it's values will be empty space and then after every move we will change
the value according to player's choice of move.

2. We will have to print the updated board after every move in the game and thus we will make a
function in which we'll define the print Board function so that we can easily print the board every
time by calling this function.

3. Now we'll write the main function which has all the gameplay functionality.

4. Now we will check if player X or O has won, for every move after 5 moves.

5. If neither X nor O wins and the board is full, we'll declare the result as 'tie'.

6. Now we have to change the player after every move.

7. Now we will ask if player wants to restart the game or not.

Code:

#Implementation of Two Player Tic-Tac-Toe game in Python.

''' We will make the board using dictionary


in which keys will be the location(i.e : top-left,mid-right,etc.)
and initialliy it's values will be empty space and then after every move
we will change the value according to player's choice of move. '''

theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }

board_keys = []

for key in theBoard:


board_keys.append(key)

''' We will have to print the updated board after every move in the game and
thus we will make a function in which we'll define the printBoard function

1
18CSC305JARTIFICIAL INTELLIGENCE

so that we can easily print the board everytime by calling this function. '''

def printBoard(board):
print(board['7'] + '|' + board['8'] + '|' + board['9'])
print('-+-+-')
print(board['4'] + '|' + board['5'] + '|' + board['6'])
print('-+-+-')
print(board['1'] + '|' + board['2'] + '|' + board['3'])

# Now we'll write the main function which has all the gameplay functionality.
def game():

turn = 'X'
count = 0

for i in range(10):
printBoard(theBoard)
print("It's your turn," + turn + ".Move to which place?")

move = input()

if theBoard[move] == ' ':


theBoard[move] = turn
count += 1
else:
print("That place is already filled.\nMove to which place?")
continue

# Now we will check if player X or O has won,for every move after 5 moves.
if count >= 5:
if theBoard['7'] == theBoard['8'] == theBoard['9'] != ' ': # across the top
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['4'] == theBoard['5'] == theBoard['6'] != ' ': # across the middle
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['2'] == theBoard['3'] != ' ': # across the bottom
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['4'] == theBoard['7'] != ' ': # down the left side
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break

2
18CSC305JARTIFICIAL INTELLIGENCE

elif theBoard['2'] == theBoard['5'] == theBoard['8'] != ' ': # down the middle


printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['3'] == theBoard['6'] == theBoard['9'] != ' ': # down the right side
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['7'] == theBoard['5'] == theBoard['3'] != ' ': # diagonal
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break
elif theBoard['1'] == theBoard['5'] == theBoard['9'] != ' ': # diagonal
printBoard(theBoard)
print("\nGame Over.\n")
print(" **** " +turn + " won. ****")
break

# If neither X nor O wins and the board is full, we'll declare the result as 'tie'.
if count == 9:
print("\nGame Over.\n")
print("It's a Tie!!")

# Now we have to change the player after every move.


if turn =='X':
turn = 'O'
else:
turn = 'X'

# Now we will ask if player wants to restart the game or not.


restart = input("Do want to play Again?(y/n)")
if restart == "y" or restart == "Y":
for key in board_keys:
theBoard[key] = " "

game()

if __name__ == "__main__":
game()

3
18CSC305JARTIFICIAL INTELLIGENCE

OUTPUT:

RESULT: Thus, the Program to Play Tic TAC Toe with the player has been implemented
successfully.

DATE: DEVELOPING AGENT PROGRAMS FOR REAL-WORLD

4
18CSC305JARTIFICIAL INTELLIGENCE

EX.NO: 2 PROBLEMS

AIM:

To Write a Program to color code all territories in Australia

ALGORITHIM:

1. Helper function that returns -1 for non-found index value of a seq

2. Returns list of tuples with which the free space may be swapped.

3. Get row and column of the empty piece and find which pieces can move there.

4. Performs A* search for goal state.

5. If finished state not found, return failure.

6. Heuristic template that provides the current and target position for each number and the total
function.

7. Some heuristic functions, the best being the standard manhattan distance in this case, as it
comes closest to maximizing the estimated distance while still being admissible.

Code:

CSP.py:

from typing import Generic, TypeVar, Dict, List, Optional

from abc import ABC, abstractmethod

V = TypeVar('V') # variable type

D = TypeVar('D') # domain type

# Base class for all constraints

class Constraint(Generic[V, D], ABC):

# The variables that the constraint is between

def __init__(self, variables: List[V]) -> None:

self.variables = variables

# Must be overridden by subclasses

@abstractmethod

5
18CSC305JARTIFICIAL INTELLIGENCE

def satisfied(self, assignment: Dict[V, D]) -> bool:

...

# A constraint satisfaction problem consists of variables of type V

# that have ranges of values known as domains of type D and constraints

# that determine whether a particular variable's domain selection is valid

class CSP(Generic[V, D]):

def __init__(self, variables: List[V], domains: Dict[V, List[D]]) -> None:

self.variables: List [V] = variables # variables to be constrained

Self. Domains: Duct [V, List [D]] = domains # domain of each variable

Self. Constraints: Duct [V, List [Constraint [V, D]]] = {}

For variable in self. Variables:

Self. Constraints [variable] = []

If variable not in self.domains:

Raise LookupError("Every variable should have a domain assigned to it.")

def add_constraint(self, constraint: Constraint[V, D]) -> None:

for variable in constraint.variables:

if variable not in self.variables:

raise LookupError("Variable in constraint not in CSP")

else:

self.constraints[variable].append(constraint)

# Check if the value assignment is consistent by checking all constraints

# for the given variable against it

def consistent(self, variable: V, assignment: Dict[V, D]) -> bool:

for constraint in self.constraints[variable]:

if not constraint.satisfied(assignment):

return False

return True
6
18CSC305JARTIFICIAL INTELLIGENCE

def backtracking_search(self, assignment: Dict[V, D] = {}) -> Optional[Dict[V, D]]:

# assignment is complete if every variable is assigned (our base case)

if len(assignment) == len(self.variables):

return assignment

# get all variables in the CSP but not in the assignment

unassigned: List[V] = [v for v in self.variables if v not in assignment]

# get the every possible domain value of the first unassigned variable

first: V = unassigned[0]

for value in self.domains[first]:

local_assignment = assignment.copy()

local_assignment[first] = value

# if we're still consistent, we recurse (continue)

if self.consistent(first, local_assignment):

result: Optional[Dict[V, D]] = self.backtracking_search(local_assignment)

# if we didn't find the result, we will end up backtracking

if result is not None:

return result

COLOR_MAPPING.py:

class MapColoringConstraint(Constraint[str, str]):

def __init__(self, place1: str, place2: str) -> None:

super().__init__([place1, place2])

self.place1: str = place1

self.place2: str = place2


7
18CSC305JARTIFICIAL INTELLIGENCE

def satisfied(self, assignment: Dict[str, str]) -> bool:

# If either place is not in the assignment then it is not

# yet possible for their colors to be conflicting

if self.place1 not in assignment or self.place2 not in assignment:

return True

# check the color assigned to place1 is not the same as the

# color assigned to place2

return assignment[self.place1] != assignment[self.place2]

if __name__ == "__main__":

variables: List[str] = ["Western Australia", "Northern Territory", "South Australia",

"Queensland", "New South Wales", "Victoria", "Tasmania"]

domains: Dict[str, List[str]] = {}

for variable in variables:

domains[variable] = ["red", "green", "blue"]

csp: CSP[str, str] = CSP(variables, domains)

csp.add_constraint(MapColoringConstraint("Western Australia", "Northern Territory"))

csp.add_constraint(MapColoringConstraint("Western Australia", "South Australia"))

csp.add_constraint(MapColoringConstraint("South Australia", "Northern Territory"))

csp.add_constraint(MapColoringConstraint("Queensland", "Northern Territory"))

csp.add_constraint(MapColoringConstraint("Queensland", "South Australia"))

csp.add_constraint(MapColoringConstraint("Queensland", "New South Wales"))

csp.add_constraint(MapColoringConstraint("New South Wales", "South Australia"))

csp.add_constraint(MapColoringConstraint("Victoria", "South Australia"))

csp.add_constraint(MapColoringConstraint("Victoria", "New South Wales"))

csp.add_constraint(MapColoringConstraint("Victoria", "Tasmania"))
8
18CSC305JARTIFICIAL INTELLIGENCE

solution: Optional[Dict[str, str]] = csp.backtracking_search()

if solution is None:

print("No solution found!")

else:

print(solution)

OUTPUT:

RESULT: Thus, the Program to colour code all territories in Australia has been implemented
successfully.

DATE: IMPLEMENTATION OF CONSTRAINT


EX.NO: 3 SATISFACTION PROBLEMS
9
18CSC305JARTIFICIAL INTELLIGENCE

AIM:

To write a Program to identify territories in Australia

ALGORITHIM:

1. Vector stores 1 corresponding to index number which is already assigned to any char, otherwise
stores 0.

2. Structure to store char and its corresponding integer.

3. Function check for correct solution

4. Recursive function to check solution for all permutations.

5. Call recursive function.

6. Backtrack for all other possible solutions.

Code:

"cells": [
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"\n",
"from typing import Generic, TypeVar, Dict, List, Optional\n",
"from abc import ABC, abstractmethod\n",
"\n",
"V = TypeVar('V') # variable type\n",
"D = TypeVar('D') # domain type\n",
"\n",
"\n",
"# Base class for all constraints\n",
"class Constraint(Generic[V, D], ABC):\n",
" # The variables that the constraint is between\n",
" def __init__(self, variables: List[V]) -> None:\n",
" self.variables = variables\n",
"\n",
" # Must be overridden by subclasses\n",
" @abstractmethod\n",
" def satisfied(self, assignment: Dict[V, D]) -> bool:\n",
" ...\n",
"\n",
"\n",
"\n",
"class CSP(Generic[V, D]):\n",
" def __init__(self, variables: List[V], domains: Dict[V, List[D]]) -> None:\n",
10
18CSC305JARTIFICIAL INTELLIGENCE

" self.variables: List[V] = variables # variables to be constrained\n",


" self.domains: Dict[V, List[D]] = domains # domain of each variable\n",
" self.constraints: Dict[V, List[Constraint[V, D]]] = {}\n",
" for variable in self.variables:\n",
" self.constraints[variable] = []\n",
" if variable not in self.domains:\n",
" raise LookupError(\"Every variable should have a domain assigned to it.\")\n",
"\n",
" def add_constraint(self, constraint: Constraint[V, D]) -> None:\n",
" for variable in constraint.variables:\n",
" if variable not in self.variables:\n",
" raise LookupError(\"Variable in constraint not in CSP\")\n",
" else:\n",
" self.constraints[variable].append(constraint)\n",
"\n",
" # Check if the value assignment is consistent by checking all constraints\n",
" # for the given variable against it\n",
" def consistent(self, variable: V, assignment: Dict[V, D]) -> bool:\n",
" for constraint in self.constraints[variable]:\n",
" if not constraint.satisfied(assignment):\n",
" return False\n",
" return True\n",
"\n",
" def backtracking_search(self, assignment: Dict[V, D] = {}) -> Optional[Dict[V, D]]:\n",
" # assignment is complete if every variable is assigned (our base case)\n",
" if len(assignment) == len(self.variables):\n",
" return assignment\n",
"\n",
" # get all variables in the CSP but not in the assignment\n",
" unassigned: List[V] = [v for v in self.variables if v not in assignment]\n",
"\n",
" # get the every possible domain value of the first unassigned variable\n",
" first: V = unassigned[0]\n",
" for value in self.domains[first]:\n",
" local_assignment = assignment.copy()\n",
" local_assignment[first] = value\n",
" # if we're still consistent, we recurse (continue)\n",
" if self.consistent(first, local_assignment):\n",
" result: Optional[Dict[V, D]] = self.backtracking_search(local_assignment)\n",
" # if we didn't find the result, we will end up backtracking\n",
" if result is not None:\n",
" return result\n",
" return None"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{

11
18CSC305JARTIFICIAL INTELLIGENCE

"name": "stdout",
"output_type": "stream",
"text": [
"{'Western Australia': 'red', 'Northern Territory': 'green', 'South Australia': 'blue', 'Queensland':
'red', 'New South Wales': 'green', 'Victoria': 'red', 'Tasmania': 'green'}\n"
]
}
],
"source": [
"\n",
"\n",
"\n",
"\n",
"class MapColoringConstraint(Constraint[str, str]):\n",
" def __init__(self, place1: str, place2: str) -> None:\n",
" super().__init__([place1, place2])\n",
" self.place1: str = place1\n",
" self.place2: str = place2\n",
"\n",
" def satisfied(self, assignment: Dict[str, str]) -> bool:\n",
" # If either place is not in the assignment then it is not\n",
" # yet possible for their colors to be conflicting\n",
" if self.place1 not in assignment or self.place2 not in assignment:\n",
" return True\n",
" # check the color assigned to place1 is not the same as the\n",
" # color assigned to place2\n",
" return assignment[self.place1] != assignment[self.place2]\n",
"\n",
"\n",
"if __name__ == \"__main__\":\n",
" variables: List[str] = [\"Western Australia\", \"Northern Territory\", \"South Australia\",\n",
" \"Queensland\", \"New South Wales\", \"Victoria\", \"Tasmania\"]\n",
" domains: Dict[str, List[str]] = {}\n",
" for variable in variables:\n",
" domains[variable] = [\"red\", \"green\", \"blue\"]\n",
" csp: CSP[str, str] = CSP(variables, domains)\n",
" csp.add_constraint(MapColoringConstraint(\"Western Australia\", \"Northern Territory\"))\
n",
" csp.add_constraint(MapColoringConstraint(\"Western Australia\", \"South Australia\"))\n",
" csp.add_constraint(MapColoringConstraint(\"South Australia\", \"Northern Territory\"))\n",
" csp.add_constraint(MapColoringConstraint(\"Queensland\", \"Northern Territory\"))\n",
" csp.add_constraint(MapColoringConstraint(\"Queensland\", \"South Australia\"))\n",
" csp.add_constraint(MapColoringConstraint(\"Queensland\", \"New South Wales\"))\n",
" csp.add_constraint(MapColoringConstraint(\"New South Wales\", \"South Australia\"))\n",
" csp.add_constraint(MapColoringConstraint(\"Victoria\", \"South Australia\"))\n",
" csp.add_constraint(MapColoringConstraint(\"Victoria\", \"New South Wales\"))\n",
" csp.add_constraint(MapColoringConstraint(\"Victoria\", \"Tasmania\"))\n",
" solution: Optional[Dict[str, str]] = csp.backtracking_search()\n",
" if solution is None:\n",
" print(\"No solution found!\")\n",
" else:\n",

12
18CSC305JARTIFICIAL INTELLIGENCE

" print(solution)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
OUTPUT:

RESULT:

Thus, the Program to identify territories in Australia has been implemented successfully

DATE: IMPLEMENTATION AND ANALYSIS OF BREATH FIRST


SEARCH AND DEPTH FIRST SEARCH FOR AN

13
18CSC305JARTIFICIAL INTELLIGENCE

EX.NO: 4 APPLICATION

AIM:

To write a Program to implement BFS and DFS

ALGORITHM:

DFS:

1. Find DFS traversal from starting vertex.

2. Create memo once in top-level call.

3. Generate adjacency list for undirected graph.

BFS:

1. BFS algorithm in python

2. Dequeue a vertex from queue

3. If not visited, mark it as visited and enqueue it.

Code:

Breath First search:

graph = {

'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = [] # List to keep track of visited nodes.


queue = [] #Initialize a queue

def bfs(visited, graph, node):


visited.append(node)
queue.append(node)

while queue:
s = queue.pop(0)
print (s, end = " ")

for neighbour in graph[s]:


if neighbour not in visited:

14
18CSC305JARTIFICIAL INTELLIGENCE

visited.append(neighbour)
queue.append(neighbour)

# Driver Code
bfs(visited, graph, 'A')

OUTPUT:

Depth first Search:


# Using a Python dictionary to act as an adjacency list
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}

visited = set() # Set to keep track of visited nodes.

def dfs(visited, graph, node):


if node not in visited:
print (node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)

15
18CSC305JARTIFICIAL INTELLIGENCE

# Driver Code
dfs(visited, graph, 'A')

OUTPUT:

RESULT: Thus, the Program to implement BFS and DFS is executed and verified successfully

DATE: DEVELOPING BEST FIRST SEARCH AND A* ALGORITHM


FOR REAL WORLD PROBLEMS
EX.NO: 5

AIM:

To write a program for the Implementation of A* Algorithm via Python

ALGORITHM:
16
18CSC305JARTIFICIAL INTELLIGENCE

1. A node class for A* Pathfinding

2. Returns a list of tuples as a path from the given start to the given end

in the given maze.

3. Create start and end node.

4. Initialize both open and closed list.

5. Add the start node.

6. Loop until you find the end.

7. Get the current node.

8. Pop current off open list, add to closed list.

9. Generate children.

10. Get node position.

11. Add the child to the open list.

Code:

OUTPUT:

17
18CSC305JARTIFICIAL INTELLIGENCE

AIM:
Implementation of Best First Search

Code:

OUTPUT:

RESULT: Thus, the code for the implementation of A*algorithim and best first search is executed
and verified successfully

18
18CSC305JARTIFICIAL INTELLIGENCE

DATE: IMPLEMENTATION OF MINIMAX ALGORITHM FOR AN


APPLICATION
EX.NO: 6

AIM:

To write a Program to implement minimax algorithm in Tic Tac Toe with Tkinter

ALGORITHM:

1. Import libraries.

2. Create a new game and game state.

3. Set the number of noughts and crosses in a row that is needed to win the game.

4. Create vectors and Set lengths.

5. Set the starting player at random and get winning positions.

6. Loop the board and vectors.

7. Get the start position and vector deltas.

8. Create a counter and Loop until we are outside the board.

9. Add winning positions and Break out from the loop

10. Update the position.

11. Check if the loop should terminate.

12. Get a heuristic move at cut off.

13. Check if the game has ended, break out from the loop in that case.

14. Get a recommended move.

15. Get a heuristic move at cut off.

19
18CSC305JARTIFICIAL INTELLIGENCE

16. Check if the move is legal.

17. Create a heuristic dictionary.

18. Check if number is in a winning position and calculate the number of X: s and O: s

19. Get the best move from the heuristic dictionary and return the best move.

20. Check if the game has ended and return a tie.

21. Check if a player has won.

22. Loop until we are outside the board or have moved the number of steps in the goal.

23. Check if a player has a piece in the tile.

24. Check if the loop should terminate.

25. Return None if no winner is found.

26. Get a min value (O)

27. Set min value to max value if it is lower than current min value.

28. Do an alpha test and beta test.

29. Get max value (X)

30. Check if the game has ended.

31. Add a piece to the board.

32. Set max value to min value if min value is greater than current max value.

33. Adjust the max value.

34. Print the current game state.

35. Tell python to run main method

Code:
# coding=UTF8
from Tkinter import Tk, Button
from tkFont import Font
from copy import deepcopy

class Board:

def __init__(self,other=None):
self.player = 'X'
self.opponent = 'O'
self.empty = '.'
self.size = 3
self.fields = {}
20
18CSC305JARTIFICIAL INTELLIGENCE

for y in range(self.size):
for x in range(self.size):
self.fields[x,y] = self.empty
# copy constructor
if other:
self.__dict__ = deepcopy(other.__dict__)

def move(self,x,y):
board = Board(self)
board.fields[x,y] = board.player
(board.player,board.opponent) = (board.opponent,board.player)
return board

def __minimax(self, player):


if self.won():
if player:
return (-1,None)
else:
return (+1,None)
elif self.tied():
return (0,None)
elif player:
best = (-2,None)
for x,y in self.fields:
if self.fields[x,y]==self.empty:
value = self.move(x,y).__minimax(not player)[0]
if value>best[0]:
best = (value,(x,y))
return best
else:
best = (+2,None)
for x,y in self.fields:
if self.fields[x,y]==self.empty:
value = self.move(x,y).__minimax(not player)[0]
if value<best[0]:
best = (value,(x,y))
return best

def best(self):
return self.__minimax(True)[1]

def tied(self):
for (x,y) in self.fields:
if self.fields[x,y]==self.empty:
return False
return True

def won(self):
# horizontal
for y in range(self.size):
winning = []

21
18CSC305JARTIFICIAL INTELLIGENCE

for x in range(self.size):
if self.fields[x,y] == self.opponent:
winning.append((x,y))
if len(winning) == self.size:
return winning
# vertical
for x in range(self.size):
winning = []
for y in range(self.size):
if self.fields[x,y] == self.opponent:
winning.append((x,y))
if len(winning) == self.size:
return winning
# diagonal
winning = []
for y in range(self.size):
x=y
if self.fields[x,y] == self.opponent:
winning.append((x,y))
if len(winning) == self.size:
return winning
# other diagonal
winning = []
for y in range(self.size):
x = self.size-1-y
if self.fields[x,y] == self.opponent:
winning.append((x,y))
if len(winning) == self.size:
return winning
# default
return None

def __str__(self):
string = ''
for y in range(self.size):
for x in range(self.size):
string+=self.fields[x,y]
string+="\n"
return string

class GUI:

def __init__(self):
self.app = Tk()
self.app.title('TicTacToe')
self.app.resizable(width=False, height=False)
self.board = Board()
self.font = Font(family="Helvetica", size=32)
self.buttons = {}
for x,y in self.board.fields:
handler = lambda x=x,y=y: self.move(x,y)

22
18CSC305JARTIFICIAL INTELLIGENCE

button = Button(self.app, command=handler, font=self.font, width=2, height=1)


button.grid(row=y, column=x)
self.buttons[x,y] = button
handler = lambda: self.reset()
button = Button(self.app, text='reset', command=handler)
button.grid(row=self.board.size+1, column=0, columnspan=self.board.size, sticky="WE")
self.update()

def reset(self):
self.board = Board()
self.update()

def move(self,x,y):
self.app.config(cursor="watch")
self.app.update()
self.board = self.board.move(x,y)
self.update()
move = self.board.best()
if move:
self.board = self.board.move(*move)
self.update()
self.app.config(cursor="")

def update(self):
for (x,y) in self.board.fields:
text = self.board.fields[x,y]
self.buttons[x,y]['text'] = text
self.buttons[x,y]['disabledforeground'] = 'black'
if text==self.board.empty:
self.buttons[x,y]['state'] = 'normal'
else:
self.buttons[x,y]['state'] = 'disabled'
winning = self.board.won()
if winning:
for x,y in winning:
self.buttons[x,y]['disabledforeground'] = 'red'
for x,y in self.buttons:
self.buttons[x,y]['state'] = 'disabled'
for (x,y) in self.board.fields:
self.buttons[x,y].update()

def mainloop(self):
self.app.mainloop()

if __name__ == '__main__':
GUI().mainloop()

OUTPUT:

23
18CSC305JARTIFICIAL INTELLIGENCE

1. 2.

3.

HERE THE DRAW IS DEPICTED SINCE It Was DELIBRATE.

24
18CSC305JARTIFICIAL INTELLIGENCE

RESULT: Thus, the implementation of minmax algorithm is executed and verified successfully

DATE: IMPLEMENTATION OF UNIFICATION AND RESOLUTION


FOR REAL WORLD PROBLEMS
EX.NO: 7

AIM:

To write a Program to implement unification With Python

ALGORITHM:

Step 1: If Ψ1 or Ψ2 is a variable or constant, then:

a. If Ψ1 or Ψ2 are identical, then return NULL.

b. Else if Ψ1 is a variable: -then if Ψ1 occurs in Ψ2, then return False

-Else return (Ψ2 / Ψ1)

c. Else if Ψ2 is a variable: -then if Ψ2 occurs in Ψ1, then return False

-Else return (Ψ1 / Ψ2)

d. Else return False.

Step 2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return False.

Step 3: IF Ψ1 and Ψ2 have a different number of arguments, then return False.

Step 4: Create Substitution list.

Step 5: For i=1 to the number of elements in Ψ1. a. Call Unify function with the i th element of Ψ1
and i th element of Ψ2, and put the result into S. b. If S = False then returns False c. If S ≠ Null
then append to Substitution list

Step 6: Return Substitution list

Code:

def get_index_comma(string):
"""
Return index of commas in string
"""

index_list = list()
# Count open parentheses
par_count = 0

25
18CSC305JARTIFICIAL INTELLIGENCE

for i in range(len(string)):
if string[i] == ',' and par_count == 0:
index_list.append(i)
elif string[i] == '(':
par_count += 1
elif string[i] == ')':
par_count -= 1

return index_list

def is_variable(expr):
"""
Check if expression is variable
"""

for i in expr:
if i == '(':
return False

return True

def process_expression(expr):
"""
input: - expression:
'Q(a, g(x, b), f(y))'
return: - predicate symbol:
Q
- list of arguments
['a', 'g(x, b)', 'f(y)']
"""

# Remove space in expression


expr = expr.replace(' ', '')

# Find the first index == '('


index = None
for i in range(len(expr)):
if expr[i] == '(':
index = i
break

# Return predicate symbol and remove predicate symbol in expression


predicate_symbol = expr[:index]
expr = expr.replace(predicate_symbol, '')

# Remove '(' in the first index and ')' in the last index
expr = expr[1:len(expr) - 1]

26
18CSC305JARTIFICIAL INTELLIGENCE

# List of arguments
arg_list = list()

# Split string with commas, return list of arguments


indices = get_index_comma(expr)

if len(indices) == 0:
arg_list.append(expr)
else:
arg_list.append(expr[:indices[0]])
for i, j in zip(indices, indices[1:]):
arg_list.append(expr[i + 1:j])
arg_list.append(expr[indices[len(indices) - 1] + 1:])

return predicate_symbol, arg_list

def get_arg_list(expr):
"""
input: expression:
'Q(a, g(x, b), f(y))'
return: full list of arguments:
['a', 'x', 'b', 'y']
"""

_, arg_list = process_expression(expr)

flag = True
while flag:
flag = False

for i in arg_list:
if not is_variable(i):
flag = True
_, tmp = process_expression(i)
for j in tmp:
if j not in arg_list:
arg_list.append(j)
arg_list.remove(i)

return arg_list

def check_occurs(var, expr):


"""
Check if var occurs in expr
"""

arg_list = get_arg_list(expr)
if var in arg_list:
return True

27
18CSC305JARTIFICIAL INTELLIGENCE

return False

def unify(expr1, expr2):


"""
Unification Algorithm

Step 1: If Ψ1 or Ψ2 is a variable or constant, then:


a, If Ψ1 or Ψ2 are identical, then return NULL.
b, Else if Ψ1 is a variable:
- then if Ψ1 occurs in Ψ2, then return False
- Else return (Ψ2 / Ψ1)
c, Else if Ψ2 is a variable:
- then if Ψ2 occurs in Ψ1, then return False
- Else return (Ψ1 / Ψ2)
d, Else return False

Step 2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return False.

Step 3: IF Ψ1 and Ψ2 have a different number of arguments, then return False.

Step 4: Create Substitution list.

Step 5: For i=1 to the number of elements in Ψ1.


a, Call Unify function with the ith element of Ψ1 and ith element of Ψ2, and put the
result into S.
b, If S = False then returns False
c, If S ≠ Null then append to Substitution list

Step 6: Return Substitution list.


"""

# Step 1:
if is_variable(expr1) and is_variable(expr2):
if expr1 == expr2:
return 'Null'
else:
return False
elif is_variable(expr1) and not is_variable(expr2):
if check_occurs(expr1, expr2):
return False
else:
tmp = str(expr2) + '/' + str(expr1)
return tmp
elif not is_variable(expr1) and is_variable(expr2):
if check_occurs(expr2, expr1):
return False
else:
tmp = str(expr1) + '/' + str(expr2)
return tmp

28
18CSC305JARTIFICIAL INTELLIGENCE

else:
predicate_symbol_1, arg_list_1 = process_expression(expr1)
predicate_symbol_2, arg_list_2 = process_expression(expr2)

# Step 2
if predicate_symbol_1 != predicate_symbol_2:
return False
# Step 3
elif len(arg_list_1) != len(arg_list_2):
return False
else:
# Step 4: Create substitution list
sub_list = list()

# Step 5:
for i in range(len(arg_list_1)):
tmp = unify(arg_list_1[i], arg_list_2[i])

if not tmp:
return False
elif tmp == 'Null':
pass
else:
if type(tmp) == list:
for j in tmp:
sub_list.append(j)
else:
sub_list.append(tmp)

# Step 6
return sub_list

if __name__ == '__main__':
# Data 1
f1 = 'p(b(A), X, f(g(Z)))'
f2 = 'p(Z, f(Y), f(Y))'

# Data 2
# f1 = 'Q(a, g(x, a), f(y))'
# f2 = 'Q(a, g(f(b), a), x)'

# Data 3
# f1 = 'Q(a, g(x, a, d), f(y))'
# f2 = 'Q(a, g(f(b), a), x)'

result = unify(f1, f2)


if not result:
print('Unification failed!')
else:
print('Unification successfully!')

29
18CSC305JARTIFICIAL INTELLIGENCE

OUTPUT:

RESULT: Thus the code for implementation of unification and resolution is executed and verified
successfully.

30
18CSC305JARTIFICIAL INTELLIGENCE

DATE: IMPLEMENTATION OF KNOWLEDGE REPRESENTATION


SCHEMES – USE CASES
EX.NO: 8

AIM:

To write a Program to solve Sudoku using Knowledge Representation

ALGORITHM:

1. Function to check if all cells are assigned or not.

2. If there is any unassigned cell, then that function will change the values of row and col
accordingly.

3. Function to check if we can put a value in a particular cell or not.

4. Checking sub matrix

5. Function to solve sudoku using backtracking.

6. If all cells are assigned, then the sudoku is already solved.

7. If we can’t proceed with this solution, reassign the cell.

Code:

size = 9
#empty cells have value zero
matrix = [
[5,3,0,0,7,0,0,0,0],
[6,0,0,1,9,5,0,0,0],
[0,9,8,0,0,0,0,6,0],
[8,0,0,0,6,0,0,0,3],
[4,0,0,8,0,3,0,0,1],
[7,0,0,0,2,0,0,0,6],
[0,6,0,0,0,0,2,8,0],
[0,0,0,4,1,9,0,0,5],
[0,0,0,0,8,0,0,7,9]]

#print sudoku
def print_sudoku():
for i in matrix:
print (i)

#assign cells and check


def number_unassigned(row, col):

1
18CSC305JARTIFICIAL INTELLIGENCE

num_unassign = 0
for i in range(0,size):
for j in range (0,size):
#cell is unassigned
if matrix[i][j] == 0:
row = i
col = j
num_unassign = 1
a = [row, col, num_unassign]
return a
a = [-1, -1, num_unassign]
return a
#check validity of number
def is_safe(n, r, c):
#checking in row
for i in range(0,size):
#there is a cell with same value
if matrix[r][i] == n:
return False
#checking in column
for i in range(0,size):
#there is a cell with same value
if matrix[i][c] == n:
return False
row_start = (r//3)*3
col_start = (c//3)*3;
#checking submatrix
for i in range(row_start,row_start+3):
for j in range(col_start,col_start+3):
if matrix[i][j]==n:
return False
return True

#check validity of number


def solve_sudoku():
row = 0
col = 0
#if all cells are assigned then the sudoku is already solved
#pass by reference because number_unassigned will change the values of row and col
a = number_unassigned(row, col)
if a[2] == 0:
return True
row = a[0]
col = a[1]
#number between 1 to 9
for i in range(1,10):
#if we can assign i to the cell or not
#the cell is matrix[row][col]
if is_safe(i, row, col):
matrix[row][col] = i

2
18CSC305JARTIFICIAL INTELLIGENCE

#backtracking
if solve_sudoku():
return True
#f we can't proceed with this solution
#reassign the cell
matrix[row][col]=0
return False

if solve_sudoku():
print_sudoku()
else:
print("No solution")

OUTPUT:

RESULT: Thus, the Program to solve Sudoku using Knowledge Representation is executed
and verified successfully.

3
18CSC305JARTIFICIAL INTELLIGENCE

DATE: IMPLEMENTATION OF UNCERTAIN METHODS FOR AN


APPLICATION
EX.NO: 9

AIM:

To write a Program to solve the Monty Python Problem using Python

ALGORITHM:

# prediction y

_pred_without_dropout = model_without_dropout.predict(x_test)

y_pred_with_dropout = model_with_dropout.predict(x_test)

# plotting

fig, ax = plt.subplots(1,1,figsize=(10,5))

ax.scatter(x_train, y_train, s=10, label='train data')

ax.plot(x_test, x_test, ls='--', label='test data', color='green')

ax.plot(x_test, y_pred_without_dropout, label='predicted ANN - R2


{:.2f}'.format(r2_score(x_test, y_pred_without_dropout)), color='red')

ax.plot(x_test, y_pred_with_dropout, label='predicted ANN Dropout - R2


{:.2f}'.format(r2_score(x_test, y_pred_with_dropout)), color='black')

ax.set_xlabel('x')

ax.set_ylabel('y')

ax.legend()

ax.set_title('test data');

Code:
import matplotlib.pyplot as plt
import seaborn; seaborn.set_style('whitegrid')
import numpy

from pomegranate import *

numpy.random.seed(0)
numpy.set_printoptions(suppress=True)

4
18CSC305JARTIFICIAL INTELLIGENCE

# The guests initial door selection is completely random


guest = DiscreteDistribution({'A': 1./3, 'B': 1./3, 'C': 1./3})

# The door the prize is behind is also completely random


prize = DiscreteDistribution({'A': 1./3, 'B': 1./3, 'C': 1./3})

# Monty is dependent on both the guest and the prize.


monty = ConditionalProbabilityTable(
[[ 'A', 'A', 'A', 0.0 ],
[ 'A', 'A', 'B', 0.5 ],
[ 'A', 'A', 'C', 0.5 ],
[ 'A', 'B', 'A', 0.0 ],
[ 'A', 'B', 'B', 0.0 ],
[ 'A', 'B', 'C', 1.0 ],
[ 'A', 'C', 'A', 0.0 ],
[ 'A', 'C', 'B', 1.0 ],
[ 'A', 'C', 'C', 0.0 ],
[ 'B', 'A', 'A', 0.0 ],
[ 'B', 'A', 'B', 0.0 ],
[ 'B', 'A', 'C', 1.0 ],
[ 'B', 'B', 'A', 0.5 ],
[ 'B', 'B', 'B', 0.0 ],
[ 'B', 'B', 'C', 0.5 ],
[ 'B', 'C', 'A', 1.0 ],
[ 'B', 'C', 'B', 0.0 ],
[ 'B', 'C', 'C', 0.0 ],
[ 'C', 'A', 'A', 0.0 ],
[ 'C', 'A', 'B', 1.0 ],
[ 'C', 'A', 'C', 0.0 ],
[ 'C', 'B', 'A', 1.0 ],
[ 'C', 'B', 'B', 0.0 ],
[ 'C', 'B', 'C', 0.0 ],
[ 'C', 'C', 'A', 0.5 ],
[ 'C', 'C', 'B', 0.5 ],
[ 'C', 'C', 'C', 0.0 ]], [guest, prize])

# State objects hold both the distribution, and a high level name.
s1 = State(guest, name="guest")
s2 = State(prize, name="prize")
s3 = State(monty, name="monty")
# Create the Bayesian network object with a useful name
model = BayesianNetwork("Monty Hall Problem")

# Add the three states to the network


model.add_states(s1, s2, s3)
# Add edges which represent conditional dependencies, where the second node is
# conditionally dependent on the first node (Monty is dependent on both guest and prize)
model.add_edge(s1, s3)
model.add_edge(s2, s3)
model.bake()

5
18CSC305JARTIFICIAL INTELLIGENCE

model.probability([['A', 'B', 'C']])


model.probability([['A', 'B', 'C']])
print(model.predict_proba({}))
print(model.predict_proba([[None, None, None]]))
print(model.predict_proba([['A', None, None]]))
print(model.predict_proba([{'guest': 'A', 'monty': 'B'}]))

OUTPUT:

6
18CSC305JARTIFICIAL INTELLIGENCE

7
18CSC305JARTIFICIAL INTELLIGENCE

RESULT:

Thus, the Program to solve the Monty Python Problem using Python is executed and verified
successfully

8
18CSC305JARTIFICIAL INTELLIGENCE

DATE: IMPLEMENTATION OF BLOCK WORLD PROBLEM

EX.NO: 10

AIM:

To write a Program to Implement Block world

ALGORITHM:

1. If Block is on another block, unstack.

2. If block is on table, pick up.

3. Initially push the goal state as compound goal onto the stack

4. Repeat until the stack is empty.

5. Get the top of the stack.

6. If Stack Top is Compound Goal, push its unsatisfied goals onto stack.

7. If Stack Top is an action and peek the operation

8. Check if any precondition is unsatisfied and push it onto program stack.

9. If all preconditions are satisfied, pop operation from stack and execute it.

10. If Stack Top is a single unsatisfied goal, Replace Unsatisfied Goal with an action that can
complete it.

11. Push Precondition on the stack.

Code:

import time
import sys
import os
from state import State
from searching import breadth_first_search
from utilities import read_input_file, write_output_file
def main():
st = time.perf_counter() #Start a time counter.

9
18CSC305JARTIFICIAL INTELLIGENCE

if len(sys.argv) == 4: #If the length of the keyword arguments is four...


method = sys.argv[1] #The second argument is the method/algorithm used to find a
solution.
input_file = sys.argv[2] #The third argument is a .txt file containing the initial and
final state of the problem.
output_file = sys.argv[3] #The fourth argument is a .txt file containing the solution of
the problem.
initial_state, goal_state = read_input_file(filename = input_file) #Read the input file
and return two state objects.
if method == 'breadth': #Check which method is selected and solve the problem
accordingly.
solution = breadth_first_search(current_state = initial_state, goal_state = goal_state,
timeout = 300)
else: #If the method argument is none of the above, print a usage message.
solution = None
print('Usage: python bw.py <method> <input filename> <output filename>')
if solution == goal_state: #If the solution is equal to the goal state...
number_of_moves = write_output_file(solution = solution, filename = output_file)
#Write the solution file and return the number of moves.
print('Solution found!')
print('Number of blocks:', len(initial_state.layout.keys()))
print('Method:', method)
print('Number of moves:', number_of_moves)
print('Execution time:', str(round(time.perf_counter() - st, 4)))
else: #Else, if the length of the keyword arguments is not equal to four, print a usage
message.
print('Usage: python bw.py <method> <input filename> <output filename>')
if __name__ == '__main__':
main()
Searching.py
import time
from collections import deque
def breadth_first_search(current_state, goal_state, timeout = 60):

10
18CSC305JARTIFICIAL INTELLIGENCE

"""
An implementation of the BFS algorithm, taking as arguments a current_state
i.e. initial state, a goal state and an optional argument timeout (default 60)
indicating the time before the algorithm stops if no solution is found.
A queue is used as a structure for storing the nodes/states and a set for keeping the
ids of the discovered states in order to check quicker whether a node has been discovered.
"""
Q = deque([]) #A queue for storing the nodes/states.
discovered = set() #A set for keeping the ids of the discovered states.
Q.append(current_state) #Add the current/initial state to the queue.
discovered.add(current_state.id) #Add the id of the state to the set.
st = time.perf_counter() #Start a time counter.
while Q: #While Q is not empty...
if time.perf_counter() - st > timeout: #If the execution time exceeds the timeout...
print('Timeout!')
return None #Break.
state = Q.popleft() #Dequeue an element from the left of Q.
if state == goal_state: #If the state is the goal state, return it and break.
return state
children = state.calcChildren() #Else, calculate the children of this state.
for child in children: #For each child...
if child.id not in discovered: #If this child has not been discovered...
discovered.add(child.id) #Mark it as discovered.
child.parent = state #Set the parent attribute of the child to be the state that has
been dequeued.
Q.append(child) #Append the child to Q.
State.py
from copy import deepcopy
class State:
def __init__(self, layout, parent = None, move = [], distance = 0):

11
18CSC305JARTIFICIAL INTELLIGENCE

self.layout = layout
self.parent = parent
self.move = move
self.distance = distance
values = list(self.layout.values()) #A list of the names of the blocks.
self.id = ''.join([str(i) for s in values for i in s]) #Create the id attribute.
def __eq__(self, other_state):
if other_state != None:
return self.id == other_state.id
else:
return False
def calcChildren(self):
layout = self.layout
children = []
free_blocks = [key for key in layout if layout[key][1] == 'c'] #The blocks that can be
moved.
for moving_block in free_blocks: #For each free block that will be moved...
for target_block in free_blocks:
if moving_block != target_block:
temp = deepcopy(layout) #Copy the current layout in order to alter it.
move = []
distance = 0
released_block = temp[moving_block][0] #The 'released_block' is the first
item of the list in layout with key == moving_block.
temp[moving_block][0] = target_block #The 'moving block' now is on top of
the 'target_block'.
temp[target_block][1] = 'u' #And the 'target_block' is now unclear.
move.append(moving_block) #Add the 'moving_block' to 'move' list.
if released_block != '-': #If the 'released_block" is not '-' i.e. is not on the
table...
temp[released_block][1] = 'c' #Set the block clear.

12
18CSC305JARTIFICIAL INTELLIGENCE

move.append(released_block) #Add the 'released_block' to 'move' list.


else:
move.append('table')
move.append(target_block) #Add the 'target_block' to 'move' list.
distance = self.distance + 1 #The distance of the child is the distance of the
parent plus 1.
children.append(State(layout = temp, parent = self, move = move, distance =
distance)) #Add to 'children' list a new State object.
if layout[moving_block][0] != '-': #If the 'moving_block' is not currently on the
table, create a state that it is.
temp = deepcopy(layout)
move = []
distance = 0
released_block = temp[moving_block][0] #The 'released_block' is the first item
of the list in layout with key == moving_block.
temp[moving_block][0] = '-'
temp[released_block][1] = 'c' #Set the block clear.
move.append(moving_block) #Add the 'moving_block' to 'move' list.
move.append(released_block) #Add the 'released_block' to 'move' list.
move.append('table')
distance = self.distance + 1 #The distance of the child is the distance of the
parent plus 1.
children.append(State(layout = temp, parent = self, move = move, distance =
distance)) #Add to 'children' list a new State object.
return children #Return the children list
Utilities.py
from state import State
def read_input_file(filename):
with open('problems/' + filename) as f:
lines = [line.split() for line in f] #Read the file by line and split it.
blocks_names = lines[0][1:] #Get the blocks names.

13
18CSC305JARTIFICIAL INTELLIGENCE

blocks_names[-1] = blocks_names[-1][:-1] #Remove the parenthesis from the last


block name.
initial = lines[1][1:-1] #Get the initial state.
initial = [i.replace('(', '') for i in initial] #Remove the parentheses.
initial = [i.replace(')', '') for i in initial]
goal = lines[2][2:] #Get the goal state.
goal = [i.replace('(', '') for i in goal] #Remove the parentheses.
goal = [i.replace(')', '') for i in goal]
initial_layout = {key: ['-', 'c'] for key in blocks_names} #Construct the inital layout.
goal_layout = {key: ['-', 'c'] for key in blocks_names} #Construct the goal layout.
for i in range(len(initial)):
if initial[i] == 'ON':
initial_layout[initial[i + 1]][0] = initial[i + 2]
initial_layout[initial[i + 2]][1] = 'u'
for i in range(len(goal)):
if goal[i] == 'ON':
goal_layout[goal[i + 1]][0] = goal[i + 2]
goal_layout[goal[i + 2]][1] = 'u'
return State(layout = initial_layout), State(layout = goal_layout) #Return two state
objects.
def write_output_file(solution, filename):
current_state = solution #The state we start, which is the last i.e. the solution.
path = [] #The path from the solution towards the intial state.
i=1
while True:
path.append(current_state) #Add the current state i.e. solution, in the list.
current_state = current_state.parent #The current state now becomes the parent of it.
if current_state.parent == None: #If the current state has no parent...
path.append(current_state) #Add the current state in the list.
break

14
18CSC305JARTIFICIAL INTELLIGENCE

path.reverse() #Reverse the list.


with open(filename, 'w') as f: #Open the output file.
for state in path[1:]: #For every state in the path, except the first one which is the
initial state that has no previous move...
move = state.move #Get the move.
f.write(str(i) + '. Move(' + move[0] + ', ' + move[1] + ', ' + move[2] + ')\n') #Write
the move.
i += 1 #Increment the counter.
return len(path[1:]) #Return the number of steps.
OUTPUT:

RESULT: Thus, the program to implement block world problem is successfully executed
and verified successfully.

15
18CSC305JARTIFICIAL INTELLIGENCE

DATE:
IMPLEMENTATION OF LEARNING ALGORITHMS FOR AN
APPLICATION
EX.NO: 11

AIM:
To write a program for the Implementation of Linear Regression algorithm

ALGORITHM:
Import Matplotlib:
a. Use the "import" statement to import the Matplotlib library.
Prepare the data:
a. Create a dataset that you want to visualize using Matplotlib.
b. Ensure that the data is in a format that Matplotlib can use, such as a
NumPy array or a Pandas DataFrame.

Create a figure:
a. Use the "plt.figure()" function to create a new figure object.
b. Specify the size and other properties of the figure if necessary.

Create a plot:
a. Use one of the many plot functions available in Matplotlib, such as
"plt.plot()" or "plt.scatter()", to create a plot of the data.
b. Specify the data to be plotted, the color, the marker style, and other
properties of the plot.

Add titles and labels:


a. Use the "plt.title()" function to add a title to the plot.
b. Use the "plt.xlabel()" and "plt.ylabel()" functions to add labels to the x
and y axes of the plot.

Customize the plot:


a. Use various Matplotlib functions to customize the appearance of the plot,
such as changing the font size or style, adjusting the axis limits, or adding a
legend.

Save or show the plot:


a. Use the "plt.savefig()" function to save the plot to a file in a specified
format, such as PNG, PDF, or SVG.
b. Use the "plt.show()" function to display the plot on the screen.

Code:

import numpy as np
import matplotlib.pyplot as plt
def estimate_coef(x, y):

16
18CSC305JARTIFICIAL INTELLIGENCE

n = np.size(x)
m_x = np.mean(x)
m_y = np.mean(y)
SS_xy = np.sum(y*x) - n*m_y*m_x
SS_xx = np.sum(x*x) - n*m_x*m_x
b_1 = SS_xy / SS_xx
b_0 = m_y - b_1*m_x
return (b_0, b_1)

def plot_regression_line(x, y, b):


plt.scatter(x, y, color = "m",
marker = "o", s = 30)
y_pred = b[0] + b[1]*x
plt.plot(x, y_pred, color = "g")
plt.xlabel('x')
plt.ylabel('y')
plt.show()

def main():
x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
y = np.array([1, 3, 2, 5, 7, 8, 8, 9, 10, 12])
b = estimate_coef(x, y)
print("Estimated coefficients:\nb_0 = {} \
\nb_1 = {}".format(b[0], b[1]))
plot_regression_line(x, y, b)

if __name__ == "__main__":
main()

17
18CSC305JARTIFICIAL INTELLIGENCE

OUTPUT:

RESULT:
Thus, the program for the Implementation of Linear Regression algorithm is executed and
verified successfully.

18
18CSC305JARTIFICIAL INTELLIGENCE

DATE: DEVELOPMENT OF ENSEMBLE MODEL FOR ANY


APPLICATION
EX.NO: 12&13

AIM:
To predict whether a bank currency note is authentic or not based on four attributes using
Random Forest classification

ALGORITHM:
1. Load libraries
2. Import train_test_split function.
3. Load data
4. Split dataset into training set and test set
5. Import Support Vector Classifier
6. Import scikit-learn metrics module for accuracy calculation.
7. Create adaboost classifer object.
8. Train Adaboost Classifer
9. Predict the response for test dataset

Code:

import pandas as pd
import numpy as np
dataset = pd.read_csv("D:/Datasets/bill_authentication.csv")
dataset.head()
X = dataset.iloc[:, 0:4].values
y = dataset.iloc[:, 4].values
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)


# Feature Scaling
from sklearn.preprocessing import StandardScaler

sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))
= sc.transform(X_test)
from sklearn.ensemble import RandomForestRegressor

regressor = RandomForestRegressor(n_estimators=20, random_state=0)


regressor.fit(X_train, y_train)
y_pred = regressor.predict(X_test)

19
18CSC305JARTIFICIAL INTELLIGENCE

from sklearn.metrics import classification_report, confusion_matrix, accuracy_score

print(confusion_matrix(y_test,y_pred))
print(classification_report(y_test,y_pred))
print(accuracy_score(y_test, y_pred))

OUTPUT:

● Program to use IRIS dataset for multi-class classification using AdaBoost algorithm

Code:

# Load libraries
from sklearn.ensemble import AdaBoostClassifier
from sklearn import datasets
# Import train_test_split function
from sklearn.model_selection import train_test_split
#Import scikit-learn metrics module for accuracy calculation
from sklearn import metrics

# Load data
iris = datasets.load_iris()
X = iris.data

20
18CSC305JARTIFICIAL INTELLIGENCE

y = iris.target

# Split dataset into training set and test set


X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3) # 70% training and 30%
test

# Create adaboost classifer object


abc = AdaBoostClassifier(n_estimators=50,
learning_rate=1)
# Train Adaboost Classifer
model = abc.fit(X_train, y_train)

#Predict the response for test dataset


y_pred = model.predict(X_test)

# Model Accuracy, how often is the classifier correct?


print("Accuracy:",metrics.accuracy_score(y_test, y_pred))

OUTPUT:

● To build the classification model using the gradient boosting algorithm using
Boston Housing Dataset

Code:

from sklearn.ensemble import GradientBoostingRegressor


import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.datasets import load_boston
from sklearn.metrics import mean_absolute_error

boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.Series(boston.target)

X_train, X_test, y_train, y_test = train_test_split(X, y)

regressor = GradientBoostingRegressor(
max_depth=2,
n_estimators=3,
learning_rate=1.0

21
18CSC305JARTIFICIAL INTELLIGENCE

)
regressor.fit(X_train, y_train)

errors = [mean_squared_error(y_test, y_pred) for y_pred in regressor.staged_predict(X_test)]


best_n_estimators = np.argmin(errors)

best_regressor = GradientBoostingRegressor(
max_depth=2,
n_estimators=best_n_estimators,
learning_rate=1.0
)
best_regressor.fit(X_train, y_train)

y_pred = best_regressor.predict(X_test)
mean_absolute_error(y_test, y_pred)

OUTPUT:

RESULT:
Thus the code for the above following is executed and verified successfully.

22
18CSC305JARTIFICIAL INTELLIGENCE

DATE:
IMPLEMENTATION OF NLP PROGRAMS
EX.NO: 14

AIM:
To discriminate between ham/spam messages automatically using UCI datasets.

ALGORITHM:
1. Import libraries.
2. Load data
3. Rename names columns.
4. Join words again to form the string.
5. Remove any stopwords for message_not_punc, but first we should
transform this into the list.
6. Classification Model
7. Test model

Code:

# Import library
import pandas as pd
import numpy as np
import string
import seaborn as sns
import matplotlib.pyplot as plt
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from collections import Counter
from sklearn.metrics import classification_report,confusion_matrix
from sklearn.model_selection import GridSearchCV
%matplotlib inline
# Load data
data = pd.read_excel('data.xlsx')
# Rename names columns
data.columns = ['label', 'messages']

data.describe()

23
18CSC305JARTIFICIAL INTELLIGENCE

data["length"] = data["messages"].apply(len)
data.sort_values(by='length', ascending=False).head(10)

data.hist(column = 'length', by ='label',figsize=(12,4), bins = 5)

# Tokenization

def transform_message(message):
message_not_punc = [] # Message without punctuation
i=0
for punctuation in message:
if punctuation not in string.punctuation:
message_not_punc.append(punctuation)
# Join words again to form the string.
message_not_punc = ''.join(message_not_punc)

# Remove any stopwords for message_not_punc, but first we should


# to transform this into the list.
message_clean = list(message_not_punc.split(" "))
while i <= len(message_clean):
for mess in message_clean:
if mess.lower() in stopwords.words('english'):
message_clean.remove(mess)
i =i +1
return message_clean

# Vectorization
vectorization = CountVectorizer(analyzer = transform_message )
X = vectorization.fit(data['messages'])

X_transform = X.transform([data['messages']])

# TF-IDF
tfidf_transformer = TfidfTransformer().fit(X_transform)
X_tfidf = tfidf_transformer.transform(X_transform)
print(X_tfidf.shape)

# Classification Model

X_train, X_test, y_train, y_test = train_test_split(X_tfidf, data['messages'], test_size=0.30,


random_state = 50)
clf = SVC(kernel='linear').fit(X_train, y_train)

# Test model

predictions = clf.predict(X_test)
print('predicted', predictions)
# Is our model reliable?

print (classification_report(y_test, predictions))

24
18CSC305JARTIFICIAL INTELLIGENCE

print(confusion_matrix(y_test,predictions))

OUTPUT:

RESULT: Thus, the program To discriminate between ham/spam messages automatically


using UCI datasets is executed and verified successfully
25
18CSC305JARTIFICIAL INTELLIGENCE

DATE: APPLYING DEEP LEARNING METHOD FOR AUTOMATIC


HANDWRITING RECOGNITION
EX.NO: 15

AIM:
Program to implement deep learning method for Automatic Handwriting Recognition

ALGORITHM:

1. Import libraries.
2. Number of training epochs since start
3. Best validation character error rate
4. Number of epochs no improvement of character error rate occurred.
5. Stop training after this number of epochs without improvement.
6. Train, validate and write summary.
7. If best validation accuracy so far, save model parameters.
8. Stop training if no more improvement in the last x epochs.
9. Print validation result.
10. Set chosen CTC decoder.
11. Train or validate on IAM dataset.
12. Load training data, create TF model.
13. Save characters of model for inference mode
14. Save words contained in dataset into file.
15. Execute training or validation.
16. Infer text on test image

Code:

from keras.datasets import mnist


import matplotlib.pyplot as plt
import cv2
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Flatten, Conv2D, MaxPool2D, Dropout
from keras.optimizers import SGD, Adam
from keras.callbacks import ReduceLROnPlateau, EarlyStopping
from keras.utils import to_categorical
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils import np_utils
import matplotlib.pyplot as plt
from tqdm import tqdm_notebook
from sklearn.utils import shuffle

26
18CSC305JARTIFICIAL INTELLIGENCE

# Read the data...


data = pd.read_csv(r"D:\a-z alphabets\A_Z Handwritten Data.csv").astype('float32')

# Split data the X - Our data , and y - the prdict label


X = data.drop('0',axis = 1)
y = data['0']

# Reshaping the data in csv file so that it can be displayed as an image...

train_x, test_x, train_y, test_y = train_test_split(X, y, test_size = 0.2)


train_x = np.reshape(train_x.values, (train_x.shape[0], 28,28))
test_x = np.reshape(test_x.values, (test_x.shape[0], 28,28))

print("Train data shape: ", train_x.shape)


print("Test data shape: ", test_x.shape)

# Dictionary for getting characters from index values...


word_dict =
{0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I',9:'J',10:'K',11:'L',12:'M',13:'N',14:'O',15:'P',16:'
Q',17:'R',18:'S',19:'T',20:'U',21:'V',22:'W',23:'X', 24:'Y',25:'Z'}

# Plotting the number of alphabets in the dataset...

train_yint = np.int0(y)
count = np.zeros(26, dtype='int')
for i in train_yint:
count[i] +=1

alphabets = []
for i in word_dict.values():
alphabets.append(i)

fig, ax = plt.subplots(1,1, figsize=(10,10))


ax.barh(alphabets, count)

plt.xlabel("Number of elements ")


plt.ylabel("Alphabets")
plt.grid()
plt.show()

#Shuffling the data ...


shuff = shuffle(train_x[:100])

27
18CSC305JARTIFICIAL INTELLIGENCE

fig, ax = plt.subplots(3,3, figsize = (10,10))


axes = ax.flatten()

for i in range(9):
axes[i].imshow(np.reshape(shuff[i], (28,28)), cmap="Greys")
plt.show()

#Reshaping the training & test dataset so that it can be put in the model...

train_X = train_x.reshape(train_x.shape[0],train_x.shape[1],train_x.shape[2],1)
print("New shape of train data: ", train_X.shape)

test_X = test_x.reshape(test_x.shape[0], test_x.shape[1], test_x.shape[2],1)


print("New shape of train data: ", test_X.shape)

# Converting the labels to categorical values...

train_yOHE = to_categorical(train_y, num_classes = 26, dtype='int')


print("New shape of train labels: ", train_yOHE.shape)

test_yOHE = to_categorical(test_y, num_classes = 26, dtype='int')


print("New shape of test labels: ", test_yOHE.shape)

# CNN model...

model = Sequential()

model.add(Conv2D(filters=32, kernel_size=(3, 3), activation='relu', input_shape=(28,28,1)))


model.add(MaxPool2D(pool_size=(2, 2), strides=2))

model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu', padding = 'same'))


model.add(MaxPool2D(pool_size=(2, 2), strides=2))

model.add(Conv2D(filters=128, kernel_size=(3, 3), activation='relu', padding = 'valid'))


model.add(MaxPool2D(pool_size=(2, 2), strides=2))

model.add(Flatten())

model.add(Dense(64,activation ="relu"))
model.add(Dense(128,activation ="relu"))

model.add(Dense(26,activation ="softmax"))

model.compile(optimizer = Adam(learning_rate=0.001), loss='categorical_crossentropy',


metrics=['accuracy'])

28
18CSC305JARTIFICIAL INTELLIGENCE

reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=1, min_lr=0.0001)


early_stop = EarlyStopping(monitor='val_loss', min_delta=0, patience=2, verbose=0,
mode='auto')

history = model.fit(train_X, train_yOHE, epochs=1, callbacks=[reduce_lr, early_stop],


validation_data = (test_X,test_yOHE))

model.summary()
model.save(r'model_hand.h5')

# Displaying the accuracies & losses for train & validation set...

print("The validation accuracy is :", history.history['val_accuracy'])


print("The training accuracy is :", history.history['accuracy'])
print("The validation loss is :", history.history['val_loss'])
print("The training loss is :", history.history['loss'])

#Making model predictions...

pred = model.predict(test_X[:9])
print(test_X.shape)

# Displaying some of the test images & their predicted labels...

fig, axes = plt.subplots(3,3, figsize=(8,9))


axes = axes.flatten()

for i,ax in enumerate(axes):


img = np.reshape(test_X[i], (28,28))
ax.imshow(img, cmap="Greys")
pred = word_dict[np.argmax(test_yOHE[i])]
ax.set_title("Prediction: "+pred)
ax.grid()

# Prediction on external image...

img = cv2.imread(r'C:\Users\abhij\Downloads\img_b.jpg')
img_copy = img.copy()

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)


img = cv2.resize(img, (400,440))

img_copy = cv2.GaussianBlur(img_copy, (7,7), 0)

29
18CSC305JARTIFICIAL INTELLIGENCE

img_gray = cv2.cvtColor(img_copy, cv2.COLOR_BGR2GRAY)


_, img_thresh = cv2.threshold(img_gray, 100, 255, cv2.THRESH_BINARY_INV)

img_final = cv2.resize(img_thresh, (28,28))


img_final =np.reshape(img_final, (1,28,28,1))

img_pred = word_dict[np.argmax(model.predict(img_final))]

cv2.putText(img, "Dataflair _ _ _ ", (20,25), cv2.FONT_HERSHEY_TRIPLEX, 0.7, color =


(0,0,230))
cv2.putText(img, "Prediction: " + img_pred, (20,410), cv2.FONT_HERSHEY_DUPLEX,
1.3, color = (255,0,30))
cv2.imshow('Dataflair handwritten character recognition _ _ _ ', img)

while (1):
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
cv2.destroyAllWindows()

OUTPUT:

30
18CSC305JARTIFICIAL INTELLIGENCE

31
18CSC305JARTIFICIAL INTELLIGENCE

32
18CSC305JARTIFICIAL INTELLIGENCE

RESULT:
Thus, the Program to implement deep learning method for Automatic Handwriting
Recognition is executed and verified successfully.

33

You might also like