AI Lab Manual Spring 2025
AI Lab Manual Spring 2025
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)
Page 2 of 7
(SSUET/QR/111)
SIR SYED UNIVERSITY OF ENGINEERING & TECHNOLOGY
COMPUTER ENGINEERING DEPARTMENT
BS COMPUTER ENGINEERING
GRADING POLICY:
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
• 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:
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.
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
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.
Laboratory Manual
Lab Exam
Total (50)
Examined by:
(Name and Signature of concerned lab instructor)
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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 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.
• 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:
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])
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
Example: 04
Output:
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:
Example#07:
Output:
8|Page
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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])
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:
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
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
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 –
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.
Example:
Output:
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
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.
• 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.
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
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
Output:
Exercise:
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
18 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
Output:
>>> 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
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()
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
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:
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
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)
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
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
def printAdjList(self):
for item in self.adjlist.items():
print(item)
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)
BFS(g,0,8)
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
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 = []
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
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.
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
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:
# return the h value from nodelist dictionary e.g. for nodelist {0:2, 1:3,4:5} and n =4 , the
function shouldreturn 5
‘’’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))
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
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
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.
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.
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
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 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
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
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)
Example:
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
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)
47 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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.
3. Create a null vector of size 15 and update fifth value to 12 and ninth value to 17
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 ( ).
• 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: 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.
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.
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:
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.
# [0, 10]
start = 0
stop = 10 + 0.001
step = 0.25
x = np.arange(start, stop, step) print(x)
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.
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?
52 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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.
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
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
55 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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.
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)
56 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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.
57 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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
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
Output:
60 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
Example:
Output:
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
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
THEORY
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
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:
65 | P a g e
Artificial Intelligence for Computer Engineering (CE-415L) Lab Manual
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')
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
quality['average'].view()
service.view()
tip.view()
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
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)
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
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.
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:
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
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:
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
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
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