0% found this document useful (0 votes)
82 views

AI Lab Manual Spring 2025

The document is a laboratory manual for the Artificial Intelligence course (CE-415L) at Sir Syed University of Engineering and Technology for the Spring 2025 semester. It outlines course objectives, learning outcomes, assessment methods, grading policies, and a detailed course outline including topics and laboratory synchronization. The manual also includes a rubric for evaluating student performance in software handling, programming, and project demonstration.

Uploaded by

infofarhanali555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
82 views

AI Lab Manual Spring 2025

The document is a laboratory manual for the Artificial Intelligence course (CE-415L) at Sir Syed University of Engineering and Technology for the Spring 2025 semester. It outlines course objectives, learning outcomes, assessment methods, grading policies, and a detailed course outline including topics and laboratory synchronization. The manual also includes a rubric for evaluating student performance in software handling, programming, and project demonstration.

Uploaded by

infofarhanali555
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 85

Computer Laboratory Manual

Artificial Intelligence (CE-415L)


6th Semester Computer Engineering

Computer Engineering Department


Sir Syed University Of Engineering and Technology
University Road Karachi - 75300
http://www.ssuet.edu.pk
(SSUET/QR/111)
SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY
COMPUTER ENGINEERING DEPARTMENT
BS COMPUTER ENGINEERING

LAB INFORMATION SHEET


(For Lab Course)
Session: SPRING-2025 (Batch 2022F)
Course Title: Artificial Intelligence
Course Code: CE-415L
Credit Hours: 1
Semester: 6th
Pre-Requisites: CE-205 Data structures & Algorithms;
Engr. M.Yasir Zaheen
Instructor Name:
Engr. Maheen Sadiq
[email protected]
Email and Contact Information:
[email protected]
WhatsApp Group -
Office Hours: 8:30 am – 5:00 pm
Mode of Teaching: Synchronous

COURSE OBJECTIVE:

The main purpose of this course is to provide the most fundamental knowledge to the students so that they
can understand what artificial intelligence is. This is an introductory course on Artificial Intelligence. The
topics may include AI methodology and fundamentals, intelligent agents, search algorithms, knowledge
representation, Reasoning, and planning.

COURSE OUTLINE:

Introduction to AI, Intelligence and Artificial Intelligence, branches and applications. Agent based Systems:
Introduction, applications, rationality, environment types, and agent types. Problem Solving, formulating
problems. Uninformed search strategies, Breadth-first search, uniform search, depth first search, iterative
depending search. Performance parameters. Informed (Heuristic) Search Strategies, Heuristic functions,
greedy search, A* Search, Genetic algorithm. Game Playing, minmax algorithm, Alpha Beta Pruning.
Knowledge and reasoning, Introduction to Fuzzy Logic, operator, inference procedure. Advanced Topics,
Machine Learning, Types of machine learning, artificial neural network, Naïve Bayes etc.

Page 1 of 7
(SSUET/QR/111)
SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY
COMPUTER ENGINEERING DEPARTMENT
BS COMPUTER ENGINEERING
COURSE LEARNING OUTCOMES (CLOs) and its mapping with Program Learning Outcomes
(PLOs):
CLO Bloom’s
No. Course Learning Outcomes (CLOs) PLOs
Taxonomy
Demonstrate working knowledge of Artificial PLO_5 C3
1 Intelligence algorithms in programming (Modern Tool Usage) (Applying)
language (Python)
Complete a project to implement different
PLO_10 A4
2 Artificial Intelligence algorithms in a
(Communication) (Organization)
programming language (Python)

COMPLEX ENGINEERING ACTIVITY:

Complex Engineering Activity Details Included: Yes


Nature and details of Complex Engineering Activity (CEA):
It will be given in
- Project

It is based on CLO_2. To solve the problem, students will


Formulate Solution (e.g. Designing Model, Extracting
parameters etc. Applying appropriate technique etc.) for a
problem using AI techniques discussed. Moreover they use
in-depth knowledge related to the following concepts.
Attributes: EA1 and EA3

EA1: Range of resources


EA3: Innovation

Assessment in: Project

RELATIONSHIP BETWEEN ASSESSMENT TOOLS AND CLOS:

Assessment Tools CLO-1 (35) CLO-2 (15)


Lab Manual 42.86% (15) -

Project - 100% (15)

Lab Exam 57.14% (20) -

Page 2 of 7
(SSUET/QR/111)
SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY
COMPUTER ENGINEERING DEPARTMENT
BS COMPUTER ENGINEERING
GRADING POLICY:

Assessment Tools Percentage


Lab Manual 30% (15 Marks)
Project 30% (15 Marks)
Lab Exam 40% (20 [15 + 05 Viva] Marks)
Total 100% (50 Marks)

Recommended Book:

• Stuart Russell and Peter Norvig, Artificial Intelligence. A Modern Approach, 4thedition, Pearson,
2021. ISBN-13: 978-0134610993, ISBN-10: 0134610997
Artificial.Intelligence.A.Modern.Approach.4th.Edition.Peter.Norvig.Stuart.Russell.Pearson.9780
134610993.EBooksWorld.ir.pdf

Reference Books:

• Artificial Intelligence: Foundations of Computational Agents, 3rd Edition, David L. Poole and
Alan K. Mackworth
Artificial Intelligence: Foundations of Computational Agents, 3rd Edition (artint.info)
• Timothy J. Ross, Fuzzy Logic with Engineering Applications, 4th Edition, John Wiley & Sons,
Ltd, 2016
Fuzzy Logic with Engineering Applications, 4th Edition | Timothy J. Ross | download on
Z-Library

• Martin T. Hagan, Neural Network Design, 2nd Edition, 2014


https://hagan.okstate.edu/NNDesign.pdf

• Luger, G.F. and Stubblefield, W.A., 2009. AI algorithms, data structures, and idioms in Prolog,
Lisp, and Java. Pearson Addison-Wesley.

Page 3 of 7
(SSUET/QR/111)
SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY
COMPUTER ENGINEERING DEPARTMENT
BS COMPUTER ENGINEERING
COURSE BREAKDOWN WITH LAB SYNCHRONIZATION:

- Both sides same Colours: Lab is synchronized with the topic


- Red Color: Lab is not synchronized (conducted before theory)
- No Color: Lab is to introduce new hardware or software skill /
Open Ended Lab / Lab is relevant to a topic taught in
pre-requisite and required for upcoming labs

Week
Topics Laboratory Synchronization
No.
Chapter1: Introduction to AI Demonstrate the concept of String, List, tuples
Topics: Intelligence, Artificial Intelligence, and Pandas for AI data using Python
1 Turing test (Act, Think), Foundations of AI, language1.
Applications domains. Working with data in
AI applications1
Chapter 2: Intelligent Agents Demonstrate the basics of developing a simple
Topics: Agent (Human, robotic, software) & Agent using Python language2.
environment, Vacuum cleaner with just 2
2 locations, Concept of rationality, PEAS, Task
Environment & their characteristics. Agents
types. How to design a Simple Agent
application2
Chapter 3: Solving Problems by Searching Implement a simple reflex agent using python
Topics: Problem formulation, 8 puzzle, 8 language.2
queens, Measuring Problem Solving
3
performance4, Uninformed Search Strategies:
Breadth First Search5 Uniform cost, Depth
First .Queue approach to BFS and DFS 4
Depth limited, Iterative deepening cost Implement set of records using priority queue
Chapter 4: Informed Search Methods: (queue and heapq) modules for searching
4
Heuristic Search algorithms and implement shortest path using
BFS3
Greedy Search, A* Search7 Implement shortest path using DFS search
5
techniques.5, 6
A* Search7 Implement shortest path using A* search
6 technique7.

Genetic Algorithm8 Implement local search technique using


7 genetic algorithm8.

Chapter 5: Game Theory, Min max algorithm, Open Ended lab


8
Alpha beta pruning algorithm
MIDTERM EXAMS
Introduction to Fuzzy Logic 9- CRISP Set to Implement N-dimensional array using NumPy
FUZZY Sets: Crispy Set, Sets (Basic & library. Also study predicate and propositional
10
Concepts), Fuzzy Sets Vs Crisp Sets – logic using python.

Page 4 of 7
(SSUET/QR/111)
SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY
COMPUTER ENGINEERING DEPARTMENT
BS COMPUTER ENGINEERING
Additional Properties, Representation of
Fuzzy Sets
Operation on Fuzzy Sets10 – Types of Implement fuzzy logic system using Scikit
Operations, Fuzzy Complements, Fuzzy fuzzy module9
11
intersection, union, combination, aggregation
operations
Fuzzy Relations, Fuzzy Inference, Implement membership functions using Scikit
Fuzzification of the input variables, Rule fuzzy in fuzzy logic10.
12
evaluation, Aggregation of the rule outputs,
Defuzzification
Process of developing a fuzzy expert system, Implement Neural Networks using Python.
Operation of a fuzzy expert system11
13
Examples: Air Conditioner; Cart Pole
Problem.
Advanced Topics Implement scientific and technical computing
14 Introduction to Machine Learning, Types of with plotting using SciPy and matplotlib
Learning library11.
Advanced Topics Open ended lab
15 Naïve Bayes
Advanced Topics Lab Test/ Project Viva / Complex Engineering
16
ANN(Optional) Activity

Page 5 of 7
Sir Syed University of Engineering & Technology, Karachi SSUET/QR/118
Computer Engineering Department (Form IIa)
Rubric Guideline for Software Based Lab

Artificial Intelligence (CE-415L), Spring Semester 2025

Criteria Exceeds Meets Expectations Developing Unsatisfactory


Expectations (70%-89%) (50%-69%) (<50%)
(>=90%)
Software Able to use software Able to use software Able to use Unable to use the
with its standard and with its standard and software with its software
Handling advanced features advanced features with standard features
without assistance minimal assistance with assistance
Programming/ Able to program/ Able to program/ Able to program/ Unable to
simulate the lab simulate the lab tasks simulate lab tasks program/simulate
Simulation tasks with without errors with errors
simplification
Able to achieve all Able to achieve all the Able to achieve Unable to achieve
Results the desired results desired results most of the the desired results
with alternate ways desired results
with errors
Laboratory manual Laboratory manual has Laboratory Laboratory manual
has no grammatical very few grammatical/ manual has has several
and/ or spelling spelling errors. multiple grammatical/
Laboratory errors. All sections of the report grammatical/ spelling errors and
Manual All sections of the are technically accurate. spelling errors. sentence
report are very well Few sections of construction is poor.
written and the report contains
technically accurate. technical errors.
SSUET/QR/118
[Form-IIb]
Sir Syed University of Engineering & Technology, Karachi
Computer Engineering Department
Rubric-Laboratory Manual
Artificial Intelligence (CE-415L), Spring Semester 2025
Name of Student: Roll No.
Lab Description & Score

1. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

2. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

3. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

4. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

5. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

6. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10
Open Ended Lab#1
7. Software Handling Programming/ Simulations Results Lab Report Score
( )/6 ( )/12 ( )/6 ( )/4 ( )/15
8. Midterm Week

9. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

10. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

11. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

12. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10

13. Software Handling Programming/ Simulations Results Lab Report Score


( )/2 ( )/4 ( )/2 ( )/2 ( )/10
Open Ended Lab#2
Software Handling Programming/ Simulations Results Lab Report Score
14. ( )/2 ( )/4 ( )/2 ( )/2 ( )/10
Software Handling Programming/ Simulations Results Lab Report Score
( )/2 ( )/4 ( )/2 ( )/2 ( )/15
15. Lab Exam / Project Viva
TOTAL SCORE

