You are on page 1of 43

lOMoARcPSD|40669920

AI-Practical File GTU

Computer Engineering (Gujarat Technological University)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)
lOMoARcPSD|40669920

A Laboratory Manual for

Artificial Intelligence
(3170716)

B.E. Semester 7
(Computer Engineering)

Institute logo

Directorate of Technical Education,


Gandhinagar,Gujarat

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Government Engineering College, Dahod


Department of Computer Engineering

Certificate

This is to certify that Mr. /Ms. ___________________________________


________ Enrollment No. _______________of B.E. Semester
_____Computer Engineering of this Institute (GTU Code: _____ ) has
satisfactorily completed the Practical / Tutorial work for the subject Artificial
Intelligence (3170716)for the academic year 2023-24.

Place: __________
Date: __________

Name and Sign of Faculty member

Head of the Department

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716)

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.

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716)

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.

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716)

5) To reverse the list.


6) To find the last element of a list.
7) To delete the first occurrence of an
element from a list.
8) To delete every occurrence of an element
from a list.
9) To find Nth element from the list.
Total

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


Experiment No: 1

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:

Objectives: To learn different kinds of knowledge bases of Prolog Programming.


To create a powerful and flexible system for representing, manipulating, and
reasoning about information in a logical and structured way.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

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.

We can ask Prolog whether Mia is a woman by posing the query:

?- 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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


So in general rules say: if the body of the rule is true, then the head of the rule is true too. And
now for the key point:
If a knowledge base contains a rule head - body, and Prolog knows that body follows from the
information in the knowledge base, then Prolog can infer head. This fundamental deduction step is
called modus ponens.

Knowledge Base 3

KB3, our third knowledge base, consists of five clauses:


happy(vincent).
listens2Music (butch). playsAirGuitar (vincent):-
listens 2Music(vincent),
happy(vincent). playsAirGuitar(butch):-
happy(butch).
playsAirGuitar(butch):-
listens2Music(butch). There are two facts, happy(vincent) and listens2Music(butch), and three
rules.
KB3 defines the same three predicates as KB2 (namely happy, listens2Music, and playsAirGuitar)
but it defines them differently. In particular, the three rules that define the playsAirGuitar
predicate introduce some new ideas.

Knowledge Base 4

Here is KB4, our fourth knowledge base:


woman(mia).
woman(jody).
woman (yolanda).
loves (vincent,mia).
loves (marsellus,mia).
loves (pumpkin, honey_bunny).
loves (honey_bunny, pumpkin).

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


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.)

Experiment No: 2

Prolog program to implement Water-Jug Problem.

Date:

Objectives:To create a functional and efficient Prolog program for solving logic puzzles.

Equipment/Instruments: Personal Computer, SWI-Prolog Interpreter

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


The resulting state will be (x - (3 - y), 3) if the 4-gallon jug becomes empty or (4, y) if the
3-gallon jug becomes full.
 Pour water from the 3-gallon jug into the 4-gallon jug: This operator pours water from the
3-gallon jug into the 4-gallon jug until the 4-gallon jug is full or the 3-gallon jug is empty.
The resulting state will be (4, y - (4 - x)) if the 3-gallon jug becomes empty or (x, 3) if the
4-gallon jug becomes full.
Observation/Program:

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Conclusion:
I have successfully understood searching techniques and implement them in Water-Jug Problem.
Experiment No: 3

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

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.

Equipment/Instruments: Personal Computer, open-source software for programming

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


The key feature of the A* algorithm is that it keeps a track of each visited node which helps in
ignoring the nodes that are already visited, saving a huge amount of time. It also has a list that
holds all the nodes that are left to be explored and it chooses the most optimal node from this list,
thus saving time not exploring unnecessary or less optimal nodes.

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.

f-score = h-score + g-score

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.

How A* solves the 8-Puzzle problem.

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


This solves the issue of generating redundant child states, as the algorithm will expand the node
with the least f-score.

Safety and necessary Precautions:

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


import java.util.PriorityQueue;

