AI MANUAL

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

A Laboratory Manual for

Artificial Intelligence
(3161608)

B.E. Semester 6
(Information Technology)

Directorate of Technical Education,


Gandhinagar,Gujarat
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Government Engineering College, Gandhinagar


Department of Information Technology

Certificate

This is to certify that Mr. /Ms. Karan Vaghela


Enrollment No.210130116068 of B.E. Semester 6th Information Technology
of this Institute (GTU Code: 016) has satisfactorily completed the Practical /
Tutorial work for the subject Artificial Intelligence (3161608)for the
academic year 2023-24.

Place:
Date:

Name and Sign of Faculty member

Head of the Department

1
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Programme Outcomes (POs)

1. Engineering knowledge: Apply the knowledge of mathematics, science, engineering


fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2. Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
3. Design/development of solutions: Design solutions for complex engineering problems
and design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and
environmental considerations.
4. Conduct investigations of complex problems: Use research-based knowledge and
research methods including design of experiments, analysis and interpretation of data, and
synthesis of the information to provide valid conclusions.
5. Modern tool usage: Create, select, and apply appropriate techniques, resources, and
modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
6. The engineer and society: Apply reasoning informed by the contextual knowledge to
assess societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7. Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and
need for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9. Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and
write effective reports and design documentation, make effective presentations, and give
and receive clear instructions.
11. Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.
12. Life-long learning: Recognize the need for, and have the preparation and ability to
engage in independent and life-long learning in the broadest context of technological
change.

2
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Program Specific Outcomes (PSOs)

▪ Sound knowledge of fundamentals of computer science and engineering including


software and hardware.
▪ Develop the software using sound software engineering principles having web
based/mobile based interface.
▪ Use various tools and technology supporting modern software frameworks for solving
problems having large volume of data in the domain of data science and machine learning.

Program Educational Objectives (PEOs)

▪ Possess technical competence in solving real life problems related to Computing.


▪ Acquire good analysis, design, development, implementation and testing skills to
formulate simple computing solutions to the business and societal needs.
▪ Provide requisite skills to pursue entrepreneurship, higher studies, research, and
development and imbibe high degree of professionalism in the fields of computing.
▪ Embrace life-long learning and remain continuously employable.

▪ Work and excel in a highly competence supportive, multicultural and professional


environment which abiding to the legal and ethical responsibilities

3
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Preface

Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant
competencies in psychomotor domain. By keeping in view, GTU has designed competency
focused outcome- based curriculum for engineering degree programs where sufficient
weightage is given to practical work. It shows importance of enhancement of skills amongst the
students and it pays attention to utilize every second of time allotted for practical amongst
students, instructors and faculty members to achieve relevant outcomes by performing the
experiments rather than having merely study type experiments. It is must for effective
implementation of competency focused outcome-based curriculum that every practical is keenly
designed to serve as a tool to develop and enhance relevant competency required by the various
industry among every student. These psychomotor skills are very difficult to develop through
traditional chalk and board content delivery method in the classroom. Accordingly, this lab
manual is designed to focus on the industry defined relevant outcomes, rather than old practice
of conducting practical to prove concept and theory.

By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each
experiment in this manual begins with competency, industry relevant skills, course outcomes as
well as practical outcomes (objectives). The students will also achieve safety and necessary
precautions to be taken while performing practical.

This manual also provides guidelines to faculty members to facilitate student centric lab
activities through each experiment by arranging and managing necessary resources in order that
the students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.

Artificial Intelligence (AI) has become an integral part of many industries and fields, impacting
human life in numerous ways. AI techniques, such as Predicate Logic, Production Rules, and
Semantic Networks, are used to encode knowledge in computer systems and solve real-world
problems. Additionally, fields of AI like Game Playing, Natural Language Processing, and
Connectionist Models play a vital role in various industries. It is essential for students to learn
programming languages for AI as it is used in both technical and non-technical fields. AI has
been implemented in every branch of engineering, making systems more effective and dynamic.
The Fundamentals of Artificial Intelligence course aims to provide exposure to the basic AI
techniques.

Utmost care has been taken while preparing this lab manual however there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal
of errors if any

4
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Practical – Course Outcome matrix

