Ai 1131

Download as pdf or txt
Download as pdf or txt
You are on page 1of 65

Degree Engineering

A Laboratory Manual for


Artificial Intelligence
(3170716)
[ B.E. (Computer Engineering) : Semester - 7 ]

Enrolment No 200220131124
Name Yash Rana
Branch CSE
Academic Term 2023-24
Institute Name Government Engineering Collage, Patan

Directorate of Technical Education, Gandhinagar,


Gujarat
Government Engineering College, Patan

Computer Science and Engineering

CERTIFICATE

This is to certify that Mr./Ms. Rana Yash

Enrollment No. 200220131124 of B.E. Semester 7th from Computer Engineering

Department of this Institute (GTU Code: 022) has satisfactorily completed the Practical / Tutorial work

for the subject Compiler Design (3170701) for the academic year 2023-24.

Place:

Date:

Signature of Course Faculty Head of the Department


DTE’s Vision

 To provide globally competitive technical education


 Remove geographical imbalances and inconsistencies
 Develop student friendly resources with a special focus on girls’ education and support to
weaker sections
 Develop programs relevant to industry and create a vibrant pool of technical professionals

Institute’s Vision

 To create an ecosystem for proliferation of socially responsible and technically sound


engineers, innovators and entrepreneurs.

Institute’s Mission

 To develop state-of-the-art laboratories and well-equipped academic infrastructure.


 To motivate faculty and staff for qualification up-gradation, and enhancement of subject
knowledge.
 To promote research, innovation and real-life problem-solving skills.
 To strengthen linkages with industries, academic and research organizations.
 To reinforce concern for sustainability, natural resource conservation and social
responsibility.

Department’s Vision

 To create an environment for providing value-based education in Computer Engineering


through innovation, team work and ethical practices.

Department’s Mission

 To produce computer engineering graduates according to the needs of industry,


government, society and scientific community.
 To develop state of the art computing facilities and academic infrastructure.
 To develop partnership with industries, government agencies and R & D organizations for
knowledge sharing and overall development of faculties and students.
 To solve industrial, governance and societal issues by applying computing techniques.
 To create environment for research and entrepreneurship.
Programme Outcomes (POs)

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


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

 Sound knowledge of fundamentals of computer science and engineering including software


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

Program Educational Objectives (PEOs)

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


 Acquire good analysis, design, development, implementation and testing skills to formulate
simple computing solutions to the business and societal needs.
 Provide requisite skills to pursue entrepreneurship, higher studies, research, and
development and imbibe high degree of professionalism in the fields of computing.
 Embrace life-long learning and remain continuously employable.
 Work and excel in a highly competence supportive, multicultural and professional
environment which abiding to the legal and ethical responsibilities.
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.
Artificial Intelligence (3170716)

Practical – Course Outcome matrix

Course Outcomes (COs):


CO-1 Understand the search technique procedures applied to real world problems
CO-2 Understand and use various types of logic and knowledge representation schemes.
CO-3 Understand various Game Playing techniques and apply them in programs.
CO-4 Gain knowledge in AI Applications and advances in Artificial Intelligence
CO-5 Use Prolog Programming language using predicate logic

Sr.
Objective(s) of Experiment CO1 CO2 CO3 CO4 CO5
No.
Write a Prolog program which contains three
predicates: male, female, parent. Make rules for

1. following family relations: father, mother, √
grandfather, grandmother, brother, sister, uncle,
aunt, nephew and niece.
Write a Prolog program to implement Water √
2. √
Jug Problem.
Solve 8 Puzzle Problem using A*Algorithm in any
3. √
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
5. given statements. √
1) John gives Mary a book
2) John gave Mary the book yesterday.
Implement the Minimax algorithm for a simple tic-tac-
6. √
toe game using Python Language.
Implement Bayesian Networks algorithm for
7. the Monty Hall Problem using any √
programming Language.
8. Demonstrate Connectionist Model using Tool. √
Implement Genetic Algorithm using any
9. √
programming Language.
Artificial Intelligence (3170716)

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.
10. 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.
Artificial Intelligence (3170716)

Guidelines for Faculty members

1. Teacher should provide the guideline with demonstration of practical to the students
with all features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
3. Involve all the students in performance of each experiment.
4. Teacher is expected to share the skills and competencies to be developed in the students
and ensure that the respective skills and competencies are developed in the students
after the completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the
demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not
covered in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task
assigned to check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the
guidelines for implementation.

Instructions for Students

1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme,
skill set to be developed etc.
2. Students will have to perform experiments as per practical list given.
3. Students have to show output of each program in their practical file.
4. Students are instructed to submit practical list as per given sample list shown on next page.
5. Student should develop a habit of submitting the experimentation work as per the schedule
and s/he should be well prepared for the same.

Common Safety Instructions

Students are expected to


1) switch on the PC carefully (not to use wet hands)
2) shutdown the PC properly at the end of your Lab
3) carefully handle the peripherals (Mouse, Keyboard, Network cable etc).
4) use Laptop in lab after getting permission from Teacher
Artificial Intelligence (3170716)

Index
(Progressive Assessment Sheet)

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


No. 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 relations:
1.
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
5. the given statements.
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.
Write a PROLOG program based on list:
10. 1) To find the length of a list.
2) To sum all numbers of list.
3) To find whether given element is a
Artificial Intelligence (3170716)

member of a list.
4) To append the list.
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
Artificial Intelligence (3170716) Enrollment No:200220131124
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:

Competency and Practical Skills: Basic Understanding of Predicated and Prolog Syntax

Relevant CO: CO2, CO5

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

7
Artificial Intelligence (3170716) Enrollment No:200220131124

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

8
Artificial Intelligence (3170716) Enrollment No:200220131124
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.

Safety and necessary Precautions:

Use appropriate names and arguments for the predicates.


Make sure that the rules are accurate and cover all possible cases.

Procedure:
1. Define the domain of the knowledge base.
2. Define the facts.
3. Define the rules.
4. Test the knowledge base.

9
Artificial Intelligence (3170716) Enrollment No:200220131124

Observation/Program:

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 of the program:

10
Artificial Intelligence (3170716) Enrollment No:200220131124

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

Quiz:(Sufficient space to be provided for the answers)

1. What is Prolog and what is it used for?


2. What is a knowledge base in Prolog and how is it represented?
3. How do you define facts and rules in Prolog?
4. What are the different types of knowledge bases in Prolog and how are they implemented?
5. How do you query a Prolog knowledge base and what is the output?
6. What are the advantages and disadvantages of using Prolog for implementing knowledge
bases?
7. What are some real-world applications of Prolog-based knowledge bases?

Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online

References used by the students: (Sufficient space to be provided)

Rubric wise marks obtained:

Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks

11
Artificial Intelligence (3170716) Enrollment No:200220131124
Experiment No: 2

Write a Prolog program to implement Water-Jug Problem.

Date:

Competency and Practical Skills: Knowledge of logic programming,Basics of search Techniques

Relevant CO: CO1, CO5

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.
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
12
Artificial Intelligence (3170716) Enrollment No:200220131124
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.

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 initial state using a Prolog predicate.
2. Define the goal state predicate.
3. Define the goal state predicate.
4. Define the operators
5. Define the search algorithm.

Observation/Program:

%database
visited_state(integer,integer).

%predicates
state(integer,integer).

%clauses
state(2,0).
state(X,Y):- X < 4,
not(visited_state(4,Y)),
assert(visited_state(X,Y)),
write("Fill the 4-Gallon Jug: (",X,",",Y,") --> (", 4,",",Y,")\n"),
state(4,Y).

state(X,Y):- Y < 3,
not(visited_state(X,3)),
assert(visited_state(X,Y)),
write("Fill the 3-Gallon Jug: (", X,",",Y,") --> (",
X,",",3,")\n"),
state(X,3).