class PuzzleNode {
int[][] state;
PuzzleNode parent;
String action;
int cost;
int heuristic;

public PuzzleNode(int[][] state, PuzzleNode parent, String action, int cost) {


this.state = state;
this.parent = parent;
this.action = action;
this.cost = cost;
this.heuristic = calculateHeuristic();
}

private int calculateHeuristic() {


// Calculate the Manhattan distance as the heuristic
int h = 0;
int goalState[][] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state[i][j] != 0) {
int goalRow = state[i][j] / 3;
int goalCol = state[i][j] % 3;
h += Math.abs(i - goalRow) + Math.abs(j - goalCol);
}
}
}
return h;
}
}

public class EightPuzzleSolver {


public static int[][] applyAction(int[][] state, String action) {
int i = -1, j = -1;
// Find the blank position
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (state[i][j] == 0) {
break;
}
}
if (j < 3) {
break;
}
}

int[][] newState = new int[3][3];


for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {

G.E.C Dahod 13

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


newState[k][l] = state[k][l];
}
}

// Apply the action


if (action.equals("up") && i > 0) {
newState[i][j] = newState[i - 1][j];
newState[i - 1][j] = 0;
} else if (action.equals("down") && i < 2) {
newState[i][j] = newState[i + 1][j];
newState[i + 1][j] = 0;
} else if (action.equals("left") && j > 0) {
newState[i][j] = newState[i][j - 1];
newState[i][j - 1] = 0;
} else if (action.equals("right") && j < 2) {
newState[i][j] = newState[i][j + 1];
newState[i][j + 1] = 0;
}

return newState;
}

public static ArrayList<String> getValidActions(int[][] state) {


int i = -1, j = -1;
// Find the blank position
for (i = 0; i < 3; i++) {
for (j = 0; j < 3; j++) {
if (state[i][j] == 0) {
break;
}
}
if (j < 3) {
break;
}
}

ArrayList<String> validActions = new ArrayList<>();


if (i > 0) {
validActions.add("up");
}
if (i < 2) {
validActions.add("down");
}
if (j > 0) {
validActions.add("left");
}
if (j < 2) {
validActions.add("right");
}

return validActions;
}

G.E.C Dahod 14

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

public static ArrayList<String> solveEightPuzzle(int[][] initialState) {


PriorityQueue<PuzzleNode>openSet= new PriorityQueue<>(Comparator.comparingInt(node
->
node.cost + node.heuristic));
HashSet<String> closedSet = new HashSet<>();

PuzzleNode startNode = new PuzzleNode(initialState, null, null, 0);


openSet.add(startNode);

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));

ArrayList<String> validActions = getValidActions(currentState);


for (String action : validActions) {
int[][] newState = applyAction(currentState, action);
String newStateString = arrayToString(newState);

if (!closedSet.contains(newStateString)) {
PuzzleNode newNode = new PuzzleNode(newState, currentNode, action,
currentNode.cost + 1);
openSet.add(newNode);
}
}
}
return null; // No solution found
}

public static boolean isGoalState(int[][] state) {


int[][] goalState = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state[i][j] != goalState[i][j]) {
return false }
}
}
return true;

G.E.C Dahod 15

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


}
public static String arrayToString(int[][] array) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
builder.append(array[i][j]);
}
}
return builder.toString();
}

public static void main(String[] args) {


int[][] initialState = {
{1, 2, 3},
{4, 0, 5},
{6, 7, 8}
};

ArrayList<String> solution = solveEightPuzzle(initialState);


if (solution != null) {
System.out.println("Solution found:");
for (String action : solution) {
System.out.println("Action: " + action);
}
} else {
System.out.println("No solution found.");
}
}
}

Output:

G.E.C Dahod 16

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Experiment No: 4

Convert the given Prolog predicates into Semantic Net.

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:

Objectives: To Learn Basic symbols of Semantic Net.

Equipment/Instruments: Personal Computer, open-source software for programming

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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).

% Relationships and Attributes


sat_on(cat1, mat1).
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).

% Query to check if an entity is an animal


is_animal(X) :- animal(X).

% Query to check if an entity is a mammal


is_mammal(X) :- mammal(X).

Output:

Conclusion:
G.E.C Dahod 19

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


I have learnt basic symbols of semantic net.

Experiment No: 5