S
Objective(s) of Experiment CO1 CO CO CO4
r. 2 3
N
o.
A. Write a prolog program to put facts
indicating that sachin likes cricket, saurav
likes cricket, raj likes football, karan likes
basketball, indra likes chess and add rule that
parth likes whatever saurav likes. Write goal
for following queries:
a. Find the name of all players who like
cricket.
b. Check whether raj likes cricket or not.
1. c. Display the list of all players with the
game they like.
d. Display the name of players who likes
any game except cricket.
B. Implement prolog program that asks
username and password from user and
display whether login is successful or not
according to knowledge base considered in
the program.
a. Perform above program without
recursion.
b. Perform above program with recursion.
Implement following prolog programs.:
a. To find the greatest variable among the
three variables.
2. b. To find a factorial of a given number.
c. To check whether a given number is
palindrome or not.
d. To check whether a given number is prime
or not.
Solve 8 Puzzle Problem using A* Algorithm in any
3. programming Language.

Implement following prolog programs based


on list.
a. To display first element of a list.
b. To display last element of a list.
4. c. To display all element of a list
d. To display elements up to specified index
of a list.
e. To count number of elements in a list.
f. To count odd and even elements of a list
Write a prolog program to solve water jug problem.
5.

5
Artificial Intelligence (3161608) Karan vaghela | 210130116068
Implement the Minimax algorithm for a simple tic-
6.
tac- toe game using Python Language.

6
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Implement Bayesian Networks algorithm for the


7. Monty Hall Problem using any
programming Language.
8. Demonstrate Connectionist Model using Tool.
Implement Genetic Algorithm using any
9.
programming Language.
Write a prolog program to solve Tower of Hanoi
10.
problem.

7
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Index
(Progressive Assessment Sheet)

Sr Objective(s) of Experiment Page Date Sign. of


.
N
No. Teacher
o.
A. Write a prolog program to put facts indicating
that sachin likes cricket, saurav likes cricket, raj
likes football, karan likes basketball, indra likes
chess and add rule that parth likes whatever saurav
likes. Write goal for following queries:
a. Find the name of all players who like cricket.
b. Check whether raj likes cricket or not.
c. Display the list of all players with the game
they like.
d. Display the name of players who likes any
game except cricket.
1.
B. Implement prolog program that asks username
and password from user and display whether login
is successful or not according to knowledge base
considered in the program.
a. Perform above program without recursion.
b. Perform above program with
recursion.

Implement following prolog programs.:


a. To find the greatest variable among the three
variables.
2. b. To find a factorial of a given number.
c. To check whether a given number is palindrome
or not.
d. To check whether a given number is
prime or not.
Solve 8 Puzzle Problem using A* Algorithm in any
3. programming Language.

Implement following prolog programs based on list.


a. To display first element of a list.
b. To display last element of a list.
4. c. To display all element of a list
d. To display elements up to specified index of a
list.
e. To count number of elements in a list.

8
Artificial Intelligence (3161608) Karan vaghela | 210130116068

f. To count odd and even elements of a


list
Write a prolog program to solve water jug problem.
5.
Implement the Minimax algorithm for a simple
6.
tic-tac-toe game using Python Language.
Implement Bayesian Networks algorithm for
7. the Monty Hall Problem using any
programming Language.
Demonstrate Connectionist Model using Tool.
8.
Implement Genetic Algorithm using
9.
any programming Language.
Write a prolog program to solve Tower of
10.
Hanoi problem.

9
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 01

AIM :- Implement following prolog programs:


A. Write a prolog program to put facts indicating that sachin likes cricket, saurav likes cricket,
raj likes football, karan likes basketball, indra likes chess and add the rule that parth likes
whatever saurav likes. Write goal for following queries:
a. Find the name of all players who like cricket.
b. Check whether raj likes cricket or not.
c. Display the list of all players with the game they like.
d. Display the name of players who like any game except cricket.
B. Implement a prolog program that asks username and password from the user and displays
whether login is successful or not according to the knowledge base considered in the
program.
a. Perform above program without recursion.
b. Perform above program with recursion.

Program:

Code: (A)

% Facts
likes(sachin, cricket). % sachin likes cricket
likes(saurav, cricket). % saurav likes cricket
likes(raj, football). % raj likes football
likes(karan, basketball). % karan likes basketball
likes(indra, chess). % indra likes chess
% Rules
likes(parth, X) :- likes(saurav, X). % parth likes whatever saurav likes

Code: (B)
(a)
% knowledge base
login(srijyaa, 123).
login(ayushi, 456).
login(abc, 123).
login(xyz, 456).

start:-
write('Enter Username: '), read(Username), write('Enter Password: '), read(Password), login(Username, Password),
write('Login Successful').

