Ai Record Final
Ai Record Final
AIM:
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'.
Code:
theBoard = {'7': ' ' , '8': ' ' , '9': ' ' ,
'4': ' ' , '5': ' ' , '6': ' ' ,
'1': ' ' , '2': ' ' , '3': ' ' }
board_keys = []
''' 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()
# 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
# 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!!")
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.
4
18CSC305JARTIFICIAL INTELLIGENCE
EX.NO: 2 PROBLEMS
AIM:
ALGORITHIM:
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.
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:
self.variables = variables
@abstractmethod
5
18CSC305JARTIFICIAL INTELLIGENCE
...
Self. Domains: Duct [V, List [D]] = domains # domain of each variable
else:
self.constraints[variable].append(constraint)
if not constraint.satisfied(assignment):
return False
return True
6
18CSC305JARTIFICIAL INTELLIGENCE
if len(assignment) == len(self.variables):
return assignment
# get the every possible domain value of the first unassigned variable
first: V = unassigned[0]
local_assignment = assignment.copy()
local_assignment[first] = value
if self.consistent(first, local_assignment):
return result
COLOR_MAPPING.py:
super().__init__([place1, place2])
return True
if __name__ == "__main__":
csp.add_constraint(MapColoringConstraint("Victoria", "Tasmania"))
8
18CSC305JARTIFICIAL INTELLIGENCE
if solution is None:
else:
print(solution)
OUTPUT:
RESULT: Thus, the Program to colour code all territories in Australia has been implemented
successfully.
AIM:
ALGORITHIM:
1. Vector stores 1 corresponding to index number which is already assigned to any char, otherwise
stores 0.
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
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
13
18CSC305JARTIFICIAL INTELLIGENCE
EX.NO: 4 APPLICATION
AIM:
ALGORITHM:
DFS:
BFS:
Code:
graph = {
'A' : ['B','C'],
'B' : ['D', 'E'],
'C' : ['F'],
'D' : [],
'E' : ['F'],
'F' : []
}
while queue:
s = queue.pop(0)
print (s, end = " ")
14
18CSC305JARTIFICIAL INTELLIGENCE
visited.append(neighbour)
queue.append(neighbour)
# Driver Code
bfs(visited, graph, 'A')
OUTPUT:
15
18CSC305JARTIFICIAL INTELLIGENCE
# Driver Code
dfs(visited, graph, 'A')
OUTPUT:
RESULT: Thus, the Program to implement BFS and DFS is executed and verified successfully
AIM:
ALGORITHM:
16
18CSC305JARTIFICIAL INTELLIGENCE
2. Returns a list of tuples as a path from the given start to the given end
9. Generate children.
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
AIM:
To write a Program to implement minimax algorithm in Tic Tac Toe with Tkinter
ALGORITHM:
1. Import libraries.
3. Set the number of noughts and crosses in a row that is needed to win the game.
13. Check if the game has ended, break out from the loop in that case.
19
18CSC305JARTIFICIAL INTELLIGENCE
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.
22. Loop until we are outside the board or have moved the number of steps in the goal.
27. Set min value to max value if it is lower than current min value.
32. Set max value to min value if min value is greater than current max value.
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 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
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.
24
18CSC305JARTIFICIAL INTELLIGENCE
RESULT: Thus, the implementation of minmax algorithm is executed and verified successfully
AIM:
ALGORITHM:
Step 2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return False.
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
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 '(' in the first index and ')' in the last index
expr = expr[1:len(expr) - 1]
26
18CSC305JARTIFICIAL INTELLIGENCE
# List of arguments
arg_list = list()
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:])
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
arg_list = get_arg_list(expr)
if var in arg_list:
return True
27
18CSC305JARTIFICIAL INTELLIGENCE
return False
Step 2: If the initial Predicate symbol in Ψ1 and Ψ2 are not same, then return False.
# 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)'
29
18CSC305JARTIFICIAL INTELLIGENCE
OUTPUT:
RESULT: Thus the code for implementation of unification and resolution is executed and verified
successfully.
30
18CSC305JARTIFICIAL INTELLIGENCE
AIM:
ALGORITHM:
2. If there is any unassigned cell, then that function will change the values of row and col
accordingly.
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)
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
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
AIM:
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.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
numpy.random.seed(0)
numpy.set_printoptions(suppress=True)
4
18CSC305JARTIFICIAL INTELLIGENCE
# 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")
5
18CSC305JARTIFICIAL INTELLIGENCE
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
EX.NO: 10
AIM:
ALGORITHM:
3. Initially push the goal state as compound goal onto the stack
6. If Stack Top is Compound Goal, push its unsatisfied goals onto 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.
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
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
13
18CSC305JARTIFICIAL INTELLIGENCE
14
18CSC305JARTIFICIAL INTELLIGENCE
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.
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 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
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
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
19
18CSC305JARTIFICIAL INTELLIGENCE
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
OUTPUT:
● To build the classification model using the gradient boosting algorithm using
Boston Housing Dataset
Code:
boston = load_boston()
X = pd.DataFrame(boston.data, columns=boston.feature_names)
y = pd.Series(boston.target)
regressor = GradientBoostingRegressor(
max_depth=2,
n_estimators=3,
learning_rate=1.0
21
18CSC305JARTIFICIAL INTELLIGENCE
)
regressor.fit(X_train, y_train)
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)
# 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)
# 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
# Test model
predictions = clf.predict(X_test)
print('predicted', predictions)
# Is our model reliable?
24
18CSC305JARTIFICIAL INTELLIGENCE
print(confusion_matrix(y_test,predictions))
OUTPUT:
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:
26
18CSC305JARTIFICIAL INTELLIGENCE
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)
27
18CSC305JARTIFICIAL INTELLIGENCE
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)
# CNN model...
model = Sequential()
model.add(Flatten())
model.add(Dense(64,activation ="relu"))
model.add(Dense(128,activation ="relu"))
model.add(Dense(26,activation ="softmax"))
28
18CSC305JARTIFICIAL INTELLIGENCE
model.summary()
model.save(r'model_hand.h5')
# Displaying the accuracies & losses for train & validation set...
pred = model.predict(test_X[:9])
print(test_X.shape)
img = cv2.imread(r'C:\Users\abhij\Downloads\img_b.jpg')
img_copy = img.copy()
29
18CSC305JARTIFICIAL INTELLIGENCE
img_pred = word_dict[np.argmax(model.predict(img_final))]
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