Construct the Conceptual Dependency for the given statements.


1) John gives Mary a book
2) John gave Mary the book yesterday.

Date:

Objectives: To identify the agents involved


To identify the action performed
To identify the object of the action

Equipment/Instruments: Personal Computer, open-source software

Theory:

Conceptual Dependency originally developed to represent knowledge acquired from natural


language input.
The goals of this theory are:

 To help in the drawing of inference from sentences.


 To be independent of the words used in the original input.
 That is to say: For any 2 (or more) sentences that are identical in meaning there should be
only one representation of that meaning.

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:

 a structure into which nodes representing information can be placed


 a specific set of primitives
 at a given level of granularity.

Sentences are represented as a series of diagrams depicting actions using both abstract and real
physical situations.

 The agent and the objects are represented


 The actions are built up from a set of primitive acts which can be modified by tense.

Examples of Primitive Acts are:

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


MBUILD
-- Construct new information from old. e.g. decide.
SPEAK
-- Utter a sound. e.g. say.
ATTEND
-- Focus a sense on a stimulus. e.g. listen, watch.
MOVE
-- Movement of a body part by owner. e.g. punch, kick.
GRASP
-- Actor grasping an object. e.g. clutch.
INGEST
-- Actor ingesting an object. e.g. eat.
EXPEL
-- Actor getting rid of an object from body. e.g. ????.

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


-- future
t
-- transition

-- start transition

-- finished transition
k
-- continuing
?
-- interrogative
/
-- negative
delta
-- timeless
c
-- conditional
the absence of any modifier implies the present tense.

Advantages of CD:

 Using these primitives involves fewer inference rules.


 Many inference rules are already represented in CD structure.
 The holes in the initial structure help to focus on the points still to be established.

Disadvantages of CD:

 Knowledge must be decomposed into fairly low level primitives.


 Impossible or difficult to find correct set of primitives.
 A lot of inference may still be required.
 Representations can be complex even for relatively simple actions.

Safety and necessary Precautions:

 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:

John (Agent) Give (Past Tense) Mary (Target)

the book (Object)

yesterday (Time)

G.E.C Dahod 22

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


Conclusion:
I have learnt the proper primitives to draw conceptual diagrams.

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.

Equipment/Instruments: Personal Computer, Python3, Jupytor Notebook

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Observation/Program:

# Define constants for player symbols


EMPTY = ' '
PLAYER_X = 'X'
PLAYER_O = 'O'

# Define the Tic-Tac-Toe board


board = [EMPTY] * 9

# Print the Tic-Tac-Toe board


def print_board(board):
for i in range(0, 9, 3):
print(board[i], "|", board[i + 1], "|", board[i + 2])
if i < 6:
print("---------")

# Check if the game is over


def is_game_over(board):
# Check for a win
for i in range(0, 9, 3):
if board[i] == board[i + 1] == board[i + 2] != EMPTY:
return True
for i in range(3):
if board[i] == board[i + 3] == board[i + 6] != EMPTY:
return True
if board[0] == board[4] == board[8] != EMPTY or board[2] == board[4] == board[6] !=
EMPTY:
return True
# Check for a tie
return not any(cell == EMPTY for cell in board)

# Evaluate the game state


def evaluate(board):
if is_game_over(board):
if PLAYER_X in board:
return -1
elif PLAYER_O in board:
return 1
return 0
return 0

# 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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


max_eval = float("-inf")
for i in range(9):
if board[i] == EMPTY:
board[i] = PLAYER_O
eval = minimax(board, depth - 1, False)
board[i] = EMPTY
max_eval = max(max_eval, eval)
return max_eval
else:
min_eval = float("inf")
for i in range(9):
if board[i] == EMPTY:
board[i] = PLAYER_X
eval = minimax(board, depth - 1, True)
board[i] = EMPTY
min_eval = min(min_eval, eval)
return min_eval

# Get the best move for the current player


def get_best_move(board):
best_move = -1
best_eval = float("-inf")
for i in range(9):
if board[i] == EMPTY:
board[i] = PLAYER_O
eval = minimax(board, 2, False) # Adjust depth for difficulty
board[i] = EMPTY
if eval > best_eval:
best_eval = eval
best_move = i
return best_move