start:-
write('Login Unsuccessful')
(b)
% knowledge base
login(srijyaa, 123).
login(ayushi, 456).
login(abc, 123).
login(xyz, 456).
start:-
10
Artificial Intelligence (3161608) Karan vaghela | 210130116068
write('Enter Username: '), read(Username), write('Enter Password: '), read(Password), login(Username, Password),
write('Login Successful').
start:-
write('Login Unsuccessful'), nl, write('Try again..'), nl, start.

Output

Output 1-(a):

| ?- findall(X, likes(X, cricket), List).

List = [sachin,saurav,parth]

yes
| ?- likes(raj, cricket).

no
| ?- findall((X, Y), likes(X, Y), List).

List = [(sachin,cricket),(saurav,cricket),(raj,football),(karan,basketball),(indra,chess),
(parth,cricket)]

(16 ms) yes


| ?- findall(X, (likes(X, Y), \+ Y = cricket), List).

List = [raj,karan,indra]

yes

11
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Output 1B:

| ?- start.
Enter Username: ayushi.
Enter Password: 123.
Login Unsuccessful
Try again..
Enter Username: ayushi.
Enter Password: 456.
Login Successful

true ?

(125 ms) yes

Conclusion:
Prolog is a useful tool for implementing knowledge bases for various domains, including family
relationships, and can provide efficient and effective reasoning capabilities for querying and analyzing
such data.

12
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 02

AIM :- Implement following prolog programs:


A. To find the greatest variable among the three variables.
B. To find a factorial of a given number.
C. To check whether a given number is palindrome or not.
D. To check whether a given number is prime or not.

Program:

Program A:
greatest(X, Y, Z, G) :- X >= Y, X >= Z, G = X.
greatest(X, Y, Z, G) :- Y >= X, Y >= Z, G = Y.
greatest(X, Y, Z, G) :- Z >= X, Z >= Y, G = Z.

Output:
| ?- greatest(5,10,2,G).
G = 10 ?
yes

Program B:
factorial(0, 1).
factorial(N, F) :-
N > 0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.

Output:
| ?- factorial(6,F).
F = 720 ?
yes

Program C:
palindrome(Number) :-
number_chars(Number, Digits),
reverse(Digits, Reversed),
Digits = Reversed.

Output:
| ?- palindrome(256).
no
| ?- palindrome(121).
yes

Program D:
is_prime(2).
is_prime(3).
is_prime(P) :-
13
Artificial Intelligence (3161608) Karan vaghela | 210130116068
integer(P),
P > 3,
P mod 2 =\= 0,
\+ has_factor(P,3).

has_factor(N,L) :-
N mod L =:= 0.
has_factor(N,L) :-
L * L < N,
L2 is L + 2,
has_factor(N,L2).

Output:
| ?- is_prime(4).
no

| ?- is_prime(3).
true ?
yes

Conclusion:
In conclusion, the practical exercises in Prolog demonstrate the language’s powerful capabilities for
knowledge representation and reasoning. By implementing programs to find the greatest variable among
three, calculate factorials, determine palindromes, and check for prime numbers, we can see how
Prolog’s declarative nature allows for concise and clear expression of logical relationships and
computations.

14
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 03

AIM - Solve 8 Puzzle Problem using A* Algorithm in any programming Language.

Procedure:
1. Define the starting and goal states of the puzzle.
2. Implement the A* algorithm, which uses the heuristic function to determine the best path to
reach the goal state.

Program:

import heapq

class PuzzleState:
def __init__(self, state, parent, move, depth, cost, key):
self.state = state
self.parent = parent
self.move = move
self.depth = depth
self.cost = cost
self.key = key

def __lt__(self, other):


return self.cost < other.cost

def heuristic(state, goal):