Overall Score: out of 15 Examined by:


(Obtained Score / 160) x 15 (Name and Signature of concerned lab instructor
SSUET/QR/118
(Form IIIa)
Sir Syed University of Engineering & Technology, Karachi
Computer Engineering Department
Rubric for Subject Project
Artificial Intelligence (CE-415L), Spring Semester 2025
Name of Student: Roll No.

Criteria Exceeds Meets Developing Unsatisfactory Score


Expectations Expectations (50%-69%) (<50%) Obtained
(>=90%) (70%-89%)

Able to Able to Able to Able to


demonstrate the demonstrate demonstrate the demonstrate the
project with the project project with project with
achievement of with achievement of achievement of
required achievement of a*t least 50% less than 50%
objectives required required required
having clear objectives but objectives and objectives and
understanding understanding insufficient lacks in
Project of project of project understanding of understanding of
Demonstration limitations and limitations and project project limitations
(6) future future limitations and and future
enhancements. enhancements future enhancements.
Hardware is insufficient. enhancements. Hardware and/or
and/or Software Hardware Hardware and/or Software modules
modules are and/or Software are not functional,
fully functional, Software modules are if applicable.
if applicable. modules are partially
functional, if functional, if
applicable. applicable.

Able to achieve Able to Able to achieve Unable to achieve


Project results all the desired achieve all the most of the the desired results
results with desired results desired results
(3)
alternate ways to with errors
improve
measurements

Project report has Project report Project report Project report has
no grammatical has very few has multiple several
and/ or spelling grammatical/ grammatical/ grammatical/
Project Report errors. spelling errors. spelling errors. spelling errors and
(3) All sections of the All sections of Few sections of sentence
report are very the report are the report construction is
well-written and technically contains poor.
technically accurate. technical errors.
accurate.

Able to answer Able to answer Able to answer Unable to answer


Viva the questions the questions the questions but the questions
(3) easily and related to the with mistakes
correctly across project
the project.
Total Marks
SSUET/QR/118
(Form IIIb)
Sir Syed University of Engineering & Technology, Karachi
Computer Engineering Department
Rubric for Lab Exam

Artificial Intelligence (CE-415L), Spring Semester 2025

Name of Student: Roll No.

Criteria Exceeds Meets Developing Unsatisfactory Score


Expectation Expectations (50%-69%) (<50%) Obtained
s (>=90%) (70%-89%)
Performance
(10) Able to Able to present Able to present No or very less
present full adequate knowledge sufficient knowledge of
knowledge of of both problem and knowledge of both problem
both problem solution both problem and and solution
and solution. solution
Viva
(10) Able to Able to answer the Able to answer Unable to answer
answer the questions related to the questions but the questions
questions the project with mistakes
easily and
correctly
across the
project.
Total Score

Final Lab Assessment

Criteria Score Obtained

Laboratory Manual

Subject Project (If any)

Lab Exam

Total (50)

Examined by:
(Name and Signature of concerned lab instructor)
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

ARTIFICIAL INTELLIGENCE SSUET/QR/113


Table of Contents
Lab # List of Experiments Page # Sign Remarks

1 introduction to python, operator, string and 1


list

tuple, dictionary, functions for designing simple


2 5
agents

Demonstrate class and object for simple reflex


3 10
agent using python.
Implement priority queue using (queue and heap)
4 15
modules and Graph using a dictionary.
Implement uninformed search using BFS and
5 DFS search techniques and explore Depth 18
Limit search.
Implementing shortest path using A* search
6 21
technique.
Implement local search technique using genetic
7 24
algorithm.

25
8 Open - Ended
27
30
Implement fuzzy logic system using Scikit fuzzy
9
module.
33
Implement fuzzy logic system using Scikit fuzzy
10 34
module.
38
11 Fuzzification and Defuzzification
40
Implement fuzzy rules and control system using
12 41
Scikit fuzzy module.
Implement Scientific and technical computing with
13 plotting using SciPy and matplotlib library. 43

14 Open - Ended 47

1|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 01
INTRODUCTION TO PYTHON, OPERATOR, STRING ANDLIST
OBJECTIVE
Demonstrate the concept of Operators, String and List using Python.

THEORY
Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is
widely used for Artificial Intelligence, with packages for a number of applications including
Machine Learning and NLP. Python is designed to be highly readable. It uses English keywords
frequently whereas other languages use punctuation, and it has fewer syntactical constructions
than other languages.
• Python is Interpreted: Python is processed at runtime by the interpreter. You do not need
to compile your program before executing it. This is similar to PERL and PHP.

• Python is Interactive: You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.

• Python is Object-Oriented: Python supports Object-Oriented style or technique of


programming that encapsulates code within objects.

• Python is a Beginner's Language: Python is a great language for the beginner-level


programmers and supports the development of a wide range of applications from simple
text processing to WWW browsers to games.

Python Features:
Python's features include:
• Easy-to-learn: Python has few keywords, simple structure, and a clearly defined syntax.
This allows the student to pick up the language quickly.

• Easy-to-read: Python code is more clearly defined and visible to the eyes.

• Easy-to-maintain: Python's source code is fairly easy-to-maintain.

• A broad standard library: Python's bulk of the library is very portable and cross platform
compatible on UNIX, Windows, and Macintosh.
• Interactive Mode: Python has support for an interactive mode which allows interactive
testing and debugging of snippets of code.

2|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

• GUI Programming: Python supports GUI applications that can be created and ported to
many system calls, libraries and windows systems, such as Windows MFC, Macintosh,
and the X Window system of Unix.

• Scalable: Python provides a better structure and support for large programs than shell
scripting.

Modules in Python:
• A module allows you to logically organize your Python code. Grouping related code into
a module makes the code easier to understand and use. A module is a file consisting of
Python code. A module can define functions, classes and variables.
• In Python, modules are accessed by using the ‘import‘ statement. When you do this, you
execute the code of the module, keeping the scopes of the definitions so that your current
file(s) can make use of these.
• Many build-in modules of python, some of above
1. Math
2. Random
3. Fraction
4. Decimal
5. OS

Operator in Python:
• Basic algebraic operations
✓ Four arithmetic operations: a+b, a-b, a*b, a/b
✓ Exponentiation: a**b
✓ Other elementary functions are not part of standard Python, but included in
packages like NumPy and SciPy
• Comparison operators
✓ Greater than, less than, etc.: a < b, a > b, a <= b, a >= b
✓ Identity tests: a == b, a != b
• Bitwise operators
✓ Bitwise or: a | b
✓ Bitwise exclusive or: a ^ b # Don't confuse this with exponentiation
✓ Bitwise and: a & b
✓ Shift a left or right by b bits: a << b, a >> b

Input Function:
The input() function pauses your program and waits for the user to enter some text. Once Python
receives the user‘s input, it stores it in a variable to make it convenient for you to work with. The
purpose of an input statement is to get some information from the user of a program and store it
into a Variable.
• Syntax: <variable> = input (<prompt>)

3|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Example: 01

Strings:
A string is simply a series of characters. Anything inside quotes is considered a string in Python,
and you can use single or double quotes around your strings like this:
"This is a string."
'This is also a string.'
Changing Case in a String with Methods
One of the simplest tasks you can do with strings is change the case of the words in a string. Look
at the following code, and try to determine what‘s happening:

Combining or Concatenating Strings:


When applied to strings, the + operation is called concatenation. It produces a new string that is a
copy of the two original strings pasted together end-to-end. Notice that concatenation doesn‘t do
anything clever like insert a space between the words. The Python interpreter has no way of
knowing that you want a space; it does exactly what it is told.

Strings can be concatenated with the ‗+‘ operator and repeated with ‗*‘

Example: 02

4|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Indexing of string:
Python starts indexing at 0. A string s will have indexes running from 0 to len(s)-1 (where len(s)
is the length of s) in integer quantities.

S A m m Y S h A r k !

0 7 8 11
1 2 3 4 5 6 9 10

Example: 03
• s[i] : fetches the ith element in s
• s[i:j] : fetches elements i (inclusive) through j (not inclusive)
• s[:j] fetches all elements up to, but not including j
• s[i:] fetches all elements from i onward (inclusive)
• s[i:j:k] extracts every kth element starting with index i (inlcusive) and ending with index j
(not inclusive)
• Python also supports negative indexes. For example, s[-1] means extract the first element
of s from the end (same as s[len(s)-1])

ss=‖Sammy Shark! ― print(ss[2]) print(ss[6:11])


print(ss[:5]) print(ss[5:]) print(ss[0:5:2]) print(ss[-2])

Output:

List:
A list is a collection of items in a particular order. You can make a list that includes the letters of
the alphabet, the digits from 0–9, or the names of all the people in your family. You can put
anything you want into a list, and the items in your list don‘t have to be related in any particular
way. Because a list usually contains more than one element, it‘s a good idea to make the name of
your list plural, such as letters, digits, or names.

5|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

It can have any number of items and they may be of different types (integer, float, string etc.). In
Python, square brackets ([]) indicate a list, and individual elements in the list are separated by
commas.
# empty list
my_list = [] # list
of integers
my_list = [1, 2, 3]
#list of strings
My_list = [‗abc‘,cde‘]
Also, a list can even have another list as an item. This is called nested list.
# nested list
my_list = [[1,2,3], [8, 4, 6], [4]]
Some simple example of a list:

Changing, Adding, and Removing Elements: Most lists you create will be dynamic,
meaning you‘ll build a list and then add and remove elements from it as your program
runs its course.

6|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Modifying Elements in a List:


The syntax for modifying an element is similar to the syntax for accessing an element in a list.
To change an element, use the name of the list followed by the index of the element you want to
change, and then provide the new value you want that item to have. For example, let‘s say we
have a list of motorcycles, and the first item in the list is 'honda'. How would we change the
value of this first item?

Example: 04

Output:

Adding/Appending Elements to a List:


You might want to add a new element to a list for many reasons. For example, you might want to
make new aliens appear in a game, add new data to visualization, or add new registered users to
a website you‘ve built. Python provides several ways to add new data to existing lists.

The simplest way to add a new element to a list is to append the item to the list. When you
append an item to a list, the new element is added to the end of the list. Using the same list we
had in the previous example, we‘ll add the new element 'ducati' to the end of the list:

Example: 05

The append () method, adds 'ducati' to the end of the list without affecting any of the other elements
in the list:
Output:

Removing Elements
from a List:

7|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Example#06:

Output:

• The remove operation on a list is given a value to remove. It searches the list to find an
item with that value and deletes the first matching item it finds. It is an error if there is no
matching item.

• The del statement can be used to delete an entire list. If you have a specific list item as
your argument to del. It is even possible to delete a "slice" from a list.

• The pop() is to delete the last item from a list as you use the list as a stack. Unlike del, pop
returns the value that it popped off the list.

Organizing a List:

Sorting a List Permanently with the sort() Method:


Python‘s sort() method makes it relatively easy to sort a list. Imagine we have a list of cars and
want to change the order of the list to store them alphabetically. To keep the task simple, let‘s
assume that all the values in the list are lowercase.

Example#07:

Output:

8|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Built-in List Functions & Methods:


Python includes the following list functions −
Sr.No. Function with Description

1 cmp(list1, list2)
Compares elements of both lists.

2 len(list)
Gives the total length of the list.

3 max(list)
Returns item from the list with max value.

4 min(list)
Returns item from the list with min value.

5 list(seq)
Converts a tuple into list.
Python includes following list methods
Sr.No. Methods with Description

1
list.append(obj)
Appends object obj to list

2 list.count(obj)
Returns count of how many times obj occurs in list

4 list.index(obj)
Returns the lowest index in list that obj appears

5 list.insert(index, obj)
Inserts object obj into list at offset index

6 list.pop(obj=list[-1])

Removes and returns last object or obj from list

7 list.remove(obj)
Removes object obj from list

9|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

8 list.reverse()
Reverses objects of list in place

9 list.sort([func])
Sorts objects of list, use compare func if given

Before we start talking about tuples and dictionaries, we have to introduce two important concepts:
sequence types and mutability.

Sequence type:
A sequence type is a type of data in Python which is able to store more than one value (or less
than one, as a sequence may be empty), and these values can be sequentially (hence the name)
browsed, element by element. As the for loop is a tool especially designed to iterate through
sequences, we can express the definition as: a sequence is data which can be scanned by the for
loop. You‘ve encountered one Python sequence so far – the list. The list is a classic example of a
Python sequence.

Mutability:
Mutability is a property of any of Python‘s data that describes its readiness to be freely changed
during program execution. There are two kinds of Python data: mutable and immutable.
Mutable data can be freely updated at any time. Immutable data cannot be modified in this way.

Panda Library:
Pandas is a Python library that is used to work with data sets. It has functions for analyzing,
cleaning, exploring, and manipulating data. You will need to install the Pandas library to work
with. Pandas provides two types of data structures for handling data:

1. Series: a one-dimensional labelled array holding data of any type


such as integers, strings, Python objects etc.
2. DataFrame: a two-dimensional data structure that holds data like a two-dimensional array
or a table with rows and columns.

Example#08: To import the library.

import pandas as pd

Example#09: Dataframe can be created manually using multiple datatypes offered by pandas

df2 = pd.DataFrame(
{
"A": 1.0,
"B": pd.Timestamp("20130102"),

10 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

"C": pd.Series(1, index=list(range(4)), dtype="float32"),


"D": np.array([3] * 4, dtype="int32"),
"E": pd.Categorical(["test", "train", "test", "train"]),
"F": "foo",
}
)

Data Frame can also be created using external data source for example Pandas provides
the read_csv() function to read data stored as a csv file.

Example#10: Create data.csv in excel with the following columns and data and save it in the
working folder

totalbill tip gender smoker day time size


16.99 1.01 female no sun dinner 2
26.99 3.00 male no sun dinner 3
100.00 20.00 Female yes sat dinner 10

import pandas as pd
df = pd.read_csv('data.csv')
print(df)

Example#11:
df.head()will show top 4 rows of the frame. You can adjust the number of rows you want to see.
df.tail(3) will show last three rows of the frame

11 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Exercise:
1. Write a script that take user input for a number then adds 3 to that number. Then
multipliesthe result by 2, subtract 4, then again adds 3, then print the result.

2. Write a script that takes input as radius then calculate area of circle. (hint: A= πr²).

3. Write a Python script that asks users for their favourite color. Create the following
output(assuming blue is the chosen color) (hint: use ‗+‘ and ‗*‘)
1. blueblueblueblueblueblueblueblueblueblue
2. blue blue
3. blueblueblueblueblueblueblueblueblueblue

4. Store a person‘s name, and include some whitespace characters at the beginning and
endof the name. Make sure you use each character combination, "\t" and "\n", at least
once. Print the name once, so the whitespace around the name is displayed. Then
print the name using each of the three stripping functions, lstrip(),rstrip(), and strip().

5. Store the names of a few of your friends in a list called names. Print each person‘s
nameby accessing each element in the list, one at a time.

6. If you could invite anyone, living or deceased, to dinner, who would you invite? Make
alist that includes at least three people you‘d like to invite to dinner. Then use your list
toprint a message to each person, inviting them to dinner.

7. Changing Guest List: You just heard that one of your guests can‘t make the dinner,
soyou need to send out a new set of invitations. You ‘ll have to think of someone
else to invite.
• Modify your list, replacing the name of the guest who can‘t make it with the name of
thenew person you are inviting.
• Print a second set of invitation messages, one for each person who is still in your list.

8. Add some more data in data.csv file and create data frame by reading
csv.Use the following commands in the data frame.
a. Append
b. Info
c. Search by Row

12 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 02
TUPLE, DICTIONARY, FUNCTIONS FOR DESIGNING
SIMPLE AGENTS

OBJECTIVE
Demonstrate the python basic structure to design simple agents.

THEORY

Tuples:
A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The
differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use
parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated values. Optionally you can put
these comma-separated values between parentheses also. For example –

tup1 = ('physics', 'chemistry', 1997,


2000); tup2 = (1, 2, 3, 4, 5 ); tup3 = "a",
"b", "c", "d"; tup4 = ( );
To write a tuple containing a single value you have to include a comma, even though there is only
one value –
tup1 = (50,);

Dictionary:
A dictionary in Python is a collection of key-value pairs. Each key is connected to a value, and
you can use a key to access the value associated with that key. A key‘s value can be a number, a
string, a list, or even another dictionary. Python dictionary is an unordered collection of items.
While other compound data types have only value as an element, a dictionary has a key: value
pair. Dictionaries can store an almost limitless amount of information.

13 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Creating a dictionary is as simple as placing items inside curly braces {} separated by comma.
An item has a key and the corresponding value expressed as a pair, key: value.

dict = {'color': 'green', 'points': 5}


Adding New Key-Value Pairs:
Dictionaries are dynamic structures, and you can add new key-value pairs to a dictionary at any
time. For example, to add a new key-value pair, you would give the name of the dictionary
followed by the new key in square brackets along with the new value.

Example:

Output:

Removing Key-value pair:


When you no longer need a piece of information that‘s stored in a dictionary, you can use the del
statement to completely remove a key-value pair. All ‗del‘ needs is the name of the dictionary and
the key that you want to remove.

Example:
bumpers = {"north" : True, "east" : False, "south" : False, "west" : True}

Output:
>>>> bumpers
{‘north’ : True, ‘east’ : False, ‘south’ : False, ‘west’ : True

}Example:

Example:

✓ The method items () returns a list of dict's (key, value) tuple pairs. The syntax of items ()

14 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

method is: dictionary.items ().


✓ The key-value pairs are not returned in the order in which they were stored, even when
looping through a dictionary. Python doesn‘t care about the order in which key-value pairs
are stored; it tracks only the connections between individual keys and their values.
✓ There is also a method named values(), which works similarly to keys(), but returns a list
of values.

Output:

Functions:

Defining a Function:
You can define functions to provide the required functionality. Here are simple rules to define a
function in Python.
• Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).

• Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.

• The code block within every function starts with a colon (:) and is indented.

Syntax: def functioname


PARAMETERS ):
Statement
Example:
def simple_randomized_agent(bumpers, dirty):
return np.random.choice(actions)
Arguments:
An argument is a piece of information that is passed from a function call to a function. When we
call the function, we place the value we want the function to work with in parentheses.
You can call a function by using the following types of formal arguments:

• Required arguments
• Keyword arguments
• Default arguments

Required Arguments:
15 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Required arguments are the arguments passed to a function in correct positional order. Here, the
number of arguments in the function call should match exactly with the function definition.

Keyword Arguments:
Keyword arguments are related to the function calls. When you use keyword arguments in a
function call, the caller identifies the arguments by the parameter name.
This allows you to skip arguments or place them out of order because the Python interpreter is
able to use the keywords provided to match the values with parameters.

When the above code is executed, it produces the following result.

Default Arguments:
A default argument is an argument that assumes a default value if a value is not provided in the
function call for that argument. The following example gives an idea on default arguments, it
prints default age if it is not passed –
import numpy as np
actions = ["north", "east", "west", "south", "suck"]
dirty = True

def simple_environment(agent, max_steps, verbose=True):


num_cleaned = 0

for i in range(max_steps):
action = agent(bumpers, dirty)
if (verbose): print("step", i, "- action:", action)
if (action == "suck"):
num_cleaned = num_cleaned + 1

16 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

print(simple_environment(simple_randomized_agent, max_steps = 10))

Output:

Step 0 – action: suck


Step 1 – action: north
Step 2 – action: east
Step 3 – action: east
Step 4 – action: suck
Step 5 – action: west
Step 6 – action: east
Step 7 – action: suck
Step 8 – action: west
Step 9 – action: suck

Exercise:

1. Update the environment and agent function with the following:


a. Add another action ‘bump’ in the action list
b. if action = ‘suck’ and dirty =True, then dirty =False and increment num_cleaned else
display the message “Wrong Action, Dirt Not Detected.”
c. In the agent function, check actions in bumpers, and if an action is true, randomly select
another action and repeat. Maintain a list of all (action, comment) tuples where the
comment is a string “ bump” is bump detected or “OK.”
d. Update environment function to print all (actions, comments)

2. Write a function called absolute_num() that accepts one parameter, num. The function
should return only a positive value and apply a condition on it. This function returns the
absolute value of the entered number.

17 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 03

OBJECTIVE
Demonstrate class and object for simple reflex agent using python.
THEORY

Class and Object:


• Python is an object-oriented programming language. Unlike procedure-oriented
programming, where the main emphasis is on functions, object-oriented programming
stresses on objects.
• A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. Class is a blueprint for the object.
• Object is simply a collection of data (variables) and methods (functions) that act on those
data.

Defining a Class in Python:


Like function definitions begin with the keyword def, in Python, we define a class using the
keyword class.
The first string is called docstring and has a brief description about the class. Although not
mandatory, this is recommended. Here is a simple class definition.
class MyNewClass:
'''This is a docstring. I have created a new class'''
pass
A class creates a new local namespace where all its attributes are defined. Attributes may be data
or functions.
It also contains special attributes beginning with double underscores ( ). For example, doc
gives us the docstring of that class.

18 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Output:

Creating an Object in Python:


We saw that the class object could be used to access different attributes.
It can also be used to create new object instances (instantiation) of that class. The procedure to
create an object is similar to a function call.

>>> ob = Class()

This will create a new instance object named ob. We can access attributes of objects using the
object name prefix.
Attributes may be data or method. The method of an object is the corresponding functions of that
class. Any function object that is a class attribute defines a method for objects of that class.
This means to say, since MyClass.func is a function object (attribute of class), func will be a
method object.

Example:

Output:

Class Features:

Initialization ( init ):
The init method is run as soon as an object of a class is instantiated. The method is useful
to do any initialization you want to do with your object. Notice the double underscore both in the
beginning and at the end in the name.

Example:

19 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Simple Reflex Agent:

Let consider the A simple Reflex Agent

class Agent:
def init (self, tlocation):
self.loccovered=0
self.loccount=tlocation
self.stop=False
print("Agent Initialized")
def move(self):
if (self.loccovered<self.loccount-1):
self.loccovered=self.loccovered+1
print("Agent's Location changed")
else:
print("There are no more locations to move. Returning to home")
self.loccovered=0
self.stop=True

def clean(self):
print("Agent cleaned the location")
return 'Clean'

class Env:
locationlist = ['A', 'B']
def init (self):
self.locationstatus={'A':'Dirty','B':'Dirty'}
print("Enviornment Initialized")

#percept
def isLocClean(self,vaccleaner):
temp=False
if (self.locationstatus[self.locationlist[vaccleaner.loccovered]]=='Clean'):
temp=True
return temp

#action
def cleanLocation(self,vaccleaner):

20 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

if(self.isLocClean(vaccleaner)):
print("Location is already clean-No change observed")
else:
self.locationstatus[self.locationlist[vaccleaner.loccovered]]=vaccleaner.clean()
print(self.locationstatus)
vaccleaner.move()

#run environment and agent