# Main game loop


while not is_game_over(board):
print_board(board)
move = -1
while move < 0 or move >= 9 or board[move] != EMPTY:
try:
move = int(input("Enter your move (0-8): "))
except ValueError:
pass
board[move] = PLAYER_X
if is_game_over(board):
print_board(board)
print("You win!")
break

best_move = get_best_move(board)
board[best_move] = PLAYER_O

if is_game_over(board):
print_board(board)

G.E.C Dahod 25

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


print("Computer wins!")
break

if all(cell != EMPTY for cell in board):


print_board(board)
print("It's a tie!")
break

Output:

Conclusion:
I have successfully created Tic-Toe game in Python by applying Min-Max Algorithm.

G.E.C Dahod 26

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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.

Equipment/Instruments: Personal Computer, Programming Language

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.

The Monty Hall problem


It is a famous probability puzzle based on a game show scenario. The problem is named after
Monty Hall, the host of the game show "Let's Make a Deal".
The scenario goes as follows:
 There are three doors, behind one of which is a prize, and behind the other two are goats.
The player chooses one door, and then the host, who knows what is behind each door,
opens one of the other two doors to reveal a goat. The player is then given the option to
switch their choice to the other unopened door or stick with their original choice.
 The question is: should the player switch their choice, or stick with their original choice?
 The answer is that the player should always switch their choice.
 To understand why this is the case, consider the following:
 When the player initially chooses a door, there is a 1/3 chance that they have chosen the
door with the prize, and a 2/3 chance that they have chosen a door with a goat. When the
G.E.C Dahod 27

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


host then opens one of the other doors to reveal a goat, the probability that the player's
initial choice was correct remains at 1/3. However, the probability that the prize is behind
the other unopened door is now 2/3.
 Therefore, when given the option to switch, the player should always switch because the
probability of winning the prize increases from 1/3 to 2/3. This may seem counterintuitive,
as it goes against our initial intuition that the probability of winning should be equally
distributed among the three doors. However, this is a classic example of how probabilities
can be counterintuitive, and why it is important to understand the underlying mathematics.

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

# Simulate the Monty Hall problem


def monty_hall_simulation(num_simulations):
stay_wins = 0
switch_wins = 0

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

# Contestant's initial choice


contestant_choice = random.randint(0, 2)

# Monty Hall opens an empty door


opened_door = next(i for i in range(3) if i != contestant_choice and doors[i] == 0)

# Contestant's strategy: Stay with the initial choice


stay_wins += doors[contestant_choice]

# Contestant's strategy: Switch the choice


switch_choice = next(i for i in range(3) if i != contestant_choice and i != opened_door)
switch_wins += doors[switch_choice]

return stay_wins, switch_wins

# Number of simulations
num_simulations = 10000

stay_wins, switch_wins = monty_hall_simulation(num_simulations)

print(f"Number of simulations: {num_simulations}")


G.E.C Dahod 28

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


print(f"Stay with the initial choice wins: {stay_wins} ({stay_wins / num_simulations * 100:.2f}
%)")
print(f"Switching the choice wins: {switch_wins} ({switch_wins / num_simulations * 100:.2f}
%)")

Output:

Conclusion:
We have implemented Bayesian Networks algorithm for the Monty Hall Problem in
Python Language.

G.E.C Dahod 29

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Experiment No: 8

Demonstrate Connectionist Model using Tool.

Date:

Objectives: Learn a tool should be selected that provides an easy-to-use interface for designing,
training, and deploying Connectionist Model.

Equipment/Instruments: Personal Computer, Connectionist Models Tool

Theory:

Connectionist Models

 In contrast to the symbolist architectures in which the mind is assumed to be a physical


symbol-processing system, connectionist systems are networks of large numbers of
interconnected “units.” Each unit can have associated with it a certain amount of
activation. Connections to other units are given explicit weights (including negative
weights).
 Activation spreads from one unit to another as a function of the weighted links. For
example, the function of a typical link might be to multiply the input activation by its
weight and then apply a threshold function. A typical unit would sum all of its input
activations, then divide this among all its links. The weights on the links are adjustable
with experience.
 Some of the links may represent sensory inputs from the outside world; some may