"""Manhattan distance heuristic"""
distance = 0
for i in range(1, 9):
distance += abs(state.index(i) // 3 - goal.index(i) // 3) + abs(state.index(i) % 3 - goal.index(i) % 3)
return distance

def a_star(start, goal):


"""A* algorithm"""
open_list = []
closed_list = set()
key = tuple(start)
start_state = PuzzleState(start, None, None, 0, heuristic(start, goal), key)
heapq.heappush(open_list, start_state)

while open_list:
current_state = heapq.heappop(open_list)
closed_list.add(current_state.key)

if current_state.state == goal:
return current_state

moves = possible_moves(current_state.state)
for move in moves:
next_state = move_state(current_state.state, move)
key = tuple(next_state)

15
Artificial Intelligence (3161608) Karan vaghela | 210130116068
if key not in closed_list:
g_cost = current_state.depth + 1
h_cost = heuristic(next_state, goal)
next_puzzle_state = PuzzleState(next_state, current_state, move, g_cost, g_cost + h_cost, key)
heapq.heappush(open_list, next_puzzle_state)

return None

def possible_moves(state):
"""Returns a list of possible moves"""
moves = []
zero_index = state.index(0)
if zero_index not in [0, 1, 2]:
moves.append('Up')
if zero_index not in [0, 3, 6]:
moves.append('Left')
if zero_index not in [2, 5, 8]:
moves.append('Right')
if zero_index not in [6, 7, 8]:
moves.append('Down')
return moves

def move_state(state, move):


"""Moves the zero tile in the given direction"""
new_state = state[:]
zero_index = state.index(0)
if move == 'Up':
new_state[zero_index], new_state[zero_index-3] = new_state[zero_index-3], new_state[zero_index]
elif move == 'Down':
new_state[zero_index], new_state[zero_index+3] = new_state[zero_index+3], new_state[zero_index]
elif move == 'Left':
new_state[zero_index], new_state[zero_index-1] = new_state[zero_index-1], new_state[zero_index]
elif move == 'Right':
new_state[zero_index], new_state[zero_index+1] = new_state[zero_index+1], new_state[zero_index]
return new_state

start = [1, 2, 3, 7, 6, 4, 0, 8, 5]
goal = [1, 2, 3, 4, 5, 6, 7, 8, 0]
solution = a_star(start, goal)
moves = []
while solution.parent:
moves.append(solution.move)
solution = solution.parent
moves.reverse()
print(moves)

Output:

['Right', 'Up', 'Right', 'Down', 'Left', 'Left', 'Up', 'Right', 'Right', 'Down']

Conclusion:
The practical application of the A* algorithm to the 8 Puzzle Problem showcases its efficiency in
16
Artificial Intelligence (3161608) Karan vaghela | 210130116068
pathfinding and puzzle-solving. It highlights the algorithm’s ability to find the most cost-effective route
to the goal state. This exercise demonstrates the practicality of A* in solving complex problems with a
heuristic approach.

17
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 04

AIM :- Implement following prolog programs based on list.


A. To display first element of a list.
B. To display last element of a list.
C. To display all element of a list
D. To display elements up to specified index of a list.
E. To count number of elements in a list.
F. To count odd and even elements of a list.

Program:

Program (A):
first_element([H|_], H).

Output:
| ?- first_element([a,b,c,d],F).
F=a
yes

Program (B):
last_element([H], H).
last_element([_|T], H) :- last_element(T, H).

Output:
| ?- last_element([a,b,c,d],L).
L=d?
yes

Program (C):
display_all([]).
display_all([H|T]) :-
write(H), nl,
display_all(T).

Output:
| ?- display_all([a,b,c,d]).
a
b
c
d

yes

18
Artificial Intelligence (3161608) Karan vaghela | 210130116068
Program (D):
display_upto_index(List, Index) :-
display_upto_index_helper(List, Index, 1).

display_upto_index_helper([], _, _).
display_upto_index_helper([H|_], Index, Index) :- write(H), nl.
display_upto_index_helper([H|T], Index, Count) :-
Count < Index,
write(H), nl,
NewCount is Count + 1,
display_upto_index_helper(T, Index, NewCount).

Output:
| ?- display_upto_index([a,b,c,d,e,f],3).
a
b
c

true ?

yes

Program (E):
count_elements([], 0).
count_elements([_|T], Count) :-
count_elements(T, TempCount),
Count is TempCount + 1.

Output:
| ?- count_elements([a,b,c,d,e], Count).
Count = 5
yes

Program (F):
count_odd_even([], 0, 0).
count_odd_even([H|T], OddCount, EvenCount) :-
0 is H mod 2,
count_odd_even(T, OddCount, TempEvenCount),
EvenCount is TempEvenCount + 1.
count_odd_even([H|T], OddCount, EvenCount) :-
1 is H mod 2,
count_odd_even(T, TempOddCount, EvenCount),
OddCount is TempOddCount + 1.

Output:
| ?- count_odd_even([1,4,2], OddCount, EvenCount).

19
Artificial Intelligence (3161608) Karan vaghela | 210130116068
EvenCount = 2
OddCount = 1 ?
yes

Conclusion:
The Prolog list manipulation practical encapsulates the language's adeptness at handling data structures,
showcasing its ability to perform fundamental operations on lists. It highlights Prolog's declarative
paradigm through concise solutions for element retrieval and enumeration. This exercise underlines the
utility of Prolog in processing and analyzing sequence-based data efficiently.

20
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 05

Aim :- Write a prolog program to solve the water jug problem.

Program:

capacity_jug1(4).
capacity_jug2(3).
goal(2).

move([_, WJ2], [NWJ1, WJ2]):-


capacity_jug1(NWJ1).

move([WJ1, _], [WJ1, NWJ2]):-


capacity_jug2(NWJ2).

move([_, WJ2], [0, WJ2]).

move([WJ1, _], [WJ1, 0]).

move([WJ1, WJ2], [NWJ1, NWJ2]):-


capacity_jug2(CapacityJug2),
Transfer is min(WJ1, CapacityJug2 - WJ2),
NWJ1 is WJ1 - Transfer,
NWJ2 is WJ2 + Transfer.

move([WJ1, WJ2], [NWJ1, NWJ2]):-


capacity_jug1(CapacityJug1),

Transfer is min(WJ2, CapacityJug1 - WJ1),


NWJ1 is WJ1 + Transfer,
NWJ2 is WJ2 - Transfer.

solve_dfs(Path, [Jug1, Jug2]):-


goal(Goal),
(Jug1 = Goal; Jug2 = Goal),
!,
write('Solution Path: '), nl,
print_path(Path).

solve_dfs(Path, State):-
move(State, NextState),
\+ member(NextState, Path), % Avoid loops
solve_dfs([NextState|Path], NextState).

print_path([]).
print_path([[J1, J2]|RestPath]) :-
print_path(RestPath),
write('Jug1: '), write(J1),
write(' Jug2: '), write(J2), nl.

start:-
solve_dfs([], [0, 0]).

21
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Output:
| ?- start.
Solution Path:
Jug1: 4 Jug2: 0
Jug1: 4 Jug2: 3
Jug1: 0 Jug2: 3
Jug1: 3 Jug2: 0
Jug1: 3 Jug2: 3
Jug1: 4 Jug2: 2

T true

Conclusion:
The Prolog program for the water jug problem illustrates the language’s strength in solving algorithmic
puzzles through logical deduction. It demonstrates Prolog’s suitability for state-space search problems.
This practical serves as a testament to Prolog’s capability to model and solve classic artificial
intelligence challenges effectively.

22
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 06

Aim:- Implement the Minimax algorithm for a simple tic-tac-toe game using Python Language.

Program:

import random

def is_winner(board, player):


win_conditions = [(0, 1, 2), (3, 4, 5), (6, 7, 8),
(0, 3, 6), (1, 4, 7), (2, 5, 8),
(0, 4, 8), (2, 4, 6)]
for condition in win_conditions:
if board[condition[0]] == board[condition[1]] == board[condition[2]] == player:
return True
return False

def get_available_moves(board):
return [i for i, x in enumerate(board) if x == " "]

def minimax(board, depth, is_maximizing):


if is_winner(board, "X"):
return -10 + depth
if is_winner(board, "O"):
return 10 - depth
if len(get_available_moves(board)) == 0:
return 0

if is_maximizing:
max_eval = float("-inf")
for move in get_available_moves(board):
board[move] = "O"
eval = minimax(board, depth + 1, False)
board[move] = " "
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float("inf")
for move in get_available_moves(board):
board[move] = "X"
eval = minimax(board, depth + 1, True)
board[move] = " "
min_eval = min(min_eval, eval)
return min_eval

def best_move(board, player):


best_score = float("-inf") if player == "O" else float("inf")
best_move = -1
for move in get_available_moves(board):
board[move] = player
score = minimax(board, 0, player == "X")
board[move] = " "
if player == "O":
if score > best_score:

23
Artificial Intelligence (3161608) Karan vaghela | 210130116068
best_score = score
best_move = move
else:
if score < best_score:
best_score = score
best_move = move
return best_move

def play_game():
board = [" ", " ", " ",
" ", " ", " ",
" ", " ", " "]
current_player = "X" if random.randint(0, 1) == 0 else "O"
while True:
move = best_move(board, current_player)
board[move] = current_player
print_board(board)
if is_winner(board, current_player):
print(f"Player {current_player} wins!")
break

if len(get_available_moves(board)) == 0:
print("It's a tie!")
break
current_player = "O" if current_player == "X" else "X"

def print_board(board):
print(f"{board[0]} | {board[1]} | {board[2]}")
print("---------")
print(f"{board[3]} | {board[4]} | {board[5]}")
print("---------")
print(f"{board[6]} | {board[7]} | {board[8]}")
print()

# Start the game


play_game()

Output:

X| |
---------
| |
---------
| |

X| |
---------
|O|
---------
| |

24
Artificial Intelligence (3161608) Karan vaghela | 210130116068
X|X|
---------
|O|
---------
| |

X|X|O
---------
|O|
---------
| |

X|X|O
---------
|O|
---------
X| |

X|X|O
---------
O|O|
---------
X| |

X|X|O
---------
O|O|X
---------
X| |

X|X|O
---------
O|O|X
---------
X|O|

X|X|O
---------
O|O|X
---------
X|O|X

25
Artificial Intelligence (3161608) Karan vaghela | 210130116068
It's a tie!

Conclusion:
The practical implementation of the Minimax algorithm in a Python-based tic-tac-toe game exemplifies
its strategic decision-making prowess. It underscores Python's versatility for algorithmic programming
and AI development. This exercise effectively demonstrates the Minimax algorithm's ability to
anticipate opponent moves and optimize gameplay.

26
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 07

Aim :- Implement Bayesian Networks algorithm for the Monty Hall Problem using any
programming Language.

Procedure:
● Define an evaluation function to evaluate the game state and return a score.
● Define a recursive function to search for the best move using the Minimax algorithm.
● Create a function to get the best move for the current player.

Program:

from pgmpy.models import BayesianModel


from pgmpy.factors.discrete import TabularCPD
from pgmpy.inference import VariableElimination

model = BayesianModel([('Player', 'Host'), ('Prize', 'Host')])

cpd_player = TabularCPD(variable='Player', variable_card=3, values=[[1/3], [1/3], [1/3]])


cpd_prize = TabularCPD(variable='Prize', variable_card=3, values=[[1/3], [1/3], [1/3]])

cpd_host = TabularCPD(variable='Host', variable_card=3,


values=[[0, 0, 0, 1/2, 0, 1, 1/2, 1, 0],
[1/2, 1/2, 1, 0, 1/2, 0, 0, 0, 1/2],
[1/2, 1/2, 0, 1/2, 1/2, 0, 1/2, 0, 1/2]],
evidence=['Player', 'Prize'],
evidence_card=[3, 3])

model.add_cpds(cpd_player, cpd_prize, cpd_host)

inference = VariableElimination(model)

# Assuming the player initially chooses door 0, and the host opens door 1
result = inference.query(variables=['Prize'], evidence={'Player': 0, 'Host': 1})

print(result)

27
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Output:

+----------+--------------+
| Prize | phi(Prize) |
+==========+==============+
| Prize(0) | 0.2500 |
+----------+--------------+
| Prize(1) | 0.2500 |
+----------+--------------+
| Prize(2) | 0.5000 |
+----------+--------------+

Conclusion:
The implementation of Bayesian Networks for the Monty Hall Problem in a programming language
demonstrates the algorithm's effectiveness in probabilistic reasoning. It highlights the practical use of
Bayesian inference in decision-making scenarios. This exercise validates the algorithm's utility in
unraveling complex problems with uncertainty.

28
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 08

Aim :- Demonstrate Connectionist Model using tool.

Procedure:
1. Choose a connectionist modeling tool
2. Define the problem
3. Design the architecture of the
4. Implement the model
5. Test the model
6. Deploy the model

Program:

import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical

(x_train, y_train), (x_test, y_test) = mnist.load_data()

train_filter = np.where((y_train == 0 ) | (y_train == 1))


test_filter = np.where((y_test == 0) | (y_test == 1))
x_train, y_train = x_train[train_filter], y_train[train_filter]
x_test, y_test = x_test[test_filter], y_test[test_filter]

x_train = x_train.reshape(x_train.shape[0], -1) / 255.0


x_test = x_test.reshape(x_test.shape[0], -1) / 255.0

y_train = to_categorical(y_train)
y_test = to_categorical(y_test)

model = Sequential()
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dense(512, activation='relu'))
model.add(Dense(2, activation='softmax'))

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])