def run():
rooms=Env()
vacclean=Agent(len(rooms.locationlist))
while (vacclean.stop==False):
rooms.cleanLocation(vacclean)
print("status:" + rooms.locationstatus. str ())
print("Agent Shutdown")
run()

Output
Environment initialized
Agent initialized
Agent cleaned the location
{‘A’:’Clean’, ‘B’:’Dirty’}
Agent’s location changed
Agent cleaned the location
{‘A’:’Clean’, ‘B’:’Clean’}
There are no more locations to move. Returning to home
status: {‘A’: ’Clean’, ‘B’: ’Clean’}
Agent Shutdown

Exercise:
1. Create a Class ―Employee‖, it’s a common base class for all the employee. Then initialize
the employee parameters like empName and salary and create a function like displayCount(),
containing the total number of employees in your knowledge base, and displayEmployee(),
containing empName and their salary.

2. Add a bump list dictionary indicating which location is blocked and which is accessible. (hint:
lab 02 bumper dictionary). Agents can now move in four directions up, down, left and right.
Move function should now be moveup(), movedown() and so on. Any move should also check
if the bump list permits the move and then check if all locations are cleaned. On the bump, the
message “Invalid Move” should be displayed. The run function should simulate all moves.

21 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 04

OBJECTIVE
Implement priority queue using (queue and heap) modules and Graph using a dictionary.

THEORY

Priority Queue
A priority queue is an abstract data type (ADT) that is like a regular queue or stack data structure,
but each element has a priority associated with it. In a priority queue, an element with high priority
is served before an element with low priority. If two elements have the same priority, they are
served according to their order in the queue.
While priority queues are often implemented with heaps, they are conceptually distinct from
heaps. A priority queue is an abstract concept like a list or a map; just as a list can be implemented
with a linked list or an array, a priority queue can be implemented with a heap or various other
methods, such as an unordered array.
ALGORITHM: Priority Queue
A priority queue is a specialized type of queue
• Items added to queue are assigned an order of rank
• Items of higher priority are removed before those of lower priority
• Items of equal priority are removed in FIFO order
• Items A has a higher priority than item B if A<B

Module in Python which support Priority queue:

Queue:
The queue module provides a first-in, first-out (FIFO) data structure suitable for multi-threaded
programming. As we can see from the output, the queue stores the elements by priority not by the
order of element creation. Note that depending on the Python versions, the name of the priority
queue is different.

Example: Output:

22 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

In queue module,
• PriorityQueue ( ) is a subclass of Queue; retrieves entries in priority order (lowest first).
Entries are typically tuples of the form: (priority number, data).
• Empty ( ), return True if the queue is empty, False otherwise.
• Put (item), put an item into the queue. If the queue is full, wait until a free slot is available
before adding item.
• Get ( ), remove and return an item from the queue. If the queue is empty, wait until an item
is available.

The module implements three types of queue, which differ only in the order in which the entries
are retrieved. In a FIFO queue, the first tasks added are the first retrieved. The most recently added
entry in a LIFO queue is the first retrieved (operating like a stack). With a priority queue, the
entries are kept sorted (using the heapq module), and the lowest-valued entry is retrieved first.

Heapq:
Python has a heapq module that implements a priority queue using a binary heap. Python's heapq
module implements a binary min-heap on top of a list.
Heaps are binary trees for which every parent node has a value less than or equal to any of its
children. This implementation uses arrays for which heap[k] <= heap[2*k+1]
and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison,
non-existing elements are considered to be infinite. The interesting property of a heap is that its
smallest element is always the root, heap[0]. Heap[0] is the smallest item, and heap.sort()
maintains the heap invariant
A max-heap ensures that the parent is larger than or equal to both of its children. A min-heap
requires that the parent be less than or equal to its children. Python‘s heapq module implements a
min-heap.

Function of heapq:
• First initialize Heap=[ ]
• Method: heapq.heappush(Heap,n): add n into heap
• Method: heapq.heapify(list): convert list as a heap
• Method: heapq.heappop(Heap): pop the smallest item
• Method: heapq.heapreplace(Heap,n): replace the smallest item with n

23 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Example:

Example: Output:

Implementation of Graph using Adjacency List

A graph is a data structure you can use to model hierarchy and relationships between
objects. It consists of a set of nodes and a set of edges. Nodes representindividual
objects, while edges illustrate relationships between those objects.
Graphs can be uni-directional or bi-directional. The edges of the graph can be
associated with weight as well. The Graph can be stored as adjacency Matrix or
Adjacency List. An adjacency list is the most efficient way to store a graph.
Adjacency List can be created using dictionary in python

24 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

from collections import defaultdict

#for bidirectional graphclass


BiDirGraph:

def init (self, nodes: int):


# Store the adjacency list as a dictionary# { 0 : [ 1, 2 ], 1 : [ 3, ] }

# The default dictionary would create an empty list as a default


(value)
# for the nonexistent keys. self.adjlist =
defaultdict(list)self.nodes = nodes

# Assuming that the edge is bidirectional


def AddEdge(self, source: int, destination: int):
self.adjlist[source].append(destination)
self.adjlist[destination].append(source)

def printAdjList(self):
for item in self.adjlist.items():print(item)

def main():

nodes = 7

g = BiDirGraph(nodes)

g.AddEdge(0, 1)
g.AddEdge(0, 2)
g.AddEdge(1, 3)

25 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

g.AddEdge(1, 4)
g.AddEdge(2, 3)
g.AddEdge(3, 5)
g.AddEdge(4, 6)
g.AddEdge(5, 6)