state(X,Y):- X > 0,
not(visited_state(0,Y)),
assert(visited_state(X,Y)),
write("Empty the 4-Gallon jug on ground: (", X,",",Y,") --> (",
0,",",Y,")\n"),
state(0,Y).

state(X,Y):- Y > 0,
not(visited_state(X,0)),
assert(visited_state(X,0)),
write("Empty the 3-Gallon jug on ground: (", X,",",Y,") --> (",
X,",",0,")\n"),
state(X,0).

state(X,Y):- X + Y >= 4,
Y > 0,
NEW_Y = Y - (4 - X),
not(visited_state(4,NEW_Y)),
assert(visited_state(X,Y)),
write("Pour water from 3-Gallon jug to 4-gallon until it is full:
(", X,",",Y,") --> (", 4,",",NEW_Y,")\n"),
state(4,NEW_Y).

13
Artificial Intelligence (3170716) Enrollment No:200220131124

state(X,Y):- X + Y >=3,
X > 0,
NEW_X = X - (3 - Y),
not(visited_state(X,3)),
assert(visited_state(X,Y)),
write("Pour water from 4-Gallon jug to 3-gallon until it is full:
(", X,",",Y,") --> (", NEW_X,",",3,")\n"),
state(NEW_X,3).

state(X,Y):- X + Y>=4,
Y > 0,
NEW_X = X + Y,
not(visited_state(NEW_X,0)),
assert(visited_state(X,Y)),
write("Pour all the water from 3-Gallon jug to 4-gallon: (",
X,",",Y,") --> (", NEW_X,",",0,")\n"),
state(NEW_X,0).

state(X,Y):- X+Y >=3,


X > 0,
NEW_Y = X + Y,
not(visited_state(0,NEW_Y)),
assert(visited_state(X,Y)),
write("Pour all the water from 4-Gallon jug to 3-gallon: (",
X,",",Y,") --> (", 0,",",NEW_Y,")\n"),
state(0,NEW_Y).

state(0,2):- not(visited_state(2,0)),
assert(visited_state(0,2)),
write("Pour 2 gallons from 3-Gallon jug to 4-gallon: (",
0,",",2,") --> (", 2,",",0,")\n"),
state(2,0).

state(2,Y):- not(visited_state(0,Y)),
assert(visited_state(2,Y)),
write("Empty 2 gallons from 4-Gallon jug on the ground: (",
2,",",Y,") --> (", 0,",",Y,")\n"),
state(0,Y).

goal:-
makewindow(1,2,3,"4-3 Water Jug Problem",0,0,25,80),
state(0,0).

Output:

% Goal:-
makewindow(1,2,3,"4-3 Water Jug Problem",0,0,25,80),
state(0,0).
+ 4-3 Water Jug Problem +
| Fill the 4-Gallon Jug: (0,0) --> (4,0)
|
| Fill the 3-Gallon Jug: (4,0) --> (4,3)
|
| Empty the 4-Gallon jug on ground: (4,3) --> (0,3)
|
| Pour all the water from 3-Gallon jug to 4-gallon: (0,3) --> (3,0)
|
| Fill the 3-Gallon Jug: (3,0) --> (3,3)
|

14
Artificial Intelligence (3170716) Enrollment No:200220131124
| Pour water from 3-Gallon jug to 4-gallon until it is
full: (3,3) --> (4,2) |
| Empty the 4-Gallon jug on ground: (4,2) --> (0,2)
|
| Pour all the water from 3-Gallon jug to 4-gallon: (0,2) --> (2,0)
|
|
|
| Press the SPACE bar
|
|
|
|
|
|
|
+ +

Conclusion:

The Water-Jug Problem serves as a useful exercise for practicing problem-solving and algorithmic
thinking, and it highlights the power of Prolog in modeling and solving such puzzles through declarative
programming and backtracking. It's an illustrative example of how Prolog can be employed to solve
problems in a logical and systematic manner.

Quiz: (Sufficient space to be provided for the answers)

1. What search algorithm can you use to find a solution to the Water-Jug Problem, and how
would you implement it in Prolog?
Ans  To solve the Water-Jug Problem using Prolog, you can use a depth-first search algorithm.
The Water-Jug Problem involves two jugs of different capacities and a goal to measure a specific
quantity of water using these jugs. The search space in this problem can be explored using Prolog's
backtracking mechanism, making it a suitable choice for solving it.

2. How would you test the Prolog program to ensure that it works correctly?

Ans  Testing a Prolog program to ensure it works correctly involves creating a set of test
cases that cover various aspects of the program, including different states, actions, and
potential edge cases. Here are some steps and considerations for testing the Prolog program
for the Water-Jug Problem:

1. Test the Initial State: Ensure that the program correctly initializes the jugs to the initial
state. Check if it sets the jugs to the expected capacities (e.g., small jug with 0, big jug
with 0).
2. Test the Goal State: Confirm that the program can successfully identify the goal state and
terminate when it reaches it. You should test cases where the goal amount is in either the
small or big jug or even in both.
3. Test Actions: Test each action (fill, empty, pour) separately to verify that they are
executed correctly. You can manually simulate actions and check if the state changes as
expected.
4. Test the Search Algorithm: Check if the depth-first search algorithm explores the search
space correctly and terminates with a valid solution. This includes testing various
combinations of actions to reach the goal state.
5. Test Invalid Actions: Ensure that the program handles invalid actions appropriately, such
as trying to fill a jug that is already full or emptying a jug that is already empty.
6. Test Unsolvable Cases: Try to create cases that are impossible to solve. For instance,
where the goal amount cannot be achieved with the given jug capacities.

15
Artificial Intelligence (3170716) Enrollment No:200220131124
7. Test Edge Cases: Test the program with extreme or edge
cases, such as using jugs with very large capacities or very small capacities.
8. Test Backtracking: Verify that the program backtracks correctly when it encounters a
dead-end and explores alternative paths.
9. Test Repeatability: Run the program multiple times with the same input to check if it
produces the same output consistently.
10. Performance Testing: For larger instances of the problem, test the program's performance
by measuring the time it takes to find a solution. Make sure it doesn't run into stack
overflow issues for deep search trees.

Suggested Reference:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
2. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
3. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students: (Sufficient space to be provided)


1.Prolog Tutorials on YouTube
Rubric wise marks obtained:

Problem Completeness
Knowledge Logic
Recognition and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks

16
Artificial Intelligence (3170716) Enrollment No:200220131124
Experiment No: 3

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

Date:

Competency and Practical Skills:Knowledge of logic programming

Relevant CO: CO1

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.

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.

17
Artificial Intelligence (3170716) Enrollment No:200220131124
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.

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.

18
Artificial Intelligence (3170716) Enrollment No:200220131124

Observation/Program:

class Node:
def init (self,data,level,fval):
""" Initialize the node with the data, level of the node and the calculated fvalue """
self.data = data
self.level = level
self.fval = fval

def generate_child(self):
""" Generate child nodes from the given node by moving the blank space
either in the four directions {up,down,left,right} """
x,y = self.find(self.data,'_')
""" val_list contains position values for moving the blank space in either of
the 4 directions [up,down,left,right] respectively. """
val_list = [[x,y-1],[x,y+1],[x-1,y],[x+1,y]]
children = []
for i in val_list:
child = self.shuffle(self.data,x,y,i[0],i[1])
if child is not None:
child_node = Node(child,self.level+1,0)
children.append(child_node)
return children

def shuffle(self,puz,x1,y1,x2,y2):
""" Move the blank space in the given direction and if the position value are out
of limits the return None """
if x2 >= 0 and x2 < len(self.data) and y2 >= 0 and y2 < len(self.data):
temp_puz = []
temp_puz = self.copy(puz)
temp = temp_puz[x2][y2]
temp_puz[x2][y2] = temp_puz[x1][y1]
temp_puz[x1][y1] = temp
return temp_puz
else:
return None

19
Artificial Intelligence (3170716) Enrollment No:200220131124
def copy(self,root):
""" Copy function to create a similar matrix of the given node"""
temp = []
for i in root:
t = []
for j in i:
t.append(j)
temp.append(t)
return temp

def find(self,puz,x):
""" Specifically used to find the position of the blank space """
for i in range(0,len(self.data)):
for j in range(0,len(self.data)):
if puz[i][j] == x:
return i,j

class Puzzle:
def init (self,size):
""" Initialize the puzzle size by the specified size,open and closed lists to empty """
self.n = size
self.open = []
self.closed = []

def accept(self):
""" Accepts the puzzle from the user """
puz = []
for i in range(0,self.n):
temp = input().split(" ")
puz.append(temp)
return puz

def f(self,start,goal):
""" Heuristic Function to calculate hueristic value f(x) = h(x) + g(x) """
return self.h(start.data,goal)+start.level

def h(self,start,goal):

20
Artificial Intelligence (3170716) Enrollment No:200220131124
""" Calculates the different between the given puzzles """
temp = 0
for i in range(0,self.n):
for j in range(0,self.n):
if start[i][j] != goal[i][j] and start[i][j] != '_':
temp += 1
return temp

def process(self):
""" Accept Start and Goal Puzzle state"""
print("Enter the start state matrix \n")
start = self.accept()
print("Enter the goal state matrix \n")
goal = self.accept()

start = Node(start,0,0)
start.fval = self.f(start,goal)
""" Put the start node in the open list"""
self.open.append(start)
print("\n\n")
while True:
cur = self.open[0]
print("")
print(" | ")
print(" | ")
print(" \\\'/ \n")
for i in cur.data:
for j in i:
print(j,end=" ")
print("")
""" If the difference between current and goal node is 0 we have reached the goal node"""
if(self.h(cur.data,goal) == 0):
break
for i in cur.generate_child():
i.fval = self.f(i,goal)

21
Artificial Intelligence (3170716) Enrollment No:200220131124
self.open.append(i)
self.closed.append(cur)
del self.open[0]

""" sort the opne list based on f value """


self.open.sort(key = lambda x:x.fval,reverse=False)

puz = Puzzle(3)
puz.process()

Output:

22
Artificial Intelligence (3170716) Enrollment No:200220131124

Conclusion:

In conclusion, the code offers a functional implementation of the A* algorithm for solving the 8 Puzzle
Problem. It showcases the key elements required to tackle this classic problem, making it a useful
starting point for those interested in exploring AI search algorithms and puzzle-solving in Python

Quiz: (Sufficient space to be provided for the answers)

1. How do you generate successor states in the A* algorithm for solving the 8 Puzzle Problem,
and what information do you need to calculate their f-scores?

Ans: In the A* algorithm for solving the 8 Puzzle Problem, generating successor states
involves determining the possible moves from the current state and creating new states by
applying those moves. To do this, you need to consider the following steps:

1. Find the Blank Space: Locate the position of the blank space (denoted as "0" in the 8
Puzzle) within the current state. The blank space is the only tile that can be moved in a
given move.
2. Generate Possible Moves: Determine the valid moves that can be made from the current
state. These moves include sliding tiles into the blank space, effectively swapping the
blank space with an adjacent tile.
3. Create Successor States: For each valid move, create a new state by applying the move
to the current state. This involves swapping the blank space with an adjacent tile in the
direction of the move. This results in a set of new states that represent the puzzle
configuration after each possible move.
4. Calculate F-scores for Successors: To calculate the f-scores for the successor states,
you need to consider two key components:
o G-score (Path Cost): The g-score represents the cost or distance from the initial state to
the current state. It is the total number of moves made to reach the current state. You can
maintain a dictionary or data structure that tracks the g-scores for each state in the search
process.
o Heuristic (H-score): The heuristic function estimates the cost from the current state to the
goal state. In the 8 Puzzle Problem, the commonly used heuristic is the Manhattan
distance, which calculates the sum of the horizontal and vertical distances of each tile from
its desired goal position. The heuristic is applied to each successor state to estimate the
remaining cost to reach the goal state.
o F-score (Total Estimated Cost): The f-score is calculated as the sum of the g-score and
the heuristic score (f = g + h). It represents the total estimated cost to reach the goal state
from the current state through a specific successor state. The A* algorithm prioritizes
states with lower f-scores.

For each successor state, calculate its g-score as the g-score of the current state plus 1 (since
one move is made to reach the successor state), and calculate its h-score using the heuristic
function. Then, add the g-score and h-score to compute the f-score for the successor state.

2. How does the A* algorithm decide which state to explore next in the search space, and why
is this decision important for the efficiency of the algorithm?

Ans The A* algorithm decides which state to explore next in the search space based on
a combination of two factors: the cost to reach that state from the initial state (g-score)

23
Artificial Intelligence (3170716) Enrollment No:200220131124
and the estimated cost to reach the goal state from that state
(h-score). This combined cost, known as the f-score, is used to prioritize which state to
explore next. Specifically, A* selects the state with the lowest f-score to explore next.
The decision-making process is crucial for the efficiency of the algorithm, and here's
why:

1. Efficiency and Optimality: A* is an informed search algorithm, and its goal is to find the
optimal path to the goal state while efficiently navigating the search space. By
considering both the g-score (the cost incurred so far) and the h-score (the estimated
remaining cost), A* can efficiently explore states that are likely to lead to the shortest
path to the goal. This optimality is guaranteed as long as the heuristic used is admissible
(it never overestimates the true cost).
2. Guidance Towards Promising States: A* prioritizes states with lower f-scores. This
prioritization ensures that states with a high likelihood of leading to the goal state are
explored first. It guides the search away from less promising areas of the search space,
potentially avoiding unnecessary exploration of suboptimal paths.
3. Reduction of Search Space: By focusing on states with low f-scores, A* efficiently
narrows down the search space, exploring the most relevant states first. This reduction in
search space results in significant time and memory savings, especially in large and
complex problem domains.
4. Avoidance of Unproductive Paths: When A* encounters a state with a low f-score, it's
more likely to find the optimal solution by exploring paths that lead to that state.
Conversely, states with high f-scores are explored later or not at all if a better path is
already found. This helps avoid the exploration of unproductive paths that may not lead
to the optimal solution.
5. Balancing Exploration and Exploitation: A* efficiently balances exploration (finding
new states) and exploitation (finding the optimal solution) by considering both the past
cost (g-score) and the expected future cost (h-score). This balance ensures that the
algorithm explores a variety of paths but ultimately converges on the optimal solution.
6. Real-Time Search: In real-time applications or dynamic environments, A* can
dynamically adapt its exploration based on changing conditions. It can adjust its priority
queue as new information becomes available, further improving its efficiency.

Suggested References:
1. http://lpn.swi-prolog.org/lpnpage.php?pageid=online
2. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
3. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students: (Sufficient space to be provided)


1. Prolog Tutorials on YouTube
2. geeksforgeeks
Rubric wise marks obtained:

Completeness
Knowledge Logic
and accuracy Ethics (2)
Rubrics (2) Building (2) Total
(2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

24
Artificial Intelligence (3170716) Enrollment No:200220131124
*
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:

Competency and Practical Skills:Understanding of basics of semantic Net.

Relevant CO: CO2

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

25
Artificial Intelligence (3170716) Enrollment No:200220131124
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.

This representation consists of mainly two types of relations:


IS-A relation (Inheritance)
Kind-of-relation

Safety and necessary Precautions:

When creating a semantic net, it is important to avoid ambiguity by using clear and
concise notations. Ambiguity can lead to confusion and misinterpretation of the net.

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:

To represent the given Prolog predicates as a Semantic Network, we can use a graph-based
representation where nodes represent entities and relationships are represented by labeled edges.
Here's how the predicates can be converted into a Semantic Network:

1. **Entities**:
- "tom"
- "cat1"
- "mat1"
- "bird1"
- "mat1"
- "john"
- "ginger"

2. **Relationships**:
- `cat(tom)` can be represented as a "is-a" relationship between "tom" and "cat."
- `cat(cat1)` can be be represented as a "is-a" relationship between "cat1" and "cat."
- `mat(mat1)` can be represented as a "is-a" relationship between "mat1" and "mat."
- `sat_on(cat1, mat1)` can be represented as a "sits-on" relationship between "cat1" and
"mat1."
- `bird(bird1)` can be represented as a "is-a" relationship between "bird1" and "bird."
- `caught(tom, bird1)` can be represented as a "caught" relationship between "tom" and
"bird1."
- `like(X, cream) :- cat(X)` can be represented as a "likes" relationship between entities
that satisfy `X` and "cream."
- `mammal(X) :- cat(X)` can be represented as a "is-a" relationship between entities that
satisfy `X` and "mammal."
- `has(X, fur) :- mammal(X)` can be represented as a "has" relationship between entities
that satisfy `X` and "fur."
26
Artificial Intelligence (3170716) Enrollment No:200220131124
- `animal(X) :- mammal(X)` can be represented as a "is-a"
relationship between entities that satisfy `X` and "animal."
- `animal(X) :- bird(X)` can be represented as a "is-a" relationship between entities that
satisfy `X` and "animal."
- `owns(john, tom)` can be represented as an "owns" relationship between "john" and
"tom."
- `is_coloured(tom, ginger)` can be represented as a "is-colored" relationship between
"tom" and "ginger."

Conclusion:

In the Semantic Network representation, each entity is a node, and each relationship is an edge between
nodes with appropriate labels. This representation captures the knowledge and relationships described in the
original Prolog predicates in a graphical format.

Quiz: (Sufficient space to be provided for the answers)

1. What is the advantage of using Semantic Nets for knowledge representation?

Ans  Graphical Representation: Semantic networks use a graph-based structure, which is


intuitive and easily understandable. This graphical representation makes it accessible for both
humans and machines to visualize and interpret knowledge.

 Expressiveness: Semantic networks are highly expressive and flexible, allowing complex
relationships and hierarchies to be represented. They can capture various types of knowledge,
such as concepts, entities, attributes, and relationships, in a natural and rich way.

 Hierarchical Structure: Semantic networks support hierarchical organization, enabling the


modeling of taxonomies or ontologies. This hierarchical structure allows for the representation
of categories, subclasses, and superclasses, making it easier to understand and navigate
complex knowledge domains.

 Efficient Querying: Retrieving information from a semantic network is generally efficient.


The graph structure allows for efficient traversal and querying, which is valuable for tasks like
information retrieval, reasoning, and decision support.

 Inference and Reasoning: Semantic networks can be used for inference and reasoning.
They allow for the representation of rules and logical relationships, making it possible to
deduce new information or validate existing knowledge.

 Integration of Multimodal Information: Semantic networks can integrate information


from various modalities, including text, images, and audio. This makes them suitable for
applications that involve multimedia data.

 Interoperability: Semantic networks can be used as a common language for knowledge


representation, promoting interoperability between different systems and domains. This is
especially important in fields like the Semantic Web.

27
Artificial Intelligence (3170716) Enrollment No:200220131124
 Ease of Maintenance and Updates: Semantic networks are
relatively easy to update and maintain. When new information needs to be added or existing
knowledge is revised, changes can be made to the network structure without a complete
overhaul.

 Simplification of Complex Domains: In complex domains, semantic networks can simplify


the representation of knowledge by breaking it down into manageable components. This
simplification aids in problem-solving and decision-making.

 Natural Language Understanding: Semantic networks align well with natural language
understanding. They can represent linguistic elements, concepts, and relationships, which is
beneficial for tasks involving language processing and understanding.

2. What is the IS-A relation in a Semantic Net?


AnsThe "IS-A" relation, often referred to as the "is-a" link or "is-a" relationship, is a fundamental
concept in Semantic Networks, particularly in knowledge representation and ontology systems. It
signifies a type of hierarchical relationship that represents how one entity or concept is a member or
instance of a broader, more general category or class
Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students: (Sufficient space to be provided)


Prolog Tutorials on YouTube

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

28
Artificial Intelligence (3170716) Enrollment No:200220131124
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:

Competency and Practical Skills:Understanding of basics of Knowledge Represenation.

Relevant CO: CO2

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.

29
Artificial Intelligence (3170716) Enrollment No:200220131124
MTRANS
-- Transfer of mental information. e.g. tell.
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
30
Artificial Intelligence (3170716) Enrollment No:200220131124
f
-- 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.

Observation/Program:

Conceptual Dependency (CD) is a theory for representing the meaning of natural language
sentences or statements in a structured format. CD represents actions, objects, and relationships
between them. Here's how you can construct CD structures for the given sentences:

31
Artificial Intelligence (3170716) Enrollment No:200220131124
1. John gives Mary a book:
o Agent: John
o Action: gives
o Recipient: Mary
o Theme: a book

In CD notation, this would look like:

[Agent: John] [Action: gives] [Recipient: Mary] [Theme: a book]

2. John gave Mary the book yesterday:


o Agent: John
o Action: gave
o Recipient: Mary
o Theme: the book
o Time: yesterday

In CD notation, this would look like:

[Agent: John] [Action: gave] [Recipient: Mary] [Theme: the book] [Time:
yesterday]

Conclusion:

These CD structures represent the core elements of the sentences and their relationships. They capture
the key concepts, actions, and temporal information in the given statements. The CD notation is a way to
break down natural language statements into a more formal and structured representation, making it easier
to analyze and process their meaning.

Quiz: (Sufficient space to be provided for the answers)

1. What is the purpose of a Conceptual Dependency diagram?


Ans The purpose of a Conceptual Dependency (CD) diagram is to provide a structured
and graphical representation of the meaning of a natural language sentence or statement.
Conceptual Dependency is a theory used in artificial intelligence and computational
linguistics to capture the essential semantic components of a sentence in a formalized and
standardized format.

2. How can Conceptual Dependency be used in natural language processing?


Ans The Conceptual Dependency framework is used for a natural language parser by
reversing the realization rules and using the semantics as a check with reality. The system
for analyzing a sentence into its con- ceptual representation operates on pieces of a
sentence looking up the potential conceptual realizates.

3. Can a Conceptual Dependency primitive be further decomposed?

Ans Yes, Conceptual Dependency (CD) primitives can be further decomposed into
more primitive concepts or actions. CD primitives represent the basic building blocks of

32
Artificial Intelligence (3170716) Enrollment No:200220131124
meaning in a sentence, and sometimes it is necessary to
break them down into smaller components to represent more fine-grained concepts and
relationships. This decomposition can be particularly valuable in complex sentences or
when detailed semantic analysis is required. Here's an example:

Consider the CD primitive: "Agent-Action-Object."

 Agent: Represents the entity or concept that performs the action.


 Action: Represents the action or verb.
 Object: Represents the entity or concept that is acted upon.

This is a basic CD primitive structure, but it can be decomposed further to capture more
detailed information:

 Agent can be decomposed into more specific information, such as "Agent-Role," where
the role of the agent is specified (e.g., "Agent-Patient" to indicate that the agent is the
recipient of the action).
 Action can be decomposed into more specific actions or verb modifiers, such as
"Action-Tense" (indicating the tense of the action, e.g., past, present, future) and
"Action-Modality" (indicating the modality of the action, e.g., possibility, necessity).
 Object can be decomposed into more specific object attributes, such as "Object-
Attribute" (indicating the attribute or quality of the object, e.g., color, size) or "Object-
Location" (indicating the location of the object).

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. “PROLOG Programming For Artificial Intelligence” -By Ivan Bratko( Addison-Wesley)

References used by the students: (Sufficient space to be provided)

Rubric wise marks obtained:

Problem Understandi Completeness


Knowledge
Recognition ng and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

33
Artificial Intelligence (3170716) Enrollment No:200220131124

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

Date:

Competency and Practical Skills:


Basic knowledge of Python programming language, Familiarity with the rules of tic-tac-toe game,
including the board layout and winning conditions.
Understanding of the Minimax algorithm, which is a decision-making algorithm.

Relevant CO: CO3

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.

Safety and necessary Precautions:

Handle edge cases such as invalid moves, repeated moves, and game-ending conditions to avoid
program crashes or incorrect results.

34
Artificial Intelligence (3170716) Enrollment No:200220131124
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:

#This function is used to draw the board's current state every time the user turn arrives.
def ConstBoard(board):
print("Current State Of Board : \n\n");
for i in range (0,9):
if((i>0) and (i%3)==0):
print("\n");
if(board[i]==0):
print("- ",end=" ");
if (board[i]==1):
print("O ",end=" ");
if(board[i]==-1):
print("X ",end=" ");
print("\n\n");

#This function takes the user move as input and make the required changes on the board.
def User1Turn(board):
pos=input("Enter X's position from [1...9]: ");
pos=int(pos);
if(board[pos-1]!=0):
print("Wrong Move!!!");
exit(0) ;
board[pos-1]=-1;

def User2Turn(board):
pos=input("Enter O's position from [1...9]: ");
pos=int(pos);
if(board[pos-1]!=0):
print("Wrong Move!!!");
exit(0);
board[pos-1]=1;

#MinMax function.
def minimax(board,player):
x=analyzeboard(board);
if(x!=0):
return (x*player);
pos=-1;
value=-2;

35
Artificial Intelligence (3170716) Enrollment No:200220131124
for i in range(0,9):
if(board[i]==0):
board[i]=player;
score=-minimax(board,(player*-1));
if(score>value):
value=score;
pos=i;
board[i]=0;

if(pos==-1):
return 0;
return value;

#This function makes the computer's move using minmax algorithm.


def CompTurn(board):
pos=-1;
value=-2;
for i in range(0,9):
if(board[i]==0):
board[i]=1;
score=-minimax(board, -1);
board[i]=0;
if(score>value):
value=score;
pos=i;

board[pos]=1;

#This function is used to analyze a game.


def analyzeboard(board):
cb=[[0,1,2],[3,4,5],[6,7,8],[0,3,6],[1,4,7],[2,5,8],[0,4,8],[2,4,6]];

for i in range(0,8):
if(board[cb[i][0]] != 0 and
board[cb[i][0]] == board[cb[i][1]] and
board[cb[i][0]] == board[cb[i][2]]):
return board[cb[i][2]];
return 0;

#Main Function.
def main():
choice=input("Enter 1 for single player, 2 for multiplayer: ");
choice=int(choice);
#The broad is considered in the form of a single dimentional array.
#One player moves 1 and other move -1.

36
Artificial Intelligence (3170716) Enrollment No:200220131124
board=[0,0,0,0,0,0,0,0,0];
if(choice==1):
print("Computer : O Vs. You : X");
player= input("Enter to play 1(st) or 2(nd) :");
player = int(player);
for i in range (0,9):
if(analyzeboard(board)!=0):
break;
if((i+player)%2==0):
CompTurn(board);
else:
ConstBoard(board);
User1Turn(board);
else:
for i in range (0,9):
if(analyzeboard(board)!=0):
break;
if((i)%2==0):
ConstBoard(board);
User1Turn(board);
else:
ConstBoard(board);
User2Turn(board);

x=analyzeboard(board);
if(x==0):
ConstBoard(board);
print("Draw!!!")
if(x==-1):
ConstBoard(board);
print("X Wins!!! Y Loose !!!")
if(x==1):
ConstBoard(board);
print("X Loose!!! O Wins !!!!")

# #
main()
# #

37
Artificial Intelligence (3170716) Enrollment No:200220131124

OUTPUT:

Conclusion:

Minimax is a decision rule used in decision theory, game theory, statistics and philosophy for minimizing
the possible loss for a worst case (maximum loss) scenario. Originally formulated for two-player zero-sum
game theory, covering both the cases where players take alternate moves and those where they make
simultaneous moves, it has also been extended to more complex games and to general decision making in
the presence of uncertainty.

38
Artificial Intelligence (3170716) Enrollment No:200220131124

Quiz: (Sufficient space to be provided for the answers)

1. How can you optimize the Minimax algorithm to improve its performance in Tic Tac
Toe?

Ans Optimizing the Minimax algorithm for Tic Tac Toe can significantly improve its
performance and reduce the computational overhead. Here are several techniques and
strategies to enhance the efficiency of the Minimax algorithm in Tic Tac Toe:

1. Alpha-Beta Pruning: Implement the Alpha-Beta pruning technique, which reduces the
number of nodes explored in the game tree. Alpha-Beta pruning eliminates branches of
the tree that cannot lead to better outcomes, thus saving computation time. This
optimization can dramatically reduce the search space in the minimax tree.
2. Move Ordering: Prioritize evaluating moves that are likely to be more promising. For
example, starting with the center square and then the corners is a good heuristic because
they often lead to stronger positions. This minimizes the depth of the search tree.
3. Transposition Tables: Use transposition tables to store previously computed board
states and their corresponding minimax values. This allows for caching and retrieving
results for known positions, saving computational effort.
4. Iterative Deepening: Employ an iterative deepening approach, where you explore the
game tree to increasing depths, starting with shallow searches and gradually increasing
depth. This helps in cutoff decisions and provides better move ordering information.
5. Heuristic Evaluation Function: Develop a strong heuristic evaluation function that
can quickly estimate the value of a board state without fully exploring the tree. This can
be used for ordering moves and for cutoffs in the minimax search.
6. Opening Databases: For the initial moves in the game, you can use opening databases
(also known as opening books) that provide precomputed responses for common opening
sequences. This can save significant computational resources.
7. Parallelization: Utilize parallel processing or multi-threading to explore different
branches of the game tree simultaneously. This can lead to substantial speed
improvements on multi-core processors.
8. Bitboard Representation: If you're implementing Tic Tac Toe on a computer, using a
bitboard representation can further optimize operations like checking for winning
conditions and legal moves. Bitboard is especially useful for larger games like chess, but
it can still speed up calculations in Tic Tac Toe.
9. Endgame Tables: For the endgame, consider using precomputed endgame tables that
store perfect play sequences and outcomes for all possible endgame board states. This
can be faster than running the minimax algorithm in the late game.
10. Dynamic Depth: You can dynamically adjust the depth of the minimax search
based on the remaining time or available computational resources. Deeper searches can
be performed when more resources are available, and shallower searches can be used to
maintain real-time performance.

2. Can the Minimax algorithm be used for games other than Tic Tac Toe? If so, what are
some examples?

Ans Yes, the Minimax algorithm can be used for a wide range of two-player, zero-sum
games beyond Tic Tac Toe. The Minimax algorithm is a fundamental approach for making
optimal decisions in adversarial games where two players take turns, and the outcome for

39
Artificial Intelligence (3170716) Enrollment No:200220131124
one player is a loss that directly benefits the other player. Here
are some examples of games where Minimax can be applied:

1. Chess: Minimax with alpha-beta pruning is used to evaluate board positions in chess.
Chess engines employ sophisticated evaluation functions and heuristic techniques to
search for optimal moves.
2. Checkers (Draughts): Similar to chess, the Minimax algorithm is used to analyze and
make optimal moves in checkers.
3. Connect Four: A two-player connection game, Minimax can be used to determine the
best moves in Connect Four.
4. Othello (Reversi): Minimax with alpha-beta pruning can be applied to Othello, where
players take turns placing discs and trying to capture their opponent's discs.
5. Go: While traditional Minimax is not practical for Go due to the enormous branching
factor, variants like Monte Carlo Tree Search (MCTS) are used to make informed
decisions in the game.
6. Hex: A connection game where players attempt to create a path connecting two sides of a
hexagonal board, Minimax can be used to evaluate game positions.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)


1. GEU,DEHRADUN

Rubric wise marks obtained:

Problem Completeness
Knowledge Logic
Recognition and accuracy Ethic (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

40
Artificial Intelligence (3170716) Enrollment No:200220131124
Experiment No: 7
Implement Bayesian Networks algorithm for the Monty Hall Problem using any
programming Language.

Date:

Competency and Practical Skills:Understanding of Bayesian Networks.


Familiarity with the Monty Hall problem, which is a classic probability puzzle that involves three
doors and a prize.
Knowledge of probability theory, including conditional probability and Bayes' theorem.
Familiarity with a programming language

Relevant CO: CO4

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
41
Artificial Intelligence (3170716) Enrollment No:200220131124
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.

 Safety and necessary Precautions:

Ensure that the algorithm produces accurate results, it is important to validate the input data
to ensure that it is consistent and complete.

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:

from pgmpy.models import BayesianNetwork


from pgmpy.factors.discrete import TabularCPD

# Create a Bayesian Network for the Monty Hall Problem


monty_hall_model = BayesianNetwork([('Prize', 'Monty', 'Choice')])

# Define the Conditional Probability Distributions (CPDs)


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

cpd_choice = TabularCPD(variable='Choice', variable_card=3, values=[[1/3, 1/3, 1/3]])

# Monty's choice depends on both the prize and the contestant's choice
cpd_monty = TabularCPD(variable='Monty', variable_card=3,
values=[[0, 0, 0, 0, 0.5, 1, 0, 1, 0.5],
[0.5, 0, 1, 0, 0, 0, 0.5, 0, 0.5],
[0.5, 1, 0, 1, 0.5, 0, 0.5, 0, 0]],
evidence=['Prize', 'Choice'], evidence_card=[3, 3])

# Add CPDs to the model


monty_hall_model.add_cpds(cpd_prize, cpd_choice, cpd_monty)

# Check the model for consistency


assert monty_hall_model.check_model()

# Doing exact inference using Variable Elimination


from pgmpy.inference import VariableElimination
infer = VariableElimination(monty_hall_model)

42
Artificial Intelligence (3170716) Enrollment No:200220131124
# Compute the probability of winning if the contestant initially
chooses door 1 and stays
probability_stay = infer.query(variables=['Prize'], evidence={'Choice': 1},
show_progress=False)
print("Probability of winning if staying with the initial choice:", probability_stay.values[0])

# Compute the probability of winning if the contestant initially chooses door 1 and switches
probability_switch = infer.query(variables=['Prize'], evidence={'Choice': 1, 'Monty': 2},
show_progress=False)
print("Probability of winning if switching the choice:", probability_switch.values[0])

Output:

Conclusion:

In the Monty Hall Problem, if the contestant stays with their initial choice (e.g., door 1), the probability of
winning is approximately 1/3. However, if the contestant switches their choice after Monty reveals a door
(e.g., switching to door 3), the probability of winning increases to approximately 2/3. This result
demonstrates the advantage of switching in the Monty Hall Problem.

Quiz: (Sufficient space to be provided for the answers)

1. What is inference in a Bayesian Network?

Ans Inference in a Bayesian Network is the process of using the network's structure and
probability distributions to draw conclusions or make predictions about the variables in the
network. It's a fundamental operation in probabilistic graphical models like Bayesian
Networks and plays a crucial role in various applications, including decision-making,
reasoning under uncertainty, and probabilistic modeling.

2. What are some applications of Bayesian Networks?

Ans Bayesian Networks have a wide range of applications in various fields due to their
ability to model and reason under uncertainty, making them valuable for decision-making,
prediction, and probabilistic modeling. Here are some key applications of Bayesian
Networks:

1. Medical Diagnosis: Bayesian Networks are used to assist doctors in diagnosing diseases
based on symptoms, test results, and patient history. They can provide probabilistic
assessments of various diseases.
2. Risk Assessment: In finance and insurance, Bayesian Networks help assess and manage
risks. They can model the likelihood of financial events such as defaults, fraud, or market
crashes.
3. Natural Language Processing: Bayesian Networks are used in language modeling,
speech recognition, and machine translation. They help in disambiguating word senses and
predicting the next word in a sentence.

43
Artificial Intelligence (3170716) Enrollment No:200220131124
4. Image and Video Analysis: They are used in image
recognition, video surveillance, and object tracking. Bayesian Networks can model the
uncertainty associated with image features and object locations.
5. Quality Control and Anomaly Detection: In manufacturing, Bayesian Networks are used
to monitor and control product quality. They can identify defects and anomalies in production
processes.
6. Environmental Modeling: Bayesian Networks are applied in environmental science to
model complex systems, such as ecological networks, climate models, and pollutant
dispersion.
7. Fraud Detection: They help detect fraudulent activities in financial transactions,
insurance claims, and online transactions by modeling normal and anomalous behavior.
8. Recommendation Systems: Bayesian Networks are used in recommendation engines to
provide personalized recommendations for products, movies, or content based on user
preferences and behavior.
9. Genomic Analysis: In bioinformatics, Bayesian Networks are used to model gene
regulatory networks, identify genetic markers, and make predictions about diseases based on
genetic data.
10. Criminal Justice: Bayesian Networks can assist in criminal investigations, profiling, and
court decision support by modeling evidence, witnesses, and suspects.

Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Machine Learning with Python for Everyone, Mark Fenner, Pearson
3. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
4. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)

1. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley

Rubric wise marks obtained:

Problem Logic Completeness


Knowledge
Recognition Building and accuracy Ethics (2)
Rubrics (2) Total
(2) (2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

44
Artificial Intelligence (3170716) Enrollment No:200220131124
Experiment No: 8
Demonstrate Connectionist Model using Tool.

Date:

Competency and Practical Skills:

Familiarity with neural networks, which are computational models inspired by the structure and
function of the brain.
Familiarity with a neural network tool.

Relevant CO: CO4

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.

45
Artificial Intelligence (3170716) Enrollment No:200220131124

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.

Safety and necessary Precautions:


Different tools are designed for different tasks, and it's crucial to use a tool that is
appropriate for the task at hand.
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 tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers

# Load the MNIST dataset


mnist = keras.datasets.mnist

46
Artificial Intelligence (3170716) Enrollment No:200220131124
(train_images, train_labels), (test_images, test_labels) =
mnist.load_data()
# Normalize the pixel values to be between 0 and 1
train_images, test_images = train_images / 255.0, test_images / 255.0

# Create a feedforward neural network


model = keras.Sequential([
layers.Flatten(input_shape=(28, 28)), # Flatten the 28x28 images to a 1D array
layers.Dense(128, activation='relu'), # Fully connected layer with ReLU activation
layers.Dropout(0.2), # Dropout layer for regularization
layers.Dense(10, activation='softmax') # Output layer with 10 classes (digits 0-9)
])
# Compile the model
model.compile(optimizer='adam', # Optimization algorithm
loss='sparse_categorical_crossentropy', # Loss function for classification
metrics=['accuracy']) # Metric to monitor during training

# Train the model


model.fit(train_images, train_labels, epochs=5)
# Evaluate the model on the test data
test_loss, test_acc = model.evaluate(test_images, test_labels)
print("Test accuracy:", test_acc)

Output:

Conclusion:
This connectionist model demonstrates the basic steps of building and training a neural
network for a classification task. Connectionist models are widely used for a variety of
machine learning tasks, including image recognition, natural language processing, and more.

Quiz: (Sufficient space to be provided for the answers)

1. What is the role of the activation function in a connectionist model?

Ans The activation function in a connectionist model (such as a neural network) serves a
crucial role in introducing non-linearity to the model. It is applied to the weighted sum of

47
Artificial Intelligence (3170716) Enrollment No:200220131124
inputs at each neuron or unit in a neural network. The primary
purposes and roles of activation functions are as follows:

1. Introduction of Non-Linearity: The most fundamental role of activation functions is to


introduce non-linearity to the model. Without non-linearity, neural networks would reduce
to linear models, and they would not be capable of learning complex patterns in the data.
Non-linearity allows neural networks to approximate and model complex, non-linear
relationships in data.
2. Learning Complex Patterns: Non-linear activation functions enable neural networks to
learn and represent complex, hierarchical features and patterns in data. This is particularly
important for tasks like image recognition, natural language processing, and other complex
problems where linear models would be inadequate.
3. Approximation of Arbitrary Functions: Neural networks with non-linear activation
functions have the universal approximation property, which means they can approximate
arbitrary functions. This makes them versatile for various tasks, from function
approximation to classification and regression.
4. Feature Abstraction: Activation functions help the network abstract features from the
input data. By transforming the input data through non-linear functions, neural networks
can identify and extract relevant features, making them robust to variations and noise in
the data.
5. Gradient Descent: Activation functions are critical for backpropagation and gradient
descent, which are the training mechanisms for neural networks. The non-linearity
introduced by activation functions ensures that gradients can flow backward through the
network, allowing the model to learn from the data.

2. What is the purpose of testing a connectionist model?

Ans Testing a connectionist model, such as a neural network, serves several important
purposes in the context of machine learning and model development:

1. Model Performance Evaluation: The primary purpose of testing a connectionist model is


to evaluate its performance. Testing helps assess how well the model generalizes from the
training data to new, unseen data. This evaluation is crucial for understanding how
effective the model is in making predictions or classifications.
2. Generalization Assessment: Testing allows you to measure the model's ability to
generalize. A good model should perform well not only on the training data but also on
data it has never encountered before. Testing provides insights into the model's ability to
handle unseen variations and real-world data.
3. Overfitting Detection: Testing helps identify overfitting, a common problem in machine
learning. Overfitting occurs when a model performs well on the training data but poorly on
new data because it has memorized the training data rather than learning the underlying
patterns. Testing helps detect if overfitting is occurring.
4. Hyperparameter Tuning: Testing is used to tune model hyperparameters, such as
learning rates, batch sizes, and the architecture of the network. By testing the model with
different hyperparameter configurations, you can find the best settings that maximize
performance.
5. Comparing Models: Testing allows for the comparison of different models or variations
of the same model. You can test multiple models and choose the one that performs best for
the specific task.
6. Error Analysis: Testing provides an opportunity for error analysis. By examining
misclassified or mispredicted examples, you can gain insights into the types of errors the
model makes and potentially identify areas for model improvement or data preprocessing.

48
Artificial Intelligence (3170716) Enrollment No:200220131124
7. Assessment of Robustness: Testing helps assess the model's
robustness to noise and uncertainty in the data. A robust model should perform reasonably
well even when the data contains noise or missing values.
8. Validation of Model Assumptions: Testing can validate whether the model's assumptions
about the data are reasonable. If the model is designed based on certain assumptions,
testing can confirm if those assumptions hold in practice.
9. Deployment Readiness: Before deploying a model in real-world applications, it must
undergo thorough testing to ensure it meets the required performance standards. Testing
helps in determining whether the model is ready for deployment.
10. Ethical and Fairness Considerations: Testing is essential for identifying and addressing
issues related to model bias, fairness, and ethical concerns. It allows for assessing whether
the model exhibits bias or makes unfair predictions across different demographic groups.

3. What is back propagation in a connectionist model?


Ans Backpropagation, short for "backpropagation of errors," is a fundamental algorithm for
training connectionist models, particularly artificial neural networks (ANNs). It is a supervised
learning algorithm used to adjust the model's parameters (weights and biases) in order to minimize
the error between the predicted output and the actual target values. Backpropagation is a crucial
component of training neural networks and plays a central role in enabling the network to learn from
data.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

References used by the students: (Sufficient space to be provided)


1. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley

Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks

49
Artificial Intelligence (3170716) Enrollment No:200220131124

Experiment No: 9
Implement Genetic Algorithm in any Programming Language.

Date:

Competency and Practical Skills:

Understanding of genetic algorithms, which are a class of optimization algorithms that are
inspired by the principles of natural selection and genetics.
Knowledge of a programming language

Relevant CO: CO4

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

50
Artificial Intelligence (3170716) Enrollment No:200220131124

Safety and necessary Precautions:

It is important to define clear objectives and constraints for the optimization problem.
It is crucial to validate the fitness function.

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 target binary string


target = "1101010101"

# Genetic algorithm parameters


population_size = 100
mutation_rate = 0.01

def initialize_population(pop_size):
return [''.join(random.choice("01") for _ in range(len(target))) for _ in range(pop_size)]

def fitness(individual):
return sum(1 for i, j in zip(individual, target) if i == j)

def select_parents(population):
return random.choices(population, k=2, weights=[fitness(ind) for ind in population])

def crossover(parent1, parent2):


point = random.randint(1, len(target) - 1)
return parent1[:point] + parent2[point:]

def mutate(individual, mutation_rate):


return ''.join(bit if random.random() > mutation_rate else random.choice("01") for bit in
individual)

# Main Genetic Algorithm


population = initialize_population(population_size)

51
Artificial Intelligence (3170716) Enrollment No:200220131124
generation = 1

while True:
population = sorted(population, key=fitness, reverse=True)
best_fit = fitness(population[0])
print(f"Generation {generation}, Best Fitness: {best_fit}, Best Individual: {population[0]}")

if best_fit == len(target):
print("Target achieved!")
break

new_population = [population[0]]

while len(new_population) < population_size:


parent1, parent2 = select_parents(population)
child = crossover(parent1, parent2)
child = mutate(child, mutation_rate)
new_population.append(child)

population = new_population
generation += 1

Output:

Conclusion:
This example provides a simplified illustration of a genetic algorithm. Real-world applications may involve
more complex representations, selection mechanisms, and crossover/mutation strategies

Quiz: (Sufficient space to be provided for the answers)

1. What are the genetic operators that will be used to create new individuals in each
generation? Will you use crossover, mutation, or both?

Ans In the provided genetic algorithm implementation, both crossover and mutation
operators are used to create new individuals in each generation. These are two fundamental
genetic operators that play a key role in the evolution of the population.

1. Crossover (Recombination):
o Crossover is a genetic operator that combines genetic information from two parent
individuals to create one or more offspring.

52
Artificial Intelligence (3170716) Enrollment No:200220131124
oIn the code, the crossover function combines two
parents' binary strings by selecting a random crossover point and creating a child
by combining the portions of the parents before and after the crossover point.
o Crossover introduces the recombination of genetic material and allows for the
exploration of different combinations of genes. It promotes diversity in the
population and helps share advantageous traits.
2. Mutation:
o Mutation is a genetic operator that introduces small, random changes in an
individual's genetic material.
o In the code, the mutate function randomly flips individual bits in the binary string
with a specified mutation rate.
o Mutation is a source of genetic diversity and can introduce novel traits or correct
errors in the population. It serves as a mechanism for exploring the solution space.

2. How will you evaluate the fitness of each individual in the population? Will you evaluate
them sequentially or in parallel?

Ans: The evaluation of the fitness of each individual in the population is a crucial step in a
genetic algorithm. Fitness evaluation measures how well each individual solves the
problem or how close it is to an optimal solution. The specific approach to fitness
evaluation can vary depending on the problem and computational resources. Here are
some considerations:

1. Fitness Function: The choice of a fitness function depends on the problem being
solved. It should quantify the quality of the solution provided by an individual. In some
cases, the fitness function could be a simple mathematical function, while in others, it
might involve complex simulations or real-world data.

2. Sequential vs. Parallel Evaluation: The decision to evaluate individuals sequentially


or in parallel depends on the computational resources available and the nature of the
fitness evaluation.

 Sequential Evaluation: In cases where the fitness evaluation is computationally


inexpensive and can be performed relatively quickly, sequential evaluation may be
suitable. Each individual is evaluated one after the other, and the process continues until
all individuals are evaluated.
 Parallel Evaluation: In situations where fitness evaluation is computationally intensive
or requires processing a large dataset, parallel evaluation may be more efficient.
Parallelism can be achieved using multiple processors, threads, or distributed computing.
This can significantly speed up the evaluation process, especially in large-scale
applications.
 Hybrid Approaches: In some cases, a hybrid approach may be used, where individuals
are evaluated in parallel using available resources, but the remaining evaluations are
performed sequentially.

It's important to note that the choice between sequential and parallel evaluation can significantly
impact the efficiency of the genetic algorithm. In practice, the evaluation method should be
selected based on the problem's characteristics, the available hardware resources, and the trade-off
between computational cost and algorithm speed.

53
Artificial Intelligence (3170716) Enrollment No:200220131124

3. What is the stopping criterion for the genetic algorithm? Will you stop when a certain
fitness level is reached, after a certain number of generations, or when the algorithm
converges?

Ans The choice of a stopping criterion for a genetic algorithm depends on the specific
problem, available computational resources, and the desired behavior of the algorithm.
Common stopping criteria include:

1. Fixed Number of Generations: In some cases, a genetic algorithm is run for a


predetermined number of generations. This is a simple and widely used stopping criterion.
Once the specified number of generations is reached, the algorithm terminates, regardless
of the fitness level achieved. This approach is suitable when there is no prior knowledge of
the expected fitness level.
2. Convergence: Convergence-based stopping criteria are used when the algorithm is
expected to converge to an optimal solution. The algorithm monitors the progress of the
best fitness value over successive generations. If there is little or no improvement in the
best fitness value for a certain number of generations or if it reaches a plateau, the
algorithm can be stopped. Convergence criteria help prevent unnecessary computation
when the algorithm has likely reached its best possible solution.
3. Target Fitness Level: In some cases, the genetic algorithm is terminated once a specific
fitness level is reached or surpassed. This criterion is used when there is prior knowledge
of the expected fitness level required to solve the problem. When the best individual in the
population achieves or exceeds this target fitness, the algorithm stops.
4. Resource Limitations: Stopping criteria can also be based on resource limitations, such as
a maximum time limit or available memory. If the algorithm has limited computational
resources, it may stop after a certain amount of time has elapsed, even if convergence has
not been achiev.

Suggested References:
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. Neural Networks, Fuzzy Logic, and Genetic Algorithms: Synthesis and Applications By
S. Rajshekharan, G. A. Vijayalakshmi Pai, PHI
3. Machine Learning with Python for Everyone, Mark Fenner, Pearson
4. Machine Learning, Anuradha Srinivasaraghavan, Vincy Joseph, Wiley
5. Machine Learning with Python, U Dinesh Kumar Manaranjan Pradhan, Wiley
References used by the students: (Sufficient space to be provided)
1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Rubric Recognition Building Ethics (2) Tota
(2) (2)
s (2) (2) l
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)

Marks

54
Artificial Intelligence (3170716) Enrollment No:200220131124
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

Relevant CO: CO5

Objectives:Understand the basic data structure for lists


Learn basic list operations

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.

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

55
Artificial Intelligence (3170716) Enrollment No:200220131124
to be a list.

Basic Operations on Lists

Following table contains various operations on prolog lists –

Operations Definition

Membership During this operation, we can verify whether a given element is member of
Checking 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.

Safety and necessary Precautions:

The program should handle exceptions, such as input errors or invalid operations.

Procedure:

1. Define the Structure of List in Prolog.


2. Perform Different List operations.

Observation/Program:

Code:
% Predicate to find the length of a list.
list_length([], 0).
list_length([_|Rest], Length) :- list_length(Rest, SubLength), Length is SubLength + 1.

% Predicate to sum all numbers in a list.


list_sum([], 0).
list_sum([Head|Tail], Sum) :- list_sum(Tail, TailSum), Sum is Head + TailSum.

% Predicate to check if an element is a member of a list.


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

% Predicate to append two lists.


append_lists([], List, List).
append_lists([Head|Rest1], List2, [Head|Result]) :- append_lists(Rest1, List2, Result).

% Predicate to reverse a list.

56
Artificial Intelligence (3170716) Enrollment No:200220131124
reverse_list(List, Reversed) :- reverse_list(List, [], Reversed).
reverse_list([], Reversed, Reversed).
reverse_list([Head|Rest], Acc, Reversed) :- reverse_list(Rest, [Head|Acc], Reversed).

% Predicate to find the last element of a list.


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

% Predicate to delete the first occurrence of an element from a list.


delete_first(_, [], []).
delete_first(X, [X|Rest], Rest).
delete_first(X, [Y|Rest], [Y|Result]) :- delete_first(X, Rest, Result).

% Predicate to delete every occurrence of an element from a list.


delete_all(_, [], []).
delete_all(X, [X|Rest], Result) :- delete_all(X, Rest, Result).
delete_all(X, [Y|Rest], [Y|Result]) :- X \= Y, delete_all(X, Rest, Result).

% Predicate to find the nth element from a list (1-based index).


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

Output:
1.

2.

3.

4.

57
Artificial Intelligence (3170716) Enrollment No:200220131124
5.

6.

7.

8.

9.

Conclusion:

In this Prolog program, we implemented a set of list operations, including finding the length of a
list, summing all numbers in a list, checking if an element is a member of a list, appending two lists,
reversing a list, finding the last element of a list, and deleting occurrences of an element from a list.
Additionally, we implemented a predicate to find the nth element from a list.

Quiz: (Sufficient space to be provided for the answers)


1) What is a list in Prolog?
Ans In Prolog, a list is a fundamental data structure that can hold a sequence of elements.
Lists in Prolog are typically represented as a collection of elements enclosed in square
brackets, separated by commas.

2) Write a Prolog predicate "last/2" that returns the last element of a list.
Ans You can create a Prolog predicate called last/2 to return the last element of a list using
recursion. Here's how you can define it:
% Base case: The last element of a list with one element is that element.
last([X], X).

% Recursive case: To find the last element, discard the head of the list.
last([_|Tail], Last) :- last(Tail, Last).

58
Artificial Intelligence (3170716) Enrollment No:200220131061

Example:
?- last([1, 2, 3, 4, 5], Last).
% Last = 5

?- last([apple, banana, cherry], Last).


% Last = cherry
Suggested References:

1. “Artificial Intelligence” -By Elaine Rich And Kevin Knight (2nd Edition) Tata Mcgraw-
Hill
2. https://www.geeksforgeeks.org/artificial-intelligence-an-introduction/

References used by the students: (Sufficient space to be provided)

1. Artificial Intelligence: A Modern Approach


2. Prolog Programming on GitHub

Rubric wise marks obtained:

Problem Logic
Knowledge Tool Usage
Recognition Building Ethics (2)
Rubrics (2) (2) Total
(2) (2)
Good Avg. Good Avg. Good Avg. Good Avg. Good Avg.
(2) (1) (2) (1) (2) (1) (2) (1) (2) (1)
Marks

59

You might also like