model.fit(x_train, y_train, epochs=10, validation_data=(x_test, y_test))

test_loss, test_acc = model.evaluate(x_test, y_test)

print('Test accuracy:', test_acc)

model.save('mnist_binary_classification.h5')

Output:

Downloading data from https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz

29
Artificial Intelligence (3161608) Karan vaghela | 210130116068
11490434/11490434 [==============================] - 0s 0us/step
Epoch 1/10
396/396 [==============================] - 20s 39ms/step - loss: 0.0112 - accuracy: 0.9964 - val_loss: 0.0027 -
val_accuracy: 0.9981
Epoch 2/10
396/396 [==============================] - 7s 18ms/step - loss: 0.0046 - accuracy: 0.9991 - val_loss: 0.0017 -
val_accuracy: 0.9995
Epoch 3/10
396/396 [==============================] - 5s 13ms/step - loss: 8.9771e-04 - accuracy: 0.9997 - val_loss:
1.8584e-04 - val_accuracy: 1.0000
Epoch 4/10
396/396 [==============================] - 4s 11ms/step - loss: 0.0021 - accuracy: 0.9992 - val_loss: 0.0044 -
val_accuracy: 0.9995
Epoch 5/10
396/396 [==============================] - 4s 11ms/step - loss: 4.3942e-04 - accuracy: 0.9998 - val_loss: 0.0023 -
val_accuracy: 0.9995
Epoch 6/10
396/396 [==============================] - 5s 13ms/step - loss: 4.6901e-05 - accuracy: 1.0000 - val_loss:
1.7359e-04 - val_accuracy: 1.0000
Epoch 7/10
396/396 [==============================] - 4s 11ms/step - loss: 2.9806e-06 - accuracy: 1.0000 - val_loss:
1.6002e-04 - val_accuracy: 1.0000
Epoch 8/10
396/396 [==============================] - 4s 11ms/step - loss: 9.6494e-07 - accuracy: 1.0000 - val_loss:
1.0489e-04 - val_accuracy: 1.0000
Epoch 9/10
396/396 [==============================] - 5s 13ms/step - loss: 6.8068e-07 - accuracy: 1.0000 - val_loss:
1.1432e-04 - val_accuracy: 1.0000
Epoch 10/10
396/396 [==============================] - 4s 11ms/step - loss: 4.9739e-07 - accuracy: 1.0000 - val_loss:
1.0760e-04 - val_accuracy: 1.0000
67/67 [==============================] - 0s 4ms/step - loss: 1.0760e-04 - accuracy: 1.0000
Test accuracy: 1.0
/usr/local/lib/python3.10/dist-packages/keras/src/engine/training.py:3103: UserWarning: You are saving your model as an
HDF5 file via `model.save()`. This file format is considered legacy. We recommend using instead the native Keras format,
e.g. `model.save('my_model.keras')`.
saving_api.save_model