print("Adjacency list for storing


graph")g.printAdjList()

if name == " main " :


main()

Exercise:
1. Create a Stack class and include push and pop functions. The class should also have display
stack function. Use this class to test the following stack operations. Display stack items after
each operations. Add any other function that you may find necessary e.g underflow

Push (1), Push(3), Push (7), Pop(), Push(2),Push(4), Push(7), Pop(), Pop()

2. We have an array of 5 elements: [4, 8, 1, 7, 3] and we have to insert all the elements in the
max-priority queue. First as the priority queue is empty, so 4 will be inserted initially. Now
when 8 will be inserted it will move to front as 8 is greater than 4. While inserting 1, as it is
the current minimum element in the priority queue, it will remain in the back of priority
queue. Now 7 will be inserted between 8 and 4 as 7 is smaller than 8. Now 3 will be inserted
before 1 as it is the 2nd minimum element in the priority queue. All the steps are represented
in the diagram below:

26 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

3. Implement the following graph using Graph Class. Create a Class Node which has a string type
name and integer type unique attribute. Update the Graph class to support Node object instead of
integer. Also update the Graph class to include cost at the edges.

27 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 05

OBJECTIVE
Implement uninformed search using BFS and DFS search techniques and explore Depth Limit
search.

THEORY

Breadth First Search (BFS):


Breadth First Search (BFS) is an uninformed search technique that searches breadth-wise in the
problem space. Breadth-First search is like traversing a tree where each node is a state which may
a be a potential candidate for solution. It expands nodes from the root of the tree and then generates
one level of the tree at a time until a solution is found. It is very easily implemented by maintaining
a queue of nodes. Initially the queue contains just the root. In each iteration, node at the head of
the queue is removed and then expanded. The generated child nodes are then added to the tail of
the queue.

ALGORITHM: Breadth First Search:

Python provides SimpleQueue Class under queue module for using it as FIFO queue

28 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

from collections import defaultdict


import queue as q

#for bidirectional graph


class DirGraph:

def init (self, nodes: int):


# Store the adjacency list as a dictionary
# { 0 : [ 1, 2 ], 1 : [ 3, 4 ] }

# The default dictionary would create an empty list as a default (value)


# for the nonexistent keys.
self.adjlist = defaultdict(list)
self.nodes = nodes

# Assuming that the edge is bidirectional


def AddEdge(self, source: int, destination: int):
self.adjlist[source].append(destination)
# self.adjlist[destination].append(source)

def printAdjList(self):
for item in self.adjlist.items():
print(item)

def BFS(tm, s,g):


visited=[]

# Create a queue for BFS


fifoq=q.SimpleQueue()

# Mark the source node as visited and enqueue it


fifoq.put(s)
state=s
while state !=g and not fifoq.empty():
# Dequeue a vertex from
# queue and print it
state = fifoq.get()
if state not in visited:
visited.append(state)
else:
state = fifoq.get()
print(state, end=" ")

# Get all adjacent vertices of the


# dequeued vertex s.
# If an adjacent has not been visited,
# then mark it visited and enqueue it
for i in tm.adjlist[state]:
fifoq.put(i)
if state == g:
print("Search Successful")
else:
print("\nGoal not found")

def main():

29 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

nodes = 7

g = DirGraph(nodes)

g.AddEdge(0, 1)
g.AddEdge(0, 2)
g.AddEdge(1, 3)
g.AddEdge(1, 2)
g.AddEdge(1, 4)
g.AddEdge(2, 5)
g.AddEdge(2, 6)
#g.AddEdge(4, 6)
#g.AddEdge(5, 6)

print("Adjacency list for storing graph")


g.printAdjList()

BFS(g,0,8)

if name == " main " :


main()

Note: The above code uses lab 4 code for creating adjacency list.

Output

30 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Depth first search (DFS):


Depth First Search (DFS) is an uninformed search technique that searches deeper into the problem
space. Breadth-first search always generates successor of the deepest unexpanded node. It uses
last-in first-out stack for keeping the unexpanded nodes. More commonly, depth-first search is
implemented recursively, with the recursion stack taking the place of an explicit node stack.

ALGORITHM: Depth first search:


1. In Depth first search edges are explored out of the most recently discovered vertex. Only
edges to unexplored vertices are explored.
2. When all of vertices edges have been explored, the search "back-tracks" to explore edges
leaving the vertex from which vertex \Vas discovered.
3. The process continues until we have discovered all the vertices that are reachable from the
original source vertex.
4. If any undiscovered vertices remain, then one of them is selected as a new source vertex.
5. This process if repeated until all vertices are discovered.

Python has LIFOQueue Class under Queue module that is used as Stack. The code uses same
algo as in BFS with change of Queue. The Graph implementation and main remains same .
The function DFS is called

def DFS(tm, s,
g):visited = []

# Create a queue for


BFSlifoq =
q.LifoQueue()

# Mark the source node as visited and enqueue


itlifoq.put(s)
state = s
print("BFS Search path")
while state != g and not
lifoq.empty():# Dequeue a vertex
from
# queue and print
itstate =
lifoq.get()

if state not in visited:


visited.append(state)
else:
state =
lifoq.get()
print(state, end=" ")

# Get all adjacent vertices of


the# dequeued vertex s.
# If an adjacent has not been
visited,# then mark it visited and

31 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

else:
print("\nGoal not found")

Exercise:

1. Use the example code and implement depth limit search, a variation of depth-first search.
2. Use a vacuum cleaner reflex agent to traverse the following state space using BFS and DFS.
You may use lab 3 code to show how the Agent will work its way to achieve the goal. The
outputshould show the appropriate actions as well as search traversal.

32 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 06

INFORMED SEARCH TECHNIQUES


OBJECTIVE
Implementing shortest path using A* search technique.

THEORY
Informed A* Search:
A* search is an informed search algorithm used for path-finding and graph traversal.
It combinesthe advantages of both Dijkstra‘s algorithm (in that it can find a shortest
path) and Greedy BestFirst-Search (in that it can use a heuristic to guide search). It
combines the information that Dijkstra‘s algorithm uses (favoring vertices that are
close to the starting point) and information that Best-First-Search uses (favoring
vertices that are closer to the goal).
Let g(n) represent the exact cost of the path from the starting point to any vertex n, and h(n)
represent the heuristic estimated cost from vertex n to the goal. Dijkstra‘s algorithms builds a
priority queue of nodes ordered on their g(n) values. Best-First-Search employs a priority queue
of nodes ordered on h(n) values.
A* balances the two as it moves from the starting point to the goal. It builds a priority
queue of nodes ordered on f(n) = g(n) + h(n) which is the total estimated path cost
through the node n.

ALGORITHM: Informed A* Search:

Exercise:
Fill in the missing code of A* search code provided below for the following state
graphs. In parti the output is provided which should match with the output of your
code:
from collections import
defaultdictimport queue as q
‘’’ Node object will hold name of node, parent node , g(n),
h(n) and f(n)’’’class Node:
def init (self, name, parent,g=-0,h=-1):

# initialize self.name, self.parent, self.g, self.h and use self.calcf to initialize self.f
# check if parent is None then self.g is same as parameter , else self.g should be parent g value + g
#check if h=-1 then self.f should be 0 else calculated

def getName(self):
33 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

# return the value of name attribute

def geth(self):
# return the h value
def getparent(self):
# return the value of parent attribute

def calcf(self):
# calculate f(n) and update f attribute

def printNode(self):
print("Node name:",self.name, " parent:", self.parent, " fn:", self.f)

class DirGraph:

# Code to create Adjacency List

def getNodeh(nodelist, n):

# return the h value from nodelist dictionary e.g. for nodelist {0:2, 1:3,4:5} and n =4 , the
function shouldreturn 5

def astar(graph, nodelist, start)

‘’’Prints the selected node with f(n) cost based on A* search ‘’’

# Create start and end node to insert in queue. The name of node will be used to iterate graph
adjacency liststart_node = Node(start, None, 0, getNodeh(nodelist,start))

end_node = Node(end, None,0,0)


# Priority Queue is used and nodes are inserted as tuple of
f(n) and node# Priority Queue will sort nodes based on tuple
f

pq=q.PriorityQueue()
pq.put((start_node.f,start_no
de))

current_state =
pq.get()flag=True
print("State Selected: ",current_state[1].getName()," Total Cost fn:
",current_state[1].f)# loop until either goal found or flag is false which
indicate queue is emptry
while current_state[1].getName() !=
end_node.getName() and flag:for i in

34 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

graph.adjlist[current_state[1].getName()]:
#print(i)
if i!=None:
state=Node(i[0], current_state[1],i[1] ,
getNodeh(nodelist,i[0]))#print(state.printNode())
pq.put((state.f,
state))current_state =
pq.get()
print("State Selected: ",current_state[1].getName()," Total Cost fn:
",current_state[1].f)if current_state==None:
flag=False

def
main():
nodes =
7
g = DirGraph(nodes)
#h value for each node from goal
state 3nodelist={0:3,1:2,2:1,3:0}
# create Graph provided in part i

print("Adjacency list for storing


graph")g.printAdjList()
astar(g,nodelist,0,5)

if name == " main ":


main()

i) Find the Goal with optimal cost between node ‗S‘ to Node ‗G‘

35 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

ii) Use the updated code in part i and add code to track the path between node
‗Arad‘ to node ‗Bucharest‘ using Astar

36 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 07

IMPLEMENTING LOCAL SEARCH TECHNIQUES


OBJECTIVE
Implement local search technique using genetic algorithm.

THEORY

Genetic Algorithm:
Genetic Algorithm (GA) is a search-based optimization technique based on the principles of
Genetics and Natural Selection. It is frequently used to find optimal or near-optimal solutions to
difficult problems that otherwise would take a lifetime to solve.
GA generates a population of points at each iteration. The best point in the population approaches
an optimal solution. Selects the next population by computation, which uses random number
generators.

Five phases are considered in a genetic algorithm.


1. Initial population
2. Fitness function
3. Selection
4. Crossover
5. Mutation

Initial Population:
The process begins with a set of individuals which is called a Population. Each individual is a
solution to the problem you want to solve.
An individual is characterized by a set of parameters (variables) known as Genes. Genes are joined
into a string to form a Chromosome (solution).
In a genetic algorithm, the set of genes of an individual is represented using a string, in terms of
an alphabet. Usually, binary values are used (a string of 1s and 0s). We say that we encode the
genes in a chromosome.

Fitness Function:
The fitness function determines how fit an individual is (the ability of an individual to compete
with other individuals). It gives a fitness score to each individual. The probability that an
individual will be selected for reproduction is based on its fitness score.
Selection:
The idea of selection phase is to select the fittest individuals and let them pass their genes to the
next generation.

37 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Two pairs of individuals (parents) are selected based on their fitness scores. Individuals with high
fitness have more chance to be selected for reproduction.
Crossover:
Crossover is the most significant phase in a genetic algorithm. For each pair of parents to be mated,
a crossover point is chosen at random from within the genes.
Offspring are created by exchanging the genes of parents among themselves until the crossover
point is reached.
Mutation:
In certain new offspring formed, some of their genes can be subjected to a mutation with a low
random probability. This implies that some of the bits in the bit string can be flipped.

ALGORITHM: Genetic Algorithm:


We start with an initial population (which may be generated at random or seeded by other
heuristics), and select parents from this population for mating. Apply crossover and mutation
operators on the parents to generate new offspring. Finally, these offspring replace the existing
individuals in the population and the process repeats. In this way genetic algorithms actually try
to mimic the human evolution to some extent.

Exercise:
Implement a Genetic algorithm to the MAXONE problem. We toss a fair coin 6 times and get
the following initial population:
s1= 1111010101 with f (s1) = 7 (chances of 1’s)
s2= 0111000101 with f (s2) = 5 (chane of 1’s)
38 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

s3= 1110110101 with f (s3) = 7


s4= 0100010011 with f (s4) = 4
s5= 1110111101 with f (s5) = 8
s6= 0100110000 with f (s6) = 3
Initial Population (set of solutions) = 6
Fitness (Quality of solution) = each solution is generally represented as a string of binary
numbers, known as a chromosome. The most common fitness function for sum of number of 1’s.
Selection = Tournament is played between 3 set of member population and maxone is selected as
winner
Crossover point = exchange data after single cross over in the the list, randomly selected for
each round of tournament.
Mutation point : random point selected for mutation

GA Code (Coin Toss Problem):


import random
import numpy as np

def calfitness(S):
fit=[]
total=0
print("Fitness")
for i in S:
fit.append(i.count(1))
total+=i.count(1)
print(fit)

print(total)
return fit;

def selection(population, fitnesses): # tournament selection


tournament = random.sample(range(len(population)), k=3)
print(tournament)
tournament_fitnesses = [fitnesses[i] for i in tournament]
print(tournament_fitnesses)
winner_index = tournament[np.argmax(tournament_fitnesses)]
print(winner_index)
return winner_index

def crossOver(p1,p2):
xo_point = random.randint(1, len(p1)/2 - 1)
print("Single point", xo_point)
return ([p1[:xo_point] + p2[xo_point:],p2[:xo_point] + p1[xo_point:]])

39 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

def mutation(individual):
for i in range(len(individual)):
if random.random() < 0.1:
individual = individual[:i] + [1-individual[i]] + individual[i + 1:]
return individual

# Start of program
S=[[0,0,1,1,1,1,1,0,0,1],[0,1,0,1,0,0,1,1,1,1],[0,1,1,0,1,1,0,1,1,1],[0,1,0,1,1,1,0,0,1,1],[0,0,1,0,1,1,1,1,1,1],[0,0,1,0,1,
1,0,1,1,1]]
print("Initial Population=",S)
fit=calfitness(S)
p1_index=selection(S,fit)
print(p1_index)
p2_index=selection(S,fit)
print(p2_index)
while p1_index==p2_index:
p2_index = selection(S, fit)
print(p2_index)
offspring1, offspring2 = crossOver(S[p1_index], S[p2_index])
print("Child1:", offspring1)
print("Child2:", offspring2)
S.append(mutation(offspring1))
S.append(mutation(offspring2))
print(S)

Lab Tasks:
1. Run the given code of Genetic Algorithm (Coin Toss Problem) and show the output.

2. The current code only has tournament/selection between two parent . The code should be
updated to have population size/2 time tournament so that maximum parent can be selected. The
output should be like the following sample output

40 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

3. Update main program so that the program can run for 10 iterations (we can call it as Generation).
The population should be printed at end of each Generation and output should be labeled such. Use
list(zip(list1, list2) to get the following sample output.

3. In given code the values of chromosomes are hardcoded, you may take input values of
chromosomes at run time.
4. Create a checkDuplicate(S) function that checks the offspring in the population and returns True if
the offspring is duplicate (meaning it is already in the population) . In this case the new offspring
should be generated.

41 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 08

OPEN ENDED LAB

OBJECTIVE
GAME SEARCH
One of the biggest areas of research in modern Artificial Intelligence is in making computer players
for popular games. Make your own four depth binary tree. Solve the decision tree by applying gaming
theory of your own choice (either apply Minimax or Alpha beta pruning etc. orany other technique),
make a choice of your own values ranging from 0 to 50:

• The game will be two player game, one will be user and other will be AI agent
• Name and design of levels must be distinct for each student‘s game binary tree

42 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 09

NUMPY LIBRARY
OBJECTIVE
Implement N-dimensional array using NumPy library. Also study predicate logic and propositional logic
using python.

THEORY

Introduction:
Python is a great general-purpose programming language on its own, but with the help of a few
popular libraries (numpy, scipy, matplotlib) it becomes a powerful environment for scientific
computing. NumPy is one of the efficient open-source add-on modules to python that provide
common mathematical and numerical routines in pre-compiled, fast functions.
NumPy (Numeric Python) is a library for the Python programming language, adding support for
large, multi-dimensional arrays and matrices, along with a large collection of high-level
mathematical functions to operate on these arrays.

Installation:
Installation files available at: https://www.lfd.uci.edu/~gohlke/pythonlibs/
Follow the link on this page to download the official releases, or use IDE package installation
mechanism to install numpy package. Altenatively you can install using pip command

Importing the NumPy module:


There are several ways to import NumPy. The standard approach is to use a simple import
statement:
import numpy
However, for large amounts of calls to NumPy functions, it can become tedious to write numpy.X
over and over again. Instead, it is common to import under the briefer name np:
Import numpy as np
This statement will allow us to access NumPy objects using np.X instead of numpy. It is also
possible to import NumPy directly into the current namespace so that we don't have to use dot
notation at all, but rather simply call the functions as if they were built-in:
from numpy import *
In this statement, all functions will be loaded into the local namespace.

43 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Arrays in NumPy:
NumPy‘s main object is the homogeneous multidimensional array.
• It is a table of elements (usually numbers), all of the same type.
• In NumPy dimensions are called axes. The number of axes is rank.
• NumPy‘s array class is called ndarray. It is also known by the alias array.
Example :
[[ 1, 2, 3],
[ 4, 2, 5]] Here, rank = 2 (as it is 2-
dimensional or it has 2 axes)
first dimension(axis) length = 2, second dimension has length = 3 overall
shape can be expressed as: (2, 3)

ndarray: The N-dimensional arrays:


The central feature of NumPy is the array object class. Arrays are similar to lists in Python,
except that every element of an array must be of the same type, typically a numeric type like
float or int. Arrays make operations with large amounts of numeric data very fast and are
generally much more efficient than lists.
Use the np.array ( ) constructor to create an array with any number of dimensions.
np.array (object, dtype=None)
Values to be used in creating the array. This can be a sequence (to create a 1-d array), a sequence
of sequences (for a 2-d array), a sequence of sequences of sequences, and so on. Each sequence
may be either a list or a tuple. To force the new array to be a given type, use one of the type
words as the second argument. For example, array ([1, 2, 3], dtype=np.float_) will give you an
array with those three values converted to floating-point type.

Example:

Representation of 1D, 2D, 3D array:


44 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

One-dimensional arrays are then printed as rows, bidimensionals as matrices and tridimensional
as lists of matrices
a = np.arange(6) # 1d array
>>>print(a)
[0 1 2 3 4 5]
>>> b = np.arange(12).reshape(4,3) # 2d array
>>>print(b)
[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]
[ 9 10 11]]
>>>
>>> c = np.arange(24).reshape(2,3,4) # 3d array
>>> print(c)
[[[ 0 1 2 3]
[ 4 5 6 7]
[ 8 9 10 11]]
[[12 13 14 15]
[16 17 18 19]
[20 21 22 23]]]
Two-dimensional arrays:
Arrays can be multidimensional. Unlike lists, different axes are accessed using commas inside
bracket notation.
Example: Output:

You can use slicing to get one row or column. A slice operation has this general form:
M [rows, cols]
In this form, rows and cols may be either regular Python slice operations (such as 2:5 to select
the third through fifth items), or they may be just ―:‖ to select all the elements in that
dimension. In this example, we extract a 2×3 submatrix, containing rows 0 and 1, and columns
0, 1, and 2.

45 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Numpy array is very much similar to python list , so if we have python list, then
why weneed numpy array?
There are several benefit using numpy array:
1) Less memory over python list
2) Fast
3) Convenient

