Ai Manual
Ai Manual
Ai Manual
Artificial Intelligence
(3161608)
B.E. Semester 6
(Information Technology)
Certificate
Place:
Date:
1
Artificial Intelligence (3161608) Karan vaghela | 210130116068
2
Artificial Intelligence (3161608) Karan vaghela | 210130116068
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
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.
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
7
Artificial Intelligence (3161608) Karan vaghela | 210130116068
Index
(Progressive Assessment Sheet)
8
Artificial Intelligence (3161608) Karan vaghela | 210130116068
9
Artificial Intelligence (3161608) Karan vaghela | 210130116068
Experiment: 01
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):
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)]
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 ?
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
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
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
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
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
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
Program:
capacity_jug1(4).
capacity_jug2(3).
goal(2).
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 get_available_moves(board):
return [i for i, x in enumerate(board) if x == " "]
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
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()
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:
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
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
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.save('mnist_binary_classification.h5')
Output:
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
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)
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
Output:
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
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:
% Example query to move 3 disks from peg A to peg C using peg B as auxiliary
% ?- move(3, 'A', 'C', 'B').
Output:
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