Conclusion:
The practical exploration of connectionist models, particularly neural networks, underscores their
robustness in simulating cognitive processes through unit interconnectivity and weight adjustments. It
highlights the adaptability of neural networks in representing complex mental states and forming
memories. This exercise reaffirms the significance of neural networks in modern AI applications,
facilitated by tools like TensorFlow and PyTorch.

30
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 09

Aim :- Implement Genetic Algorithm in any Programming Language.

Procedure:
1. Define the problem
2. Define the representation
3. Initialize the population.
4. Evaluate the fitness
5. Select parents.
6. Create offspring: Use genetic operators such as crossover and mutation to create offspring from
the selected parents.
7. Evaluate the offspring.
8. Select survivor
9. Check stopping criteria

Program:

import numpy as np

# Define the problem: Maximize the equation y = w1x1 + w2x2 + ... + w6x6
def fitness_function(weights):
x = np.array([4, -2, 3.5, 5, -11, -4.7]) # Example coefficients
return np.sum(weights * x)

# Define the representation: Weights as real numbers


def initialize_population(size, dimensions):
return np.random.uniform(low=-5.0, high=5.0, size=(size, dimensions))

# Evaluate the fitness


def evaluate_population(population):
return np.array([fitness_function(individual) for individual in population])

# Select parents: Tournament selection