The arange() function: Arithmetic progression:


The np.arange() function to build a vector containing an arithmetic progression.
arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per
the interval. The interval mentioned is half opened i.e. [Start, Stop)
Parameters :
start : [optional] start of interval range. By default start = 0 stop
: end of interval range
step : [optional] step size of interval. By default step size = 1,
For any output out, this is the distance between two adjacent values, out[i+1] - out[i].
dtype : type of output array
Basic Functions:
5:

Example: Output:

46 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Example:

The functions zeros and ones create new arrays of specified dimensions filled with these values.
These are perhaps the most commonly used functions to create new arrays:

The eye function returns matrices with ones along the kth diagonal:

Example: Output:

Array iteration:
It is possible to iterate over arrays in a manner similar to that of lists:
>>> a = np.array([1, 4, 5], int)
>>> for x in a:
print (x)

For multidimensional arrays, iteration proceeds over the first axis such that each loop returns a
subsection of the array:
>>> a = np.array([[1, 2], [3, 4], [5, 6]], float)
>>> for x in a:
print (x)

Multiple assignment can also be used with array iteration:

47 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

>>> a = np.array([[1, 2], [3, 4], [5, 6]], float)


>>> for (x, y) in a: print
(x * y)

Basic operations:
• Operations on single array: We can use overloaded arithmetic operators to do
elementwise operation on array to create a new array. In case of +=, -=, *= operators,
theexsisting array is modified.
• Unary operators: Many unary operations are provided as a method of ndarray class.
This includes sum, min, max, etc. These functions can also be applied row-wise or
column-wise by setting an axis parameter.

• Binary operators: These operations apply on array elementwise and a new array is
created. You can use all basic arithmetic operators like +, -, /, , etc. In case of +=, -=, =
operators, the exsisting array is modified.

• Universal functions (ufunc): NumPy provides familiar mathematical functions such


as sin, cos, exp, etc. These functions also operate elementwise on an array, producing an
arrayas output.
Exercise:
1. Write a Python program to convert a list of numeric value into a one-dimensional
NumPyarray.

2. Create a 3x3 matrix with values ranging from 2 to 10

3. Create a null vector of size 15 and update fifth value to 12 and ninth value to 17

4. Take 2D and 3D array and perform transpose function.

5. Write a Python program to find the real and imaginary parts of an array of complex numbers.

6. Multiply a 5x3 matrix by a 3x2 matrix create a real matrix product using dot ( ).

7. Create array by 2x3 and perform following function:

• Number of dimension(ndim)
• Total number of element/size in an array
• What type of array stores in memory(dtype)

8. Write a Python program to create a 3-D array with ones on the diagonal and zeros elsewhere.

48 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 09

INTRODUCTION TO FUZZY LOGIC

OBJECTIVE: Implement fuzzy logic system using Scikit fuzzy module.


THEORY

Introduction: Fuzzy Logic Systems (FLS) produce acceptable but definite output in response
to incomplete, ambiguous, distorted, or inaccurate (fuzzy) input.
Fuzzy Logic (FL) is a method of reasoning that resembles human reasoning. The approach of FL
imitates the way of decision making in humans that involves all intermediate possibilities
between digital values YES and NO.
The conventional logic block that a computer can understand takes precise input and produces a
definite output as TRUE or FALSE, which is equivalent to human‘s YES or NO.
The inventor of fuzzy logic, Lotfi Zadeh, observed that unlike computers, the human decision
making includes a range of possibilities between YES and NO, such as −
CERTAINLY YES
POSSIBLY YES
CANNOT SAY
POSSIBLY NO
CERTAINLY NO
The fuzzy logic works on the levels of possibilities of input to achieve the definite output.

Why Fuzzy Logic?


Fuzzy logic is useful for commercial and practical purposes.
• It can control machines and consumer products.
• It may not give accurate reasoning, but acceptable reasoning.
• Fuzzy logic helps to deal with the uncertainty in engineering.
• Fuzzy logic has been used in numerous applications such as facial pattern recognition, air
conditioners, washing machines, vacuum cleaners, transmission systems, control of subway
systems and unmanned helicopters, weather forecasting systems etc

Fuzzy Set:
Fuzzy logic starts with the concept of a fuzzy set. It can contain elements with only a partial
degree of membership. A Fuzzy Set is any set that allows its members to have different grades of
membership (membership function) in the interval [0,1].
The concept of a set is fundamental to mathematics. However, our own language is also the
supreme expression of sets. For example, car indicates the set of cars. When we say a car, we
mean one out of the set of cars.
The classical example in fuzzy sets is tall men. The elements of the fuzzy set ―tall men‖ are all
men, but their degrees of membership depend on their height.

49 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Name
Height, cm Degree of Membership Crisp Fuzzy
Chris
Mark John Tom
David Mike
Bob
Steven Bill
Peter 208
205
198
181
179
172
167
158
155
152 1
1
1
1
0
0
0
0
0
0 1.00
1.00
0.98
0.82
0.78
0.24
0.15
0.06
0.01
0.00
• The x-axis represents the universe of discourse – the range of all possible values applicable
to a chosen variable. In our case, the variable is the man height. According to this representation,
the universe of men‘s heights consists of all tall men.
• The y-axis represents the membership value of the fuzzy set. In our case, the fuzzy set of
―tall men‖ maps height values into corresponding membership values.

Fuzzy set operation:


A fuzzy set operation is an operation on fuzzy sets. These operations are generalization of crisp
set operations. There is more than one possible generalization. The most widely used operations
are called standard fuzzy set operations. There are three operations: fuzzy complements, fuzzy
intersections, and fuzzy unions.
Fuzzy complements:
50 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

The membership function of the Complement of a Fuzzy set A with membership function is
defined as the negation of the specified membership function. This is called the negation criterion.

The Complement operation in Fuzzy set theory is the equivalent of the NOT operation in Boolean
algebra.
Fuzzy Union
The membership function of the Union of two fuzzy sets A and B with membership functions and
respectively is defined as the maximum of the two individual membership functions. This is
called the maximum criterion.
The Union operation in Fuzzy set theory is the equivalent of the OR operation in Boolean algebra.
Fuzzy Intersection
The membership function of the Intersection of two fuzzy sets A and B with membership
functions and respectively is defined as the minimum of the two individual membership
functions. This is called the minimum criterion.
The Intersection operation in Fuzzy set theory is the equivalent of the AND operation in Boolean
algebra.
SciKit Fuzzy: Scikit-fuzzy is fuzzy logic python tool kit for SciPy (a.k.a. skfuzzy): Fuzzy Logic
Toolbox for Python This package implements many useful tools and functions for computation
and projects involving fuzzy logic, also known as grey logic.

Scikit-Fuzzy is a collection of fuzzy logic algorithms intended for use in the SciPy Stack, written
in the Python computing language. This SciKit is developed by the SciPy community This
package that works with NumPy arrays. The package is imported as skfuzzy:

Through the recommended import statement uses an alias:

Example: fuzzy_not operator, a.k.a. complement of a fuzzy set.

While most functions are available in the base namespace, the package is factored with a logical
grouping of functions in sub modules. If the base namespace appears overwhelming, we
recommend exploring them individually. These include:
fuzz.membership: Fuzzy membership function generation
fuzz.defuzzify: Defuzzification algorithms to return crisp results from fuzzy sets fuzz.fuzzymath:
The core of scikit-fuzzy, containing the majority of the most common fuzzy logic operations.
fuzz.intervals : Interval mathematics. The restricted Dong, Shah, & Wong SW) methods for fuzzy
set math live here.
fuzz.image: Limited fuzzy logic image processing operations.
fuzz.cluster: Fuzzy c-means clustering.
fuzz.filters : Fuzzy Inference Ruled by Else-action (FIRE) filters in 1D and 2D.

(Detailed about fuzzy functions, follow this link: http://pythonhosted.org/scikit-


fuzzy/api/skfuzzy.html)

Example use of membership function


import numpy as np import skfuzzy as fuzz
from matplotlib import pyplot as plt
51 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

# [0, 10]
start = 0
stop = 10 + 0.001
step = 0.25
x = np.arange(start, stop, step) print(x)

# Triangular membership function


trimf = fuzz.trimf(x, [0, 5, 10])
fig_scale = 1.5
plt.figure(figsize=(6.4 * fig_scale, 4.8 * fig_scale))

# 3 rows, 1 col, index from 1 plt.subplot(311)


plt.title("Fuzzy Membership Function") plt.plot(x, trimf, label="Triangle") plt.legend(loc="upper
right")

#Saving the plot file


plt.savefig("1-memship-function.png") plt.show()
Output

EXERCISE:
Generate universe variables of Quality and service on subjective ranges [0, 10] and do the
following questions.
1. Create the arrays of the provided range and generate membership using a triangular
method using the following variables and their range. Plot graph for the variables.

Low Quality: 0-5, peak: 0


Moderate Quality : 0-10 Peak: 5
High Quality: 5-10 peak: 10
Low Service : 0-5, peak: 0
Moderate Service : 0-10 peak: 5
High Service: 5-10 peak: 10

2. Apply union and intersection in fuzzy using the build-in fuzzy function.
3. Use cartesian addition of fuzzy membership vector using an algebraic method using
cartadd(x,y)
4. Implement a Cartesian product of three fuzzy membership vectors of Quality and Service
universes using cartprod(x,y). E.g. one relation R1= low quality x low service and another
R2=low quality x moderate service. Apply cartesian product to What did you understand
from the result?

5. Implement max-min composition of Quality x Service fuzzy relation matrices from

52 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 10 INTRODUCTION TO FUZZY LOGIC


OBJECTIVE: Implement fuzzy logic system using Scikit fuzzy module.

THEORY
Fuzzy Logic Systems (FLS) produce acceptable but definite output in response to incomplete,
ambiguous, distorted, or inaccurate (fuzzy) input.
Fuzzy Logic (FL) is a method of reasoning that resembles human reasoning. The approach of FL
imitates the way of decision making in humans that involves all intermediate possibilities between
digital values YES and NO.

The conventional logic block that a computer can understand takes precise input and produces a
definite output as TRUE or FALSE, which is equivalent to human‘s YES or NO.

The inventor of fuzzy logic, Lotfi Zadeh, observed that unlike computers, the human decision
making includes a range of possibilities between YES and NO, such as −
CERTAINLY YES
POSSIBLY YES
CANNOT SAY
POSSIBLY NO
CERTAINLY NO
The fuzzy logic works on the levels of possibilities of input to achieve the definite output.

Why Fuzzy Logic?


Fuzzy logic is useful for commercial and practical purposes.
• It can control machines and consumer products.
• It may not give accurate reasoning, but acceptable reasoning.
• Fuzzy logic helps to deal with the uncertainty in engineering.
• Fuzzy logic has been used in numerous applications such as facial pattern recognition, air
conditioners, washing machines, vacuum cleaners, transmission systems, control of
subway systems and unmanned helicopters, weather forecasting systems etc

Fuzzy Set:
Fuzzy logic starts with the concept of a fuzzy set. It can contain elements with only a partial degree
of membership. A Fuzzy Set is any set that allows its members to have different grades of
membership (membership function) in the interval [0,1].

53 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

The concept of a set is fundamental to mathematics. However, our own language is also the
supreme expression of sets. For example, car indicates the set of cars. When we say a car, we
mean one out of the set of cars.
The classical example in fuzzy sets is tall men. The elements of the fuzzy set ―tall men‖ are all
men, but their degrees of membership depend on their height.
Degree of
Name Membership
Height, cm Crisp Fuzzy
Chris 208 1 1.00
205 1 1.00
Mark
John 198 1 0.98
181 1 0.82
Tom
179 0 0.78
David 172 0 0.24
167 0 0.15
Mike 158 0 0.06
Bob 155 0 0.01
Steven 152 0 0.00
Bill
Peter

• The x-axis represents the universe of discourse – the range of all possible values applicableto a
chosen variable. In our case, the variable is the man height. According to this representation,
the universe of men‘s heights consists of all tall men.
• The y-axis represents the membership value of the fuzzy set. In our case, the fuzzy set of
―tall men‖ maps height values into corresponding membership values.

54 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Fuzzy set operation:


A fuzzy set operation is an operation on fuzzy sets. These operations are generalization of crisp
set operations. There is more than one possible generalization. The most widely used operations
are called standard fuzzy set operations. There are three operations: fuzzy complements, fuzzy
intersections, and fuzzy unions.
Fuzzy complements:
The membership function of the Complement of a Fuzzy set A with membership function is
defined as the negation of the specified membership
function. This is called the negation criterion.

The Complement operation in Fuzzy set theory is the equivalent of the NOT operation in Boolean
algebra.
Fuzzy Union
The membership function of the Union of two fuzzy sets A and B with membership functions and
respectively is defined as the maximum of the two individual membership functions. This is called
the maximum criterion.

The Union operation in Fuzzy set theory is the equivalent of the OR operation in Boolean algebra.
Fuzzy Intersection
The membership function of the Intersection of two fuzzy sets A and B with membership functions
and respectively is defined as the minimum of the two individual membership functions. This is
called the minimum criterion.

The Intersection operation in Fuzzy set theory is the equivalent of the AND operation in Boolean
algebra.

SciKit Fuzzy:
Scikit-fuzzy is fuzzy logic python tool kit for SciPy (a.k.a. skfuzzy): Fuzzy Logic Toolbox for
Python This package implements many useful tools and functions for computation and projects
involving fuzzy logic, also known as grey logic.
Scikit-Fuzzy is a collection of fuzzy logic algorithms intended for use in the SciPy Stack, written
in the Python computing language. This SciKit is developed by the SciPy community This
package that works with NumPy arrays. The package is imported as skfuzzy:
import skfuzzy

Through the recommended import statement uses an alias:


import skfuzzy as fuzz

55 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Example:fuzzy_not operator, a.k.a. complement of a fuzzy set.

While most functions are available in the base namespace, the package is factored with a logical
grouping of functions in sub modules. If the base namespace appears overwhelming, we
recommend exploring them individually. These include:
fuzz.membership: Fuzzy membership function generation
fuzz.defuzzify: Defuzzification algorithms to return crisp results from fuzzy sets
fuzz.fuzzymath: The core of scikit-fuzzy, containing the majority of the most common fuzzy
logic operations.
fuzz.intervals : Interval mathematics. The restricted Dong, Shah, & Wong SW) methods for
fuzzy set math live here.
fuzz.image: Limited fuzzy logic image processing operations.
fuzz.cluster: Fuzzy c-means clustering.
fuzz.filters : Fuzzy Inference Ruled by Else-action (FIRE) filters in 1D and
2D.

(Detailed about fuzzy functions, follow this link:


http://pythonhosted.org/scikit-fuzzy/api/skfuzzy.html)

Example use of membership function

import numpy as np
import skfuzzy as fuzz
from matplotlib import pyplot as plt

# [0, 10]
start = 0
stop = 10 + 0.001
step = 0.25
x = np.arange(start, stop, step)
print(x)

# Triangular membership function

56 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

trimf = fuzz.trimf(x, [0, 5, 10])


fig_scale = 1.5
plt.figure(figsize=(6.4 * fig_scale, 4.8 * fig_scale))

# 3 rows, 1 col, index from 1


plt.subplot(311)
plt.title("Fuzzy Membership Function")
plt.plot(x, trimf, label="Triangle")
plt.legend(loc="upper right")

#Saving the plot file


plt.savefig("1-memship-function.png")
plt.show()
Output

EXERCISE:

Generate universe variables of Quality and service on subjective ranges [0, 10] and do the
following questions.
1. Create the arrays of the provided range and generate membership using a triangular method
using the following variables and their range. Plot graph for the variables.

Low Quality: 0-5, peak: 0


Moderate Quality : 0-10 Peak: 5
High Quality: 5-10 peak: 10
Low Service : 0-5, peak: 0
Moderate Service : 0-10 peak: 5

57 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

High Service: 5-10 peak: 10

2. Apply union and intersection in fuzzy using the build-in fuzzy function.

3. Use cartesian addition of fuzzy membership vector using an algebraic method using
cartadd(x,y)

4. Implement a Cartesian product of three fuzzy membership vectors of Quality and Service
universes using cartprod(x,y). E.g. one relation R1= low quality x low service and another
R2=low quality x moderate service. Apply cartesian product to What did you understand from
the result?

5. Implement max-min composition of Quality x Service fuzzy relation matrices from question
4.

58 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 11

Fuzzification and Defuzzification


OBJECTIVE
Implement fuzzification and defuzzification sing Scikit fuzzy in fuzzy logic.

THEORY

Fuzzification
Fuzzification is the process of making a crisp quantity fuzzy. This is done by simply recognizing
that many of the quantities that are considered to be crisp and deterministic are not deterministic
at all; they carry considerable uncertainty. If the form of uncertainty happens to arise because of
imprecision, ambiguity, or vagueness, then the variable is probably fuzzy and can be represented
by a membership function.
Membership function (MF) represents the degree of truth in fuzzy logic. MF is a curve that defines
how each point in the input space is mapped to a membership value (or degree of membership)
between 0 and 1. Following are a few important points relating to the membership function −
• Membership functions characterize fuzziness (i.e., all the information in fuzzy set)
• Membership functions can be defined as a technique to solve practical problems by experience
rather than knowledge.
• Membership functions are represented by graphical forms.
Membership functions (MFs) are the building blocks of fuzzy set theory, i.e., fuzziness in a fuzzy
set is determined by its MF. Most widely used MFs in the fuzzy logic are triangular, trapezoidal,
Gaussian and bell-shaped functions.
The Tringle membership function was covered in the last lab. This lab deals with the other
membership functions that are commonly used.
Trapezoidal membership function:
A trapezoidal MFis specified by four parameters {a, b, c, d}

The parameters {a, b, c, d} with a < b < c < d determine the x coordinates of the four corners of
the underlying trapezoidal MF. Trapezoidal MFs can be asymmetric, depending on the relations a
≤ b and c ≤ d.
Syntax: trapmf (Trapezoidal membership function generator)
skfuzzy.trapmf(x, abcd)
Parameter:x:1D array (Independent variable)
abcd: 1D array, length 4 (Four-element vector. Ensure a <= b <= c <= d)

59 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Return:y: 1D array (Trapezoidal membership function)


Example:

Output:

Gaussian membership function:


A Gaussian MF is specified by two parameters {m, σ}. The parameters m and σ represent the
centre and width of the Gaussian MF:

Syntax: Gaussmf (Gaussian fuzzy membership function)


skfuzzy.gaussmf(x, mean, sigma)
Parameter:x:1d array or iterable (Independent variable)
mean: float (Gaussian parameter for center (mean) value)
sigma: float (Gaussian parameter for standard deviation)
Return: y: 1D array (Gaussian membership function for x)

60 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Example:

Output:

Bell-shaped membership function:


A bell-shaped MF is specified by three parameters {m, σ, a}. The parameters m and σ represent
the centre and width of the bell-shaped MF, respectively. Parameter a, usually positive, controls
the slope of the MF

Syntax: g bellmf (Generalized Bell function fuzzy membership


generator) skfuzzy.gbellmf(x, a, b, c) Example:

61 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Output:

Defuzzification
Fuzzy logic calculations are excellent tools, but to use them the fuzzy result must be converted
back into a single number. This is known as defuzzification.
There are several possible methods for defuzzification, exposed via skfuzzy.defuzz.

62 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

EXERCISE:
1. Plot linear and Gaussian membership function for each temperature state (cold, warm, and hot)
has a membership value defined at all temperatures between 0 and 40 degrees (F).
a) Define the range of each temperature fuzzy state and plot the membership values of the
trapezoidal function.
b) For [σ, m] values [5.122, 10.72], [4.481 19.21], [4.768 25.52], respectively, plot Gaussian
membership values for the temperature states.

63 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

The output will look alike:

2. Implement bell-shaped and triangle functions from scratch.

3. Use the defuzzification centroid method on the resultant fuzzy set of temperature states in Q1.
To aggregate the three fuzzy sets use numpy fmax(fset1, fset2) function.

64 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 12

FUZZY CONTROL SYSTEM


OBJECTIVE: Implement fuzzy rules and control system using Scikit fuzzy module.

THEORY

Fuzzy Rule-Based Systems

In the field of artificial intelligence (machine intelligence), there are various ways to represent
knowledge.Perhaps the most common way to represent human knowledge is to form it into natural
languageexpressions of the type

IF premise (antecedent), THEN conclusion


(consequent)

The form in Expression defined above is commonly referred to as the IF–THEN rule-based
form; thisform is generally referred to as the deductive form. It typically expresses an
inference such that if we know a fact (premise, hypothesis, antecedent), then we can infer, or
derive, another fact called a conclusion (consequent).

Most rule-based systems involve more than one rule. The process of obtaining the overall
consequent(conclusion) from the individual consequents contributed by each rule in the rule-base
is known as aggregation of rules.

Conjunctive system of rules: In the case of a system of rules that must be jointly
satisfied,the rules are connected by “and” connectives.

Disjunctive system of rules: For the case of a disjunctive system of rules where the satisfaction of
at leastone rule is required, the rules are connected by the “or” connectives.

Example:

Rule 1 IF x1 is A11 (small mass) and x2 is A12 (high velocity


),THEN y is B1 (medium energy)
Rule 2 IF x1 is A21 (large mass) or x2 is A22 (medium
velocity ),THEN y is B2 (high energy)

Set up the Fuzzy Control System using Scikit Fuzzy


Scikit-fuzzy is fuzzy logic python tool kit for SciPy (a.k.a. skfuzzy): Fuzzy Logic Toolbox for
Python This package implements many useful tools and functions for computation and projects
involving fuzzy logic, also known as grey logic.

65 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

To setup fuzzy control system , control API is used


import skfuzzy.control as ctrl

Through the recommended import statement uses an alias:


import skfuzzy as fuzz

To create rules control API offers antecendant and consequent functions


ctrl.Antecedent(universe range, ‘name of universe’)

ctrl.Consequent(universe range, 'name of output universe')

Fuzzification
Fuzzification involves generating variables of the universe and memberships of each member
using themembership function
The fuzzification process can use any membership function or a quick function automf
that can becalled

error.automf(names=names)
This convenience function allows quick construction of fuzzy variables with overlapping,
triangularmembership functions. It uses a standard naming convention defined for 'quality'
as:
* dismal, * poor, * mediocre, * average (always middle), * decent, * good, *
excellentand
for 'quant' as: * lowest, * lower, * low, * average (always middle), * high, * higher, * highest
where the names on either side of 'average' are used as needed to create 3, 5, or 7 membership
functions.

Define Rules
Ctrl.Rule(antecedent, consequent, label, and_func, or_func)
Rule in a fuzzy system, connecting antecedent(s) to consequent(s). Multiple rules can be defined
usingthe Rule method
rule0 = ctrl.Rule(antecedent=((A11['small mass'] & A12['high velocity']), consequent=B1['medium energy']
, label='rule example')

Create Control System


The rules are added to the control systems
(Detailed about fuzzy functions, follow this link: http://pythonhosted.org/scikit-
system = ctrl.ControlSystem(rules=[rule0, rule1, rule2, rule3, rule4])
fuzzy/api/skfuzzy.html)
66 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

In order to simulate this control system, create ControlSystemSimulation. This will be result in
simulatingthe controller applied to a specific set of circumstances of inputs.

sim = ctrl.ControlSystemSimulation(system)

The control can now be simulated by simply specifying the inputs and calling the compute()
method
Example

import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl

# New Antecedent/Consequent objects hold universe variables and membership


# functions
quality = ctrl.Antecedent(np.arange(0, 11, 1), 'quality')
service = ctrl.Antecedent(np.arange(0, 11, 1), 'service')
tip = ctrl.Consequent(np.arange(0, 26, 1), 'tip')

# Auto-membership function population is possible with .automf(3, 5, or 7)


quality.automf(3)
service.automf(3)

# Custom membership functions can be built interactively with a familiar,


# Pythonic API
tip['low'] = fuzz.trimf(tip.universe, [0, 0, 13])
tip['medium'] = fuzz.trimf(tip.universe, [0, 13, 25])
tip['high'] = fuzz.trimf(tip.universe, [13, 25, 25])

quality['average'].view()
service.view()
tip.view()

rule1 = ctrl.Rule(quality['poor'] | service['poor'], tip['low'])


rule2 = ctrl.Rule(service['average'], tip['medium'])
rule3 = ctrl.Rule(service['good'] | quality['good'], tip['high'])

rule1.view()
tipping_ctrl = ctrl.ControlSystem([rule1, rule2, rule3])
tipping = ctrl.ControlSystemSimulation(tipping_ctrl)

# Pass inputs to the ControlSystem using Antecedent labels with Pythonic API
# Note: if you like passing many inputs all at once, use .inputs(dict_of_data)
tipping.input['quality'] = 6.5
tipping.input['service'] = 9.8

# Crunch the numbers


tipping.compute()
print(tipping.output['tip'])
tip.view(sim=tipping)

67 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

EXERCISE:

1. Run the example code and generate output for quality=6.5 and service = 9.8. Generate output and show
plot
2. Change the input quality=5 and service = 9.2 and run the code and generate resultant tip value and plotit
against the tipping graph.

3. Create a fuzzy controller for the temperature regulator for the room. The controller senses temperature
(10-40 with step of 1) and humidity (0-1 with step of 0.1) and sets the fan Speed (0-100 with step of 10)
according to the provided rules.
• The linguistic variables for temperature are cold (10-15, peak=10, moderate (12-27, Peak 20),
hot(25-40, Peak=40).
• The linguistic variables for Humidity are dry (0-0.4, Peak=0), moderate (0.3,0.65, peak=0.45), and
wet(0.5-1, Peak=1).
• The Linguistic variable for Speed are slow (0-30 peak=10), medium (25-60, Peak=45) and fast
(50-100, Peak=70)

Consider the following rules


• if it is cold and dry OR cold and wet set speed to slow
• if it is moderate and wet set speed to slow
• if it is moderate and dry set speed to medium
• if it is moderate and wet set speed to fast
• If it is hot and wet or hot and dry set speed to fast

Plot the required graphs and est the system for three different temperature and humidity values and
generatespeed output.

68 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 13

SCIPY AND MATPLOTLIB


OBJECTIVE Implement Scientific and technical computing with plotting using SciPy and
matplotlib library.

THEORY

SciPy:
SciPy is a library of algorithms and mathematical tools built to work with NumPy arrays.SciPy,
pronounced as Sigh Pi, is a scientific python open source library to perform Mathematical,
Scientific and Engineering Computations.

The SciPy library depends on NumPy, which provides convenient and fast N-dimensional array
manipulation. The SciPy library is built to work with NumPy arrays and provides many
userfriendly and efficient numerical practices such as routines for numerical integration and
optimization. Together, they run on all popular operating systems, are quick to install and are free
of charge. NumPy and SciPy are easy to use, but powerful enough to depend on by some of the
world's leading scientists and engineers.

Importing the SciPy module:


There are several ways to import SciPy. The standard approach is to use a simple import statement:
import scipy
However, for large amounts of calls to SciPy functions, it can become tedious to write numpy.X
over and over again. Instead, it is common to import under the briefer name sp:
import scipy as sp
This statement will allow us to access SciPy objects using sp. X instead of scipy X. It is also
possible to import SciPy directly into the current namespace so that we don't have to use dot
notation at all, but rather simply call the functions as if they were built-in:
from scipy import *
if you want help regarding SciPy, or anything need to know about SciPy in python‘s editor, you
may type:
help(scipy)
help(scipy.zeros)

NumPy v/s SciPy:

69 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

In an ideal world, NumPy would contain nothing but the array data type and the most basic
operations: indexing, sorting, reshaping, basic element wise functions et cetera. All numerical
code would reside in SciPy. However, one of NumPy‘s important goals is compatibility, so NumPy
tries to retain all features supported by either of its predecessors. Thus NumPy contains some
linear algebra functions, even though these more properly belong in SciPy. In any case, SciPy
contains more fully-featured versions of the linear algebra modules, as well as many other
numerical algorithms. If you are doing scientific computing with python, you should probably
install both NumPy and SciPy. Most new features belong in SciPy rather than NumPy. Following
example, we already done in Numpy but SciPy also done the same function:

Example: Output:

Other Following example using Scipy.io package provides a wide range of functions to work
around with different format of files. Some of these formats are – Matlab, IDL, Matrix Market,
Wave, Arff, Netcdf, etc.
Following are the functions used to load and save a .mat file. This form of importing submodules
is preferred for all submodules except scipy.io (because io is also the name of a module in the
Python stdlib)

Example:

70 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Output:

• Loadmat--Loads a MATLAB file


• Savemat--Saves a MATLAB file
• Whosmat--Lists variables inside a MATLAB file

SciPy is built using the optimized ATLAS LAPACK and BLAS libraries. It has very fast linear
algebra capabilities. All of these linear algebra routines expect an object that can be converted into
a two-dimensional array. The output of these routines is also a two-dimensional array.
SciPy.linalg v/s NumPy.linalg:
A scipy.linalg contains all the functions that are in numpy.linalg. Additionally, scipy.linalg also
has some other advanced functions that are not in numpy.linalg. Another advantage of using
scipy.linalg over numpy.linalg is that it is always compiled with BLAS/LAPACK support, while
for NumPy this is optional. Therefore, the SciPy version might be faster depending on how
NumPy was installed.
The scipy.linalg.solve feature solves the linear equation a * x + b * y = Z, for the unknown x, y
values.
Example: Output:

SciPy – Stats:
All of the statistics functions are located in the sub-package scipy.stats and a fairly complete listing
of these functions can be obtained using info(stats)function. A list of random variables available
can also be obtained from the doc string for the stats sub-package. This module contains a large
number of probability distributions as well as a growing library of statistical functions.
• rv_continuous--A generic continuous random variable class meant for subclassing
• rv_discrete--A generic discrete random variable class meant for subclassing
• rv_histogram--Generates a distribution given by a histogram
The scipy.optimize package provides several commonly used optimization algorithms and so
many other build-in package provides many different functionalities.
71 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Plotting and Graphics:

Matplotlib:
Matplotlib is probably the single most used Python package for 2D-graphics. It provides both a
very quick way to visualize data from Python and publication-quality figures in many formats.
We are going to explore matplotlib in interactive mode covering most common cases.
You can generate plots, histograms, power spectra, bar charts, errorcharts, scatterplots, etc., with
just a few lines of code.
Importing the Matplotlib module:
There are several ways to import matplotlib. The standard approach is to use a simple import
statement:
import matplotlib
pyplot:
pyplot provides a procedural interface to the matplotlib object-oriented plotting library. It is
modeled closely after Matlab™. Therefore, the majority of plotting commands in pyplot have
Matlab™ analogs with similar arguments. Important commands are explained with interactive
examples.
from matplotlitb import pyplot as plt

1D plotting:
Example:

• numpy.linspace ( ), numpy.linspace (start, stop, num = 50, endpoint = True, retstep = False,
dtype = None) : Returns number spaces evenly w.r.t interval. Similar to arrange but instead
of step it uses sample number.
• plt.plot ( ), is a versatile command, and will take an arbitrary number of arguments. For
example, to plot x versus y.
• plt.show ( ), display the current figure that you are working on.

72 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

Output:

Plotting more than one line:


Example:

Output:

73 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

EXERCISE:
1. Using multiple Plotting example, change the colour of line using plt.gca( ) and adding legend
to the plot using Matplotlib legend( ). Output looks alike:

2. Plot function with Matplotlib. First, import SciPy and Matplotlib, some points on the (0, 1)
interval and then plot a parabola defined by the above interval.

3. Plot sine and cosine function using Numpy and Matplotlib library.

4. Plot square and cube function using Scipy and Matplotlib library with line space interval
(0,5).Output looks alike:

74 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual

LAB # 14

(OPEN ENDED LAB)

SUPERVISED MACHINE LEARNING

OBJECTIVE: Working with Supervised Machine Learning Technique.

SCENARIO:
1. You are provided with Iris dataset which contains information about three types of irises’
(Setosa, Versicolour, and Virginica).

The rows in the dataset are the samples and the columns are Sepal Length, Sepal Width, Petal
Length and Petal Width and the name

You can load this dataset using the following:

from sklearn import datasets


iris = datasets.load_iris()

Study the data and ensure there is no extra column added while loading data; if so, remove it. Use
three different machine learning methods to predict the type of iris. Describe briefly the method
you are using and your objective. Use the sklearn model_selection or cross_validation package for
splitting data into training and test sets. Use performance measures like F1 score, confusion matrix,
and accuracy to measure the model on test data. Use seaborn to plot a heat map for the confusion
matrix. Discuss the three models' performance and which one you find best.

75 | P a g e

You might also like