Professional Documents
Culture Documents
Artificial Intelligence
(3170716)
B.E. Semester 7
(Computer Engineering)
Institute logo
Certificate
Place: __________
Date: __________
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 always there is chances of
improvement. Therefore, we welcome constructive suggestions for improvement and removal
of errors if any.
Index
Sr. No. Objective(s) of Experiment Page Date of Date of Assessme Sign. of Remar
No. perform submiss nt Teacher ks
ance ion Marks with date
Write a Prolog program which contains
three predicates: male, female, parent.
Make rules for following family
1.
relations: father, mother, grandfather,
grandmother, brother, sister, uncle, aunt,
nephew and niece.
Write a Prolog program to implement
2.
Water Jug Problem.
Solve 8 Puzzle Problem using A* Algorithm in
3.
any programming Language.
Convert the given Prolog predicates
into Semantic Net.
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
4. caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
Construct the Conceptual Dependency for
the given statements.
5.
1) John gives Mary a book
2) John gave Mary the book yesterday.
Implement the Minimax algorithm for a simple
6.
tic-tac-toe game using Python Language.
Implement Bayesian Networks
7. algorithm for the Monty Hall Problem
using any programming Language.
Demonstrate Connectionist Model using
8.
Tool.
Implement Genetic Algorithm using
9.
any programming Language.
10. Write a PROLOG program based on list:
1) To find the length of a list.
2) To sum all numbers of list.
3) To find whether given element is a
member of a list.
4) To append the list.
Write a PROLOG program which contains three predicates: male, female, parent. Make
rules for following family relations: father, mother, grandfather, grandmother, brother, sister,
uncle, aunt, nephew and niece.
Date:
Theory:
There are only three basic constructs in Prolog: facts, rules, and queries. A collection of facts and
rules is called a knowledge base (or a database) and Prolog programming is all about writing
knowledge bases. That is, Prolog programs simply are knowledge bases, collections of facts and
rules which describe some collection of relationships that we find interesting.
Knowledge Base 1
Knowledge Base 1 (KB1) is simply a collection of facts. Facts are used to state things that are
unconditionally true of some situation of interest. For example, we can state that Mia, Jody, and
Yolanda are women, that Jody plays air guitar, and that a party is taking place, using the following
five facts:
woman(mia).
woman (jody).
woman (yolanda).
playsAirGuitar(jody).
party.
?- woman (mia).
Prolog will answer
yes
Knowledge Base 2
happy (yolanda).
listens 2Music(mia).
listens 2Music(yolanda): - happy (yolanda). playsAirGuitar(mia):- listens2Music(mia).
playsAirGuitar(yolanda):- listens 2Music(yolanda).
There are two facts in KB2, listens2Music(mia) and happy(yolanda). The last three items it
contains are rules.
Rules state information that is conditionally true of the situation of interest The part on the left
hand side of the: - is called the head of the rule, the part on the right hand side is called the body.
G.E.C Dahod 4
Knowledge Base 3
Knowledge Base 4
There are no rules, only a collection of facts. we're going to make use of variables. Here's an
example:
?- woman(X).
Prolog answers this query by working its way through KB4, from top to bottom, trying to unify
(or match) the expression woman(X) with the information KB4 contains. Now the first item in the
knowledge base is woman(mia). So, Prolog unifies X with mia, thus making the query agree
perfectly with this first item. (Incidentally, there's a lot of different terminology for this process:
we can also say that Prolog instantiates X to mia, or that it binds X to mia .) Prolog then reports
back to us as follows:
X = mia
That is, it not only says that there is information about at least one woman in KB4, it actually tells
us who she is. It didn't just say yes, it actually gave us the variable binding (or variable
instantiation) that led to success.
G.E.C Dahod 5
Knowledge Base 5
person(john).
person(susan).
person(bob).
person(alice).
city(new_york).
city(london).
city(paris).
city(tokyo).
lives_in(john, new_york).
lives_in(susan, london).
lives_in(bob, paris).
lives_in(alice, tokyo).
likes(john, sushi).
likes(john, pizza).
likes(susan, pizza).
likes(bob, croissants).
likes(alice, sushi).
likes_same_food(X, Y) :-
likes(X, Z),
likes(Y, Z),
X \= Y.
In this example, we have defined a knowledge base that includes facts about people and cities, as
well as rules that define relationships between them. Specifically, we have defined the following:
Four facts that define the people in our knowledge base (john, susan, bob, and alice) and
the cities they live in (new_york, london, paris, and tokyo).
Five facts that define the food preferences of our people.
A rule called likes_same_food/2 that defines a relationship between two people who like
the same food.
To use this knowledge base, we can query it using Prolog's built-in ?- operator. For example, we
can ask:
?- likes(john, sushi).
true.
This will return true, indicating that John likes sushi.
G.E.C Dahod 6
Code:
male(bharat).
male(dilip).
male(revabhai).
male(dev).
male(jay).
female(nayana).
female(manisha).
female(sharadaben).
female(shreya).
parent(bharat,dev).
parent(bharat,shreya).
parent(nayana,shreya).
parent(nayana,dev).
parent(revabhai,bharat).
parent(revabhai,dilip).
parent(sharadaben,dilip).
parent(sharadaben,bharat).
parent(dilip,jay).
parent(manisha,jay).
father(X,Y):-parent(X,Y),male(X).
mother(X,Y):-parent(X,Y),female(X).
grandfather(X,Z):-male(X),parent(X,Y),parent(Y,Z).
grandmother(X,Z):-parent(X,Y),father(Y,Z),female(X).
brother(X,Y):-parent(Z,X),parent(Z,Y),male(X),X\==Y.
sister(X,Y):-parent(Z,X),parent(Z,Y),female(X),X\==Y.
nephew(X,Y):-male(X),brother(Z,Y),father(Z,X).
niece(X,Y):-female(X),brother(Z,Y),father(Z,X).
uncle(X,Y):-male(X),father(Z,Y),brother(X,Z).
aunt(X,Y):-female(X),father(K,Y),nephew(W,K),mother(X,W).
Output:
Conclusion:
G.E.C Dahod 7
Experiment No: 2
Date:
Objectives:To create a functional and efficient Prolog program for solving logic puzzles.
Theory:
The Water-Jug Problem is a classic problem in Artificial Intelligence that involves two jugs of
different sizes and the task of measuring a specific amount of water using these jugs. The problem
can be formulated as follows:
Given two jugs of sizes x and y, where x is greater than y, and an amount z of water to be
measured, the task is to find a sequence of steps to measure exactly z liters of water using only
these two jugs.
The problem can be solved using various AI algorithms such as Depth-First Search, Breadth-First
Search, or heuristic search algorithms like A* search. The Breadth-First Search algorithm is
commonly used to solve the Water-Jug Problem.
To solve the problem using Breadth-First Search, we start with the initial state where both jugs are
empty and generate all possible next states from this state by applying the allowed actions such as
filling a jug, emptying a jug, or pouring water from one jug to another. We then add these
generated states to a queue and continue generating states and adding them to the queue until we
find the desired goal state, which is when one of the jugs contains exactly z liters of water. Once
the goal state is reached, we backtrack to find the sequence of steps taken to reach the goal state.
State Representation and Initial State – we will represent a state of the problem as a tuple (x, y)
where x represents the amount of water in the 4-gallon jug and y represents the amount of water in
the 3-gallon jug.
Note 0 ≤ x ≤ 4, and 0 ≤ y ≤ 3.
Our initial state: (0,0)
Goal Predicate – state = (2,y) where 0 ≤ y ≤ 3.
Operators –
Fill the 4-gallon jug: This operator fills the 4-gallon jug to its maximum capacity. The
resulting state will be (4, y), where y is the amount of water in the 3-gallon jug.
Fill the 3-gallon jug: This operator fills the 3-gallon jug to its maximum capacity. The
resulting state will be (x, 3), where x is the amount of water in the 4-gallon jug.
Empty the 4-gallon jug: This operator empties the 4-gallon jug completely. The resulting
state will be (0, y), where y is the amount of water in the 3-gallon jug.
Empty the 3-gallon jug: This operator empties the 3-gallon jug completely. The resulting
state will be (x, 0), where x is the amount of water in the 4-gallon jug.
Pour water from the 4-gallon jug into the 3-gallon jug: This operator pours water from the
4-gallon jug into the 3-gallon jug until the 3-gallon jug is full or the 4-gallon jug is empty.
G.E.C Dahod 8
member(X,[X|_]).
member(X,[Y|Z]):-member(X,Z).
move(X,Y,_):-X=:=2,Y=:=0,write('done'),!.
move(X,Y,Z):-X<4,\+member((4,Y),Z),write("fill 4 jug"),nl,move(4,Y,[(4,Y)|Z]).
move(X,Y,Z):-Y<3,\+member((X,3),Z),write("fill 3 jug"),nl,move(X,3,[(X,3)|z]).
move(X,Y,Z):-X>0,\+member((0,Y),Z),write("pour 4 jug"),nl,move(0,Y,[(0,Y)|Z]).
move(X,Y,Z):-Y>0,\+member((X,0),Z),write("pour 3 jug"),nl,move(X,0,[(X,0)|Z]).
move(X,Y,Z):-P is X+Y,P>=4,Y>0,K is 4-X,M is Y-K,\+member((4,M),Z),write("pour from 3jug
to 4jug"),nl,move(4,M,[(4,M)|Z]).
move(X,Y,Z):-P is X+Y,P>=3,X>0,K is 3-Y,M is X-K,\+member((M,3),Z),write("pour from 4jug
to 3jug"),nl,move(M,3,[(M,3)|Z]).
move(X,Y,Z):-K is X+Y,K<4,Y>0,\+member((K,0),Z),write("pour from 3jug to
4jug"),nl,move(K,0,[(K,0)|Z]).
move(X,Y,Z):-K is X+Y,K<3,X>0,\+member((0,K),Z),write("pour from 4jug to
3jug"),nl,move(0,K,[(0,K)|Z]).
Output:
G.E.C Dahod 9
Conclusion:
I have successfully understood searching techniques and implement them in Water-Jug Problem.
Experiment No: 3
Date:
Objectives:To optimize the performance of the A* algorithm by minimizing the number of states
explored and improving the efficiency of the heuristic function.
Theory:
A* Algorithm
A* is a computer algorithm that is widely used in pathfinding and graph traversal, the process of
plotting an efficiently traversable path between multiple points, called nodes. Noted for its
performance and accuracy, it enjoys widespread use.
G.E.C Dahod 10
So we use two lists namely ‘open list‘ and ‘closed list‘ the open list contains all the nodes that are
being generated and are not existing in the closed list and each node explored after it’s
neighboring nodes are discovered is put in the closed list and the neighbors are put in the open list
this is how the nodes expand. Each node has a pointer to its parent so that at any given point it can
retrace the path to the parent. Initially, the open list holds the start(Initial) node. The next node
chosen from the open list is based on its f score, the node with the least f score is picked up and
explored.
A* uses a combination of heuristic value (h-score: how far the goal node is) as well as the g-score
(i.e. the number of nodes traversed from the start node to current node).
In our 8-Puzzle problem, we can define the h-score as the number of misplaced tiles by
comparing the current state and the goal state or summation of the Manhattan distance between
misplaced nodes.
g-score will remain as the number of nodes traversed from start node to get to the current node.
calculate the h-score by comparing the initial(current) state and goal state and counting the
number of misplaced tiles.
Thus, h-score = 5 and g-score = 0 as the number of nodes traversed from the start node to the
current node is 0.
We first move the empty space in all the possible directions in the start state and calculate the f-
score for each state. This is called expanding the current state.
After expanding the current state, it is pushed into the closed list and the newly generated states
are pushed into the open list. A state with the least f-score is selected and expanded again. This
process continues until the goal state occurs as the current state. Basically, here we are providing
the algorithm a measure to choose its actions. The algorithm chooses the best possible action and
proceeds in that path.
G.E.C Dahod 11
It is important to handle edge cases such as unsolvable puzzles, invalid puzzle states, and memory
limitations to avoid program crashes or incorrect results.
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.
Observation/Program:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashSet;
G.E.C Dahod 12
class PuzzleNode {
int[][] state;
PuzzleNode parent;
String action;
int cost;
int heuristic;
G.E.C Dahod 13
return newState;
}
return validActions;
}
G.E.C Dahod 14
while (!openSet.isEmpty()) {
PuzzleNode currentNode = openSet.poll();
int[][] currentState = currentNode.state;
if (isGoalState(currentState)) {
// Goal state reached, reconstruct the path
ArrayList<String> path = new ArrayList<>();
while (currentNode != null) {
if (currentNode.action != null) {
path.add(currentNode.action);
}
currentNode = currentNode.parent;
}
return path;
}
closedSet.add(arrayToString(currentState));
if (!closedSet.contains(newStateString)) {
PuzzleNode newNode = new PuzzleNode(newState, currentNode, action,
currentNode.cost + 1);
openSet.add(newNode);
}
}
}
return null; // No solution found
}
G.E.C Dahod 15
Output:
G.E.C Dahod 16
Conclusion:
I have understood how to implement searching algorithms such as A* algorithm which is widely
used in path finding and graph traversal.
G.E.C Dahod 17
Experiment No: 4
cat(tom).
cat(cat1).
mat(mat1).
sat_on(cat1,mat1).
bird(bird1).
caught(tom,bird1).
like(X,cream) :– cat(X).
mammal(X) :– cat(X).
has(X,fur) :– mammal(X).
animal(X) :– mammal(X).
animal(X) :– bird(X).
owns(john,tom).
is_coloured(tom,ginger).
Date:
Theory:
Semantic Nets provide a powerful tool for representing and organizing knowledge in artificial
intelligence.
Semantic Nets use symbols to represent concepts and relationships between them. Here are the
common symbols used in Semantic Nets:
Nodes or Concepts: Nodes represent concepts or objects in the Semantic Net. They are
usually represented by rectangles, circles or ovals. The name of the concept is usually
written inside the node.
Arcs or Relations: Arcs represent the relationships between concepts in the Semantic Net.
They are usually represented by arrows or lines connecting two nodes. The label of the arc
describes the relationship between the two nodes.
Attributes: Attributes are used to describe the properties or characteristics of a node or
concept. They are usually written inside the node as smaller labels.
Values: Values represent the specific values of attributes associated with a particular node
or concept. They are usually written next to the attribute label in the node.
Unary Relations: Unary relations are used to represent a relationship between a concept
and an attribute. They are usually represented by an arrow pointing from the attribute to
the concept.
Cardinality: Cardinality is used to indicate the number of objects that are related to a
particular concept. It is usually represented by a small number in a circle or next to the arc.
Inheritance: Inheritance is used to represent the relationship between a general concept and
a more specific concept. It is usually represented by an arrow pointing from the specific
concept to the more general concept.
G.E.C Dahod 18
Procedure:
1. Create a node for each object or concept.
2. Create an arc between each object and its attribute or property.
3. Add appropriate labels to each node and arc to indicate the relationship between objects.
Observation/Program:
% Entities
cat(tom).
cat(cat1).
mat(mat1).
bird(bird1).
person(john).
Output:
Conclusion:
G.E.C Dahod 19
Experiment No: 5
Date:
Theory:
It has been used by many programs that portend to understand English (MARGIE, SAM, PAM).
CD developed by Schank et al. as were the previous examples.
CD provides:
Sentences are represented as a series of diagrams depicting actions using both abstract and real
physical situations.
ATRANS
-- Transfer of an abstract relationship. e.g. give.
PTRANS
-- Transfer of the physical location of an object. e.g. go.
PROPEL
-- Application of a physical force to an object. e.g. push.
MTRANS
-- Transfer of mental information. e.g. tell.
G.E.C Dahod 20
Six primitive conceptual categories provide building blocks which are the set of allowable
dependencies in the concepts in a sentence:
PP
-- Real world objects.
ACT
-- Real world actions.
PA
-- Attributes of objects.
AA
-- Attributes of actions.
T
-- Times.
LOC
-- Locations.
Arrows indicate the direction of dependency. Letters above indicate certain relationships:
o
-- object.
R
-- recipient-donor.
I
-- instrument e.g. eat with a spoon.
D
-- destination e.g. going home.
Double arrows ( ) indicate two-way links between the actor (PP) and action (ACT).
The actions are built from the set of primitive acts (see above).
o These can be modified by tense etc.
The use of tense and mood in describing events is extremely important and schank
introduced the following modifiers:
p
-- past
f
G.E.C Dahod 21
-- start transition
-- finished transition
k
-- continuing
?
-- interrogative
/
-- negative
delta
-- timeless
c
-- conditional
the absence of any modifier implies the present tense.
Advantages of CD:
Disadvantages of CD:
Primitive actions are the basic actions that can be performed or described without
reference to other actions or concepts.
Procedure:
1. Identify the main concepts and their relationships.
2. Use Proper Primitives to draw Conceptual Diagrams.
Diagram:
yesterday (Time)
G.E.C Dahod 22
Experiment No: 6
Implement the Minimax algorithm for a simple tic-tac-toe game using Python Language.
Date:
Objectives:To illustrate how to recursively apply the Minimax algorithm to build a game tree and
determine the optimal move for the computer player.
Theory:
The Minimax Algorithm is a popular decision-making algorithm used in game
theory, which allows a player to determine the best possible move to make, given
that the opponent will also make the best possible move.
Here's a general implementation of the Minimax algorithm:
Define the game state: The game state should be defined in terms of the current
state of the board or game, including the position of all pieces, scores, and any
other relevant information.
Define the game tree: The game tree represents all the possible moves that can be
made from the current game state, and the resulting game states that will arise
from each move. The game tree can be constructed recursively, with the root node
representing the current game state, and the child nodes representing the possible
moves that can be made from that state.
Assign scores to each game state: At the bottom of the game tree, assign a score to
each game state based on the outcome of the game from that state. For example, if
the game is won by the player who reached that state, assign a positive score, and
if the game is lost, assign a negative score.
Determine the best move: Starting from the root node, alternate between selecting
the move that maximizes the score for the player and selecting the move that
minimizes the score for the opponent until you reach a leaf node. The score of that
leaf node will then be propagated back up the tree to the root node, and the best
move will be the one that leads to the highest score.
Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
3. Create a function to get the best move for the current player.
G.E.C Dahod 23
Observation/Program:
# Minimax algorithm
def minimax(board, depth, is_maximizing):
if is_game_over(board) or depth == 0:
return evaluate(board)
if is_maximizing:
G.E.C Dahod 24
best_move = get_best_move(board)
board[best_move] = PLAYER_O
if is_game_over(board):
print_board(board)
G.E.C Dahod 25
Output:
Conclusion:
I have successfully created Tic-Toe game in Python by applying Min-Max Algorithm.
G.E.C Dahod 26
Experiment No: 7
Implement Bayesian Networks algorithm for the Monty Hall Problem using any
programming Language.
Date:
Objectives:To understand how Bayesian Networks can be used to represent and reason about
uncertain knowledge.
Theory:
Bayesian Networks is a probabilistic graphical model used for representing and reasoning about
uncertain knowledge. It consists of a directed acyclic graph (DAG) where nodes represent random
variables and edges represent dependencies between them. Each node has a conditional
probability distribution (CPD) that describes the probability of that node given its parents.
Bayesian Networks can be used for a wide range of tasks including prediction, classification,
diagnosis, and decision-making.
The algorithm for constructing a Bayesian Network involves the following steps:
Identify the random variables: The first step is to identify the random variables that are
relevant to the problem. These variables can be discrete or continuous, and can represent
events, states, or properties.
Define the dependencies: The next step is to define the dependencies between the
variables. This is done by specifying the causal relationships between the variables, and
determining which variables are parents and which are children.
Assign probabilities: The next step is to assign probabilities to the variables. This involves
specifying the prior probabilities for each variable, as well as the conditional probabilities
for each node given its parents.
Construct the graph: The final step is to construct the DAG by connecting the nodes
according to their dependencies, and specifying the CPDs for each node.
Procedure:
1. Define an evaluation function to evaluate the game state and return a score.
2. Define a recursive function to search for the best move using the Minimax
algorithm.
3. Create a function to get the best move for the current player.
Observation/Program:
import random
for _ in range(num_simulations):
# Randomly place the car behind one of the doors
doors = [0, 0, 0]
car_behind = random.randint(0, 2)
doors[car_behind] = 1
# Number of simulations
num_simulations = 10000
Output:
Conclusion:
We have implemented Bayesian Networks algorithm for the Monty Hall Problem in
Python Language.
G.E.C Dahod 29
Experiment No: 8
Date:
Objectives: Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.
Theory:
Connectionist Models
Neural networks are by far the most commonly used connectionist model today.
Though there are a large variety of neural network models, they almost always follow two
basic principles regarding the mind:
Any mental state can be described as an (N)-dimensional vector of numeric activation
values over neural units in a network.
Memory is created by modifying the strength of the connections between neural units. The
connection strengths, or "weights", are generally represented as an N×N matrix.
G.E.C Dahod 30
Procedure:
Choose a connectionist modeling tool
Define the problem
Design the architecture of the
Implement the model
Test the model
Deploy the model
Observation/Program:
import transformers
print(transformers.__version__)
import librosa
import torch
import IPython.display as display
G.E.C Dahod 31
audio,sampling_rate
# audio
display.Audio("../input/audio-dataset/Voice 002.m4a", autoplay=True)
transcriptions
Output:
Conclusion:
I have learnt about tensorflow and how it works through preparting a model and deploying it.
G.E.C Dahod 32
Experiment No: 9
Date:
Objectives:To use a computational approach that mimics the process of natural selection to solve
optimization problems
Equipment/InstrumentsProgramming language
Theory:
Genetic Algorithm (GA) is a popular meta heuristic optimization algorithm in the field of artificial
intelligence (AI).Genetic Algorithms are based on the theory of natural selection and work on
generating a set of random solutions and making them compete in an arena where only the fittest
survive. It is often used to solve complex optimization problems where other traditional methods
may not work well.
The first step in using GA for an AI problem is to define the problem as an optimization problem.
This involves identifying the objective function that needs to be optimized and the constraints (if
any) that need to be satisfied.
Once the problem is defined, the next step is to create an initial population of candidate solutions.
The population is typically generated randomly or using some heuristics depending on the
problem.
The fitness function is then defined, which evaluates each chromosome in the population based on
how well it satisfies the objective function and constraints.
Next, the GA applies selection, crossover, and mutation operators to create new and hopefully
better solutions. Selection involves choosing the top-performing chromosomes to be carried over
to the next generation. Crossover involves combining two chromosomes to create new offspring.
G.E.C Dahod 33
The GA then repeats the process of selection, crossover, and mutation for a number of generations
or until a stopping criterion is met (such as reaching a maximum number of generations or finding
an optimal solution).
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
Observation/Program:
import random
# Mutation
def mutate(individual, mutation_rate):
mutated = [bit ^ 1 if random.random() < mutation_rate else bit for bit in individual]
return mutated
# Genetic Algorithm
def genetic_algorithm(population_size, individual_length, mutation_rate, max_generations,
tournament_size):
population = initialize_population(population_size, individual_length)
generation = 0
if __name__ == "__main__":
population_size = 50
individual_length = 20
mutation_rate = 0.01
max_generations = 100
tournament_size = 5
G.E.C Dahod 35
Output:
Conclusion:
We have successfully implemented Genetic Algorithm in Python Language and founded Best
Solution and best fitness.
Experiment No: 10
Write a PROLOG program based on List Operations.
Date:
Theory:
The list is a simple data structure that is widely used in non-numeric programming. List consists
of any number of items, for example, red, green, blue, white, dark. It will be represented as, [red,
green, blue, white, dark]. The list of elements will be enclosed with square brackets.
A list can be either empty or non-empty. In the first case, the list is simply written as a Prolog
atom, []. In the second case, the list consists of two things as given below –
Suppose we have a list like: [red, green, blue, white, dark]. Here the head is red and tail is [green,
blue, white, dark]. So the tail is another list.
Now, let us consider we have a list, L = [a, b, c]. If we write Tail = [b, c] then we can also write
the list L as L = [ a | Tail]. Here the vertical bar (|) separates the head and tail parts.
A data structure that is either empty or consists of two parts − a head and a tail. The tail itself has
to be a list.
Operations Definition
Membership During this operation, we can verify whether a given element is member
Checking of specified list or not?
Length Calculation With this operation, we can find the length of a list.
Delete Items This operation removes the specified element from a list.
Append Items Append operation adds one list into another (as an item).
Procedure:
Observation/Program:
% Reverse a list.
reverse_list(List, Reversed) :- reverse_list_acc(List, [], Reversed).
reverse_list_acc([], Acc, Acc).
reverse_list_acc([H|T], Acc, Reversed) :- reverse_list_acc(T, [H|Acc], Reversed).
% Example usage:
% is_list([1, 2, 3]).
% list_length([1, 2, 3, 4], Len).
% list_sum([1, 2, 3, 4], Sum).
% is_member(2, [1, 2, 3, 4]).
% append_lists([1, 2, 3], [4, 5], Result).
% reverse_list([1, 2, 3], Reversed).
% last_element([1, 2, 3, 4], Last).
% delete_first(3, [1, 2, 3, 4, 3], Result).
% delete_all(3, [1, 2, 3, 4, 3], Result).
% nth_element(3, [1, 2, 3, 4], Element).
G.E.C Dahod 38
Output:
G.E.C Dahod 39
Conclusion:
We have successfully created prolog program for lists and perform various operations on them
such as append, reverse, delete, sum of list, min , max operations etc. and understood that how list
works.
G.E.C Dahod 40