def select_parents(population, fitness, num_parents):
parents = np.empty((num_parents, population.shape[1]))
for i in range(num_parents):
max_fitness_idx = np.where(fitness == np.max(fitness))
parents[i, :] = population[max_fitness_idx[0][0], :]
fitness[max_fitness_idx[0][0]] = -99999999999 # Exclude this index in future selections
return parents

# Create offspring: Crossover and mutation


def crossover_and_mutation(parents, offspring_size):
offspring = np.empty(offspring_size)
crossover_point = np.uint8(offspring_size[1]/2)

for k in range(offspring_size[0]):
parent1_idx = k % parents.shape[0]
parent2_idx = (k + 1) % parents.shape[0]
offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]
offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]
# Mutation
mutation_value = np.random.uniform(-1.0, 1.0, 1)
31
Artificial Intelligence (3161608) Karan vaghela | 210130116068
offspring[k, np.random.randint(0, offspring_size[1])] += mutation_value
return offspring

# Genetic Algorithm flow


num_generations = 100 # Increase the number of generations
population_size = 50 # Increase the population size
num_parents_mating = 10 # Increase the number of parents mating
num_weights = 6

population = initialize_population(population_size, num_weights)

for generation in range(num_generations):


fitness = evaluate_population(population)
parents = select_parents(population, fitness, num_parents_mating)
offspring_crossover = crossover_and_mutation(parents, (population_size - parents.shape[0], num_weights))
population[0:parents.shape[0], :] = parents
population[parents.shape[0]:, :] = offspring_crossover
# Elitism: Ensure the best individual is carried over
best_individual = population[np.argmax(fitness)]
population[-1] = best_individual

# Best solution after all generations


fitness = evaluate_population(population) # Re-evaluate the final population
best_fitness = np.max(fitness)
best_index = np.where(fitness == best_fitness)[0][0]
best_solution = population[best_index, :]

print("Best solution: ", best_solution)


print("Best solution fitness: ", best_fitness)

Output:

Best solution: [ 19.39421566 -11.98380586 18.02676166 13.01429456 -40.27817773


-9.54307338]
Best solution fitness: 717.6220128489646

Conclusion:
The practical application of Genetic Algorithms (GA) demonstrates their power in optimization,
mimicking natural selection to evolve solutions. It highlights GA's ability to navigate complex problem
spaces where traditional methods falter. This exercise validates GA as a versatile tool in AI for finding
optimal solutions in diverse scenarios.

32
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Experiment: 10

Aim :- Write a prolog program to solve Tower of Hanoi problem.

The Tower of Hanoi is a classic mathematical puzzle that was invented by the French mathematician
Édouard Lucas in 1883. It consists of three pegs and a number of disks of different sizes, which can be
slid onto any peg. The puzzle's objective is to move the entire stack of disks from one peg to another,
subject to the following rules:
● Pegs: There are three pegs: A, B, and C.
● Initial Configuration: The puzzle begins with all the disks stacked in decreasing order of size
on one peg, typically peg A. The smallest disk is on top, and the largest disk is at the bottom.
● Goal Configuration: The goal is to move the entire stack of disks to another peg, typically peg
● C. The disks should be stacked in the same order (smallest on top, largest on the bottom) on the
destination peg.
● Intermediate Peg: You can use peg B as an intermediate peg to move the disks. This means that
you can only move one disk at a time from the top of one peg to the top of another peg.
● Larger Disk on Top: A disk can never be placed on top of a smaller disk.

Program:

% move(+NumDisks, +SourcePeg, +TargetPeg, +AuxiliaryPeg)


move(1, Source, Target, _) :-
write('Move top disk from '),
write(Source),
write(' to '),
write(Target),
nl.

move(NumDisks, Source, Target, Auxiliary) :-


NumDisks > 1,
M is NumDisks - 1,
move(M, Source, Auxiliary, Target),
move(1, Source, Target, _),
move(M, Auxiliary, Target, Source).

% Example query to move 3 disks from peg A to peg C using peg B as auxiliary
% ?- move(3, 'A', 'C', 'B').

Output:

| ?- move(3, 'A', 'C', 'B').


Move top disk from A to C
Move top disk from A to B
Move top disk from C to B
Move top disk from A to C
Move top disk from B to A
Move top disk from B to C
Move top disk from A to C

true ?

33
Artificial Intelligence (3161608) Karan vaghela | 210130116068

Conclusion:
The Prolog solution to the Tower of Hanoi problem exemplifies the language's recursive problem-
solving capabilities. It demonstrates Prolog's strength in implementing algorithms that require
backtracking and state-space exploration. This practical reinforces Prolog's applicability in educational
and computational logic settings.

34

You might also like