represent output to effectors to the outside world. Units in connectionist models are
usually taken to be below the level of a symbol. For example, different units may
represent visual features of a letter such as verticalness or roundedness.

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Some Examples of popular tools:

 TensorFlow: An open-source platform developed by Google for building and training


machine learning models, including neural networks. It provides a high-level API that
makes it easy to build complex models with multiple layers and customizable activation
functions.
 PyTorch: An open-source machine learning library developed by Facebook that provides a
dynamic computational graph for building neural networks. It is highly optimized for GPU
acceleration and provides a Pythonic interface for building and training models.
 Keras: A high-level neural networks API developed in Python that can run on top of
TensorFlow, CNTK, or Theano. It provides a simple and intuitive interface for designing
and training neural networks, and supports both convolutional and recurrent networks.
 Caffe: A deep learning framework developed by Berkeley AI Research (BAIR) that is
optimized for speed and memory efficiency. It provides a C++ API for building and
training neural networks and supports a variety of pre-trained models for image
recognition and other tasks.
 FastAI: A Python library that provides tools for building and training deep learning
models, including neural networks, with a focus on ease of use and fast prototyping.

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:

!pip install --upgrade transformers

import transformers
print(transformers.__version__)

import librosa
import torch
import IPython.display as display

G.E.C Dahod 31

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


from transformers import Wav2Vec2ForCTC, Wav2Vec2Tokenizer
import numpy as np

#load pre-trained model and tokenizer


tokenizer = Wav2Vec2Tokenizer.from_pretrained("facebook/wav2vec2-base-960h")
model = Wav2Vec2ForCTC.from_pretrained("facebook/wav2vec2-base-960h")

#load audio file


audio, sampling_rate = librosa.load("../input/audio-dataset/Voice 002.m4a",sr=16000)

audio,sampling_rate
# audio
display.Audio("../input/audio-dataset/Voice 002.m4a", autoplay=True)

input_values = tokenizer(audio, return_tensors = 'pt').input_values


input_values

# store logits (non-normalized predictions)


logits = model(input_values).logits
logits

# store predicted id's


# pass the logit values to softmax to get the predicted values
predicted_ids = torch.argmax(logits, dim =-1)

# pass the prediction to the tokenzer decode to get the transcription


transcriptions = tokenizer.decode(predicted_ids[0])

transcriptions

Output:

Conclusion:
I have learnt about tensorflow and how it works through preparting a model and deploying it.

G.E.C Dahod 32

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Experiment No: 9

Implement Genetic Algorithm in any Programming Language.

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.

GA works by maintaining a population of candidate solutions (also called chromosomes) and


applies genetic operators such as selection, crossover, and mutation to create new and hopefully
better solutions. The basic idea is to mimic the natural process of evolution and survival of the
fittest in order to find the optimal solution to a problem.

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


Mutation involves randomly changing some genes in a chromosome to introduce diversity into the
population.

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

# Define the problem


def fitness_function(individual):
return sum(individual)

# Define the representation


def create_individual(length):
return [random.randint(0, 1) for _ in range(length)]

# Initialize the population


def initialize_population(population_size, individual_length):
return [create_individual(individual_length) for _ in range(population_size)]

# Select parents (Tournament selection)


def select_parents(population, fitness_func, tournament_size):
selected_parents = []
for _ in range(2):
tournament = random.sample(population, tournament_size)
selected_parent = max(tournament, key=fitness_func)
selected_parents.append(selected_parent)
return selected_parents

# Crossover (One-point crossover)


G.E.C Dahod 34

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


def crossover(parents):
point = random.randint(1, len(parents[0]) - 1)
child1 = parents[0][:point] + parents[1][point:]
child2 = parents[1][:point] + parents[0][point:]
return child1, child2

# Mutation
def mutate(individual, mutation_rate):
mutated = [bit ^ 1 if random.random() < mutation_rate else bit for bit in individual]
return mutated

# Evaluate the offspring


def evaluate_population(population, fitness_func):
return [fitness_func(individual) for individual in population]

# Select survivors (Elitism - keep the best individuals)


def select_survivors(population, fitness_scores):
combined = list(zip(population, fitness_scores))
combined.sort(key=lambda x: x[1], reverse=True)
survivors = [ind for ind, _ in combined[:len(population)]] # Keep the best individuals
return survivors

# Check stopping criteria (maximum generations)


def should_terminate(generation, max_generations):
return generation >= max_generations

# Genetic Algorithm
def genetic_algorithm(population_size, individual_length, mutation_rate, max_generations,
tournament_size):
population = initialize_population(population_size, individual_length)
generation = 0

while not should_terminate(generation, max_generations):


fitness_scores = evaluate_population(population, fitness_function)

parents = select_parents(population, fitness_function, tournament_size)


offspring = crossover(parents)
offspring = [mutate(child, mutation_rate) for child in offspring]

population = select_survivors(population + offspring, fitness_scores)


generation += 1

best_individual = max(population, key=fitness_function)


return best_individual, fitness_function(best_individual)

if __name__ == "__main__":
population_size = 50
individual_length = 20
mutation_rate = 0.01
max_generations = 100
tournament_size = 5

G.E.C Dahod 35

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


best_solution, best_fitness = genetic_algorithm(population_size, individual_length,
mutation_rate, max_generations, tournament_size)

print("Best Solution:", best_solution)


print("Best Fitness:", best_fitness)

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.

 To find the length of a list.


 To sum all numbers of list.
 To find whether given element is a member of a list.
 To append the list.
 To reverse the list.
 To find the last element of a list.
 To delete the first occurrence of an element from a list.
 To delete every occurrence of an element from a list.
 To find nth element from the list.

Date:

Competency and Practical Skills:

Knowledge of basic PROLOG syntax

Equipment/Instruments:Personal Computer, SWI-Prolog Interpreter

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 –

The first item, called the head of the list;

The remaining part of the list, called the tail.


G.E.C Dahod 36

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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.

So the following list representations are also valid −


[a, b, c] = [x | [b, c] ]
[a, b, c] = [a, b | [c] ]
[a, b, c] = [a, b, c | [ ] ]
For these properties we can define the list as –

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.

Following table contains various operations on prolog lists –

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.

Concatenation Concatenation is an operation which is used to join/add two lists.

Delete Items This operation removes the specified element from a list.

Append Items Append operation adds one list into another (as an item).

Insert Items This operation inserts a given item into a list.

Procedure:

1. Define the Structure of List in Prolog.


2. Perform Different List operations.

Observation/Program:

% Define the structure of a list in Prolog.


is_list([]).
is_list([_|_]).

% Find the length of a list.


list_length([], 0).
list_length([_|T], Len) :- list_length(T, LenTail), Len is LenTail + 1.

% Sum all numbers in a list.


G.E.C Dahod 37

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056


list_sum([], 0).
list_sum([H|T], Sum) :- list_sum(T, SumTail), Sum is H + SumTail.

% Check if an element is a member of a list.


is_member(Element, [Element|_]).
is_member(Element, [_|T]) :- is_member(Element, T).

% Append two lists.


append_lists([], List, List).
append_lists([H|T1], List2, [H|T3]) :- append_lists(T1, List2, T3).

% 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).

% Find the last element of a list.


last_element([X], X).
last_element([_|T], Last) :- last_element(T, Last).

% Delete the first occurrence of an element from a list.


delete_first(_, [], []).
delete_first(X, [X|T], T).
delete_first(X, [H|T], [H|Result]) :- delete_first(X, T, Result), !.

% Delete every occurrence of an element from a list.


delete_all(_, [], []).
delete_all(X, [X|T], Result) :- delete_all(X, T, Result), !.
delete_all(X, [H|T], [H|Result]) :- delete_all(X, T, Result).

% Find the nth element from a list (1-based index).


nth_element(1, [X|_], X).
nth_element(N, [_|T], Element) :- N > 1, N1 is N - 1, nth_element(N1, T, Element).

% 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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

Output:

G.E.C Dahod 39

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)


lOMoARcPSD|40669920

Artificial Intelligence (3170716) 200180107056

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

Downloaded by Pralay Guchhait (guchhaitpralay7@gmail.com)

You might also like