Artificial Intellegence Lab Manual
Artificial Intellegence Lab Manual
Artificial Intelligence
Practical No. 01
Topic:Introduction to Neural Network
Student’s Roll no: K18ES15 Points Scored: __________________________
The term fuzzy refers to things that are not clear or are vague. In the real world
many times we encounter a situation when we can’t determine whether the state
is true or false, their fuzzy logic provides very valuable flexibility for reasoning.
In this way, we can consider the inaccuracies and uncertainties of any situation.
In the boolean system truth value, 1.0 represents the absolute truth value and 0.0
represents the absolute false value. But in the fuzzy system, there is no logic for
the absolute truth and absolute false value. But in fuzzy logic, there is an
intermediate value too present which is partially true and partially false.
Reinforcement learning
Reinforcement learning is the training of machine learning models to make a
sequence of decisions. The agent learns to achieve a goal in an uncertain,
potentially complex environment. In reinforcement learning, an artificial
intelligence faces a game-like situation. The computer employs trial and error to
come up with a solution to the problem. To get the machine to do what the
programmer wants, the artificial intelligence gets either rewards or penalties for the
actions it performs. Its goal is to maximize the total reward.
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4th Year
Artificial Intelligence
Practical No. 2
Topic: Learning MATLAB Neural Networks toolbox for the
development of neural network-based applications.
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand Artificial Neural Network.
Understand Working of Neural Networks toolbox.
Create a perceptron network to perform the operation of AND function and OR function.
We can see that g(x) is just doing a sum of the inputs — a simple aggregation. And theta here is
called thresholding parameter. Each neuron has a fixed threshold. If the net input into the
neuron is greater than or equal to the threshold, the neuron fires. Inputs & output — are only
Boolean. The activation of a neuron is binary. That is, the neuron either fires (activation of one)
or does not fire (activation of zero).
Neural networks are adjusted, or trained, so that a particular input leads to aspecific target
output. This lab session gives you an insight of training a neural network to fita function
using Neural Network Toolbox functions.
Perceptron
A perceptron is a simple model of a biological neuron in an artificial neural network. Perceptron is
also the name of an early algorithm for supervised learning of binary classifiers.
We will first create a perceptron network to perform the operation of AND function for
twovariables.To start neural network toolbox type nntool. The following window appears see
figure 1
Figure 2
First, define the network input, called p, having the value [0 0 1 1;0 1 0 1]. Thus, thenetwork has a
two-element input, and four sets of such two-element vectors are presented to itin training. To
define this data, click New, and a new window, Create Network or Data,appears (see figure 2).
Select the Data tab. Set the Name to p, the Value to [0 0 1 1; 0 10 1], and set Data Type to Inputs.
Figure 3 Figure 4
Click Create and then click OK to create an input p. The Network/Data Manager window appears,
and p shows as an input. Next create a network target. This time enter the variable name t, specify
the value [0 0 0 1], and click Targets under Data Type. Again click Create and OK (See figure
3).You will see in the resulting Network/Data Manager window that you now have t as a target as
well as the previous p as an input. In order to create a new network ANDNet, select the Network
tab. Enter ANDNetunder Name. Set the Network Type to Perceptron, for that is the kind of
network you want to create. You can set the inputs to p, and the example targets to t. You can use a
hardlimtransfer function with the output range [0, 1] that matches the target values and a
learnplearning function. For the Transfer function, select hardlim. For the Learning
function,selectlearnp. The Create Network or Data window now looks like the following figure (see
figure 4)
Figure 5
Now click Create and OK to generate the network. Now close the Create Network or Data
window. To train the network, click ANDNet to highlight it (see figure 5).
Figure 6
Then double click to Open. This leads to a new window, labeled Network: ANDNet. (see Figure 6)
Figure 7
At this point you can see the network again by clicking the View tab. You can also check on the
initialization by clicking the Initialize tab. Now click the Train tab. specify the inputs and output by
clicking the Training Info tab and selecting p from the list of inputs and t from the list of targets.
The Network: ANDNet window should look like figure 7.
Figure 8
At this stage, if you want to view what weight values have been assigned or edit the values, you can
do this by clicking on View/Edit Weights. You can also initialize weights again by clicking on
Reinitialize Weights tab.
Click Train Network to train the perceptron network. The following training results
appear (see figure 8).
Figure 9
The network was trained to zero error in five epochs. Confirm that the trained network does indeed
give zero error by using the input p and simulating the network. To do this, go to the Network:
ANDNetwindow and click the Simulate tab. Use the Inputs menu to specify p as the input, and
label the output as ANDNet_outputsSim to distinguish it from the training output. (See Figure 9).
Click Simulate Network in the lower right corner and click OK. In the Network/Data Manager
you see a new variable in the output: ANDNet_outputsSim(See Figure 10). Double-click it and a
small window, Data: ANDNet_outputsSim, appears with the value [0 0 0 1]. Compare with training
Data: ANDNet_outputs(See Figure 11)..Thus, the network does perform the AND of the inputs,
giving a 1 as an output only in this last case, when both inputs are 1.
Figure 10
Figure 11 Figure 12
Lab Exercise
Step: 01
Write “nntool” in command window we get.
Step: 02
Creating Input and Target.
Step: 03
Creating Network.
Step: 04
Labelled Network.
Step: 05
Training Network.
Step: 06
Simulating Network.
Step: 07
Results.
Conclusion:
Have you become familiar with MATLAB Neural Networks toolbox? What concepts did
you gain from this practical? Comment
I have become familiar with the MATLAB Neural Network toolbox components and its
command; in this toolbox we can design different types of logic gates. its real times
applications.
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear
Artificial Intelligence
Practical No. 3
Topic:Generating and processing undirected and directed graphs
using MATLAB.
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand graphs i.e directed and undirected graphs.
Create directed and undirected graphs using MATLAB.
Find shortest path in a graph using MATLAB.
Graph
A graph is a pictorial representation of a set of objects where some pairs of objects are connected
by links. The interconnected objects are represented by points termed as vertices, and the links that
connect the vertices are called edges.
Formally, a graph is a pair of sets (V, E), where V is the set of vertices (Nodes) and E is the set of
edges, connecting the pairs of vertices.
In the below graph, V = {a, b, c, d, e} and E = {ab, ac, bd, cd, de}.
Figure 13 Graph
Weighted graph
A graph in which each of the edge is associated with a real number (weight) is called as weighted
graph. Both undirected and directed graphs can be weighted.
Example 1
Where s is the vector containing first node of each of the edge and t is the vector containing second
node of each of the edge. As this is undirected graph so, edge AC is same as CA.
Example 2
Shortest Path
The shortest path is a path between two vertices (or nodes) in a graph such that the sum of the
weights of its constituent edges is minimized. Consider the following graph:
Example 1
Procedure
Consider the following city map directed graph, where weight of each edge represent the distance
between two cities in kilometers:
Step 01: Identify the nodes and number them:
1 – Karachi, 2 – Jamshoro, 3 – Hyderabad, 4 – Nawabshah, 5 – Khairpur
Step 02: Identify the edges and their weights:
{1,2}=150, {1,3}=162, {2,1}=150, {2,3}=16, {3,1}=162, {3,2}=16, {3,4}=124,
{4,2}=128, {4,3}=124, {4,5}=163, {5,2}=300, {5,4}=163
Step 03: Open MATLAB and create new script file.
Step 04: Write down the below code in script file:
Where s is the vector containing first node of each of the edge and t is the vector containing second
node of each of the edge.
Step 06: Now find the shortest path between nodes Karachi to Nawabshahby appending below
two commands and re-run the script:
Lab Exercise
1. Define the following terms:
a. Regular Graph
b. Null Graph
c. Trivial Graph
d. Simple Graph
e. Connected Graph
f. Disconnected Graph
g. Complete Graph
h. Cyclic Graph
i. Degree of vertex
j. Pendent Vertex
k. Loop
l. Parallel Edges
Conclusion:
Have you become familiar with graphs in MATLAB? What concepts did you gain from this practical
about directed and undirected graph in MATLAB? Comment
I have become familiar with the directed and undirected graphs and their applications
and in path finding.
References:
https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html
https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html#bur8goj
https://www.mathworks.com/help/matlab/math/directed-and-undirected-graphs.html#bur8om2
https://www.mathworks.com/help/matlab/ref/digraph.html
https://www.mathworks.com/help/matlab/ref/graph.shortestpath.html
The End
Lab 3
Task 1
(a)
(b)
(C) (d)
(e)
Task 2
(a)
Task 3
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
Artificial Intelligence
Practical No. 4
Topic:Breadth First Search (BFS) algorithm using MATLAB
Student’s Roll no:K18ES15 Points Scored: __________________________
Figure 14 BFS
[1] Step 1: Choose some starting vertex (node) and insert it in queue.
[2] Step 2: Visit adjacent unvisited vertex. Mark it visited. Display it. Insert it in a queue.
[3] Step 3: If no adjacent vertex found, remove the first vertex from queue.
[4] Step 4: Repeat Rule 2 and Rule 3 until queue is empty.
v = bfsearch(G,s)
v = bfsearch(G,s) applies breadth-first search to graph G starting at node s. The result is a vector of
node IDs in order of their discovery..
Example
s = [1 1 1 1 2 2 2 2 2 2 2 2 2 2 15 15 15 15 15];
t = [3 5 4 2 14 6 11 12 13 10 7 9 8 15 16 17 19 18 20];
G = graph(s,t);
plot(G)
v = bfsearch(G,2)
Also try for v = bfsearch(G,1) , what is Difference _ ?
Lab Exercise
a. Apply Breadth-First Search and write down state of Queue, Visited Nodes and Current Node in
each step, consider A is the starting node.
b. Use bfsearch() function to verify your answer at every step.
Conclusion:
Have you become familiar Breadth First Search (BFS) algorithm using MATLAB? What concepts did
you gain from this practical? Comment
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____
References:
https://www.mathworks.com/help/matlab/ref/graph.bfsearch.html
https://www.mathworks.com/help/matlab/ref/graph.bfsearch.html#butxivb-5
https://www.hackerearth.com/practice/algorithms/graphs/breadth-first-search/tutorial/
https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
The End
LAB 4
Example 1
Result:
Example 2.1:
Task1
1 --- 1
1 2 12
1 7 2 de queue 127
2 7 127
2 37 1273
2 4 3 7 de queue 12734
7 43 12734
7 8 4 3 de queue 127348
Task 2
Task 3
Code:
Result:
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
Artificial Intelligence
Practical No. 5
Topic:Depth First Search (DFS) algorithm using MATLAB.
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand Depth first Search (dfs) Algorithm.
Understand Working of dfsearchfunction in MATLAB.
Apply Depth first Search (dfs) Algorithm on directed and undirected graphs.
Figure 15 DFS
The dfsearch function in MATLAB is used to perform depth-first graph search. The syntax
for dfsearch function is given below:
4. Example
s = [1 1 1 1 2 2 2 2 2 2 2 2 2 2 15 15 15 15 15];
t = [3 5 4 2 14 6 11 12 13 10 7 9 8 15 16 17 19 18 20];
G = graph(s,t);
plot(G)
v = dfsearch(G,1)
Also try for v = dfsearch(G,2) , what is Difference _ ?
Lab Exercise
Apply Depth-First Search and write down state of Stack, Visited Nodes and Current Node in
each step, consider 1 is the starting node.
Use dfsearch() function to verify your answer at every step.
a) Apply Depth-First Search and write down state of Stack, Visited Nodes and Current node in
each step, consider A is the starting node.
b) Use dfsearch() function to verify your answer at every step,
5. Conclusion:
Have you become familiar with Depth First Search (DFS) algorithm using MATLAB? What
concepts did you gain from this practical? Comment
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____
References:
https://www.interviewcake.com/concept/java/dfs
https://www.mathworks.com/help/matlab/ref/graph.dfsearch.html
https://gjacopo.github.io/imtools/graph/dfs.html
The End
Lab 5
Task 1
Task 2
Task 3
Result:
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronics Engineering
8th Semester 4th Year
Artificial Intelligence
Practical No. 6
Topic: Learning MATLAB Fuzzy Logic toolbox for or analyzing, designing,
and simulating systems based on fuzzy logic.
Student’s Roll no: K18ES15 Points Scored: __________________________
[9] OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand Fuzzy logic.
Become familiar with MATLAB Fuzzy Logic toolbox.
Design and simulate systems based on Fuzzy Logic.
Fuzzy Logic
3. Fuzzy logic is a form of many-valued logic in which the truth values of variables may be any real
number between 0 and 1 both inclusive. It is employed to handle the concept of partial truth,
where the truth value may range between completely true and completely false. By contrast, in
Boolean logic, the truth values of variables may only be the integer values 0 or 1.
4. The idea of fuzzy logic was first advanced by Dr. LotfiZadeh of the University of California at
Berkeley in the 1960s.
Fuzzy Logic Toolbox in MATLAB
Fuzzy Logic Toolbox™ provides functions, apps, and a Simulink® block for analyzing, designing, and
simulating systems based on fuzzy logic. The product guides you through the steps of designing
fuzzy inference systems. Functions are provided for many common methods, including fuzzy
clustering and adaptive neurofuzzy learning. The toolbox lets you model complex system behaviors
using simple logic rules, and then implements these rules in a fuzzy inference system. You can use it
as a stand-alone fuzzy inference engine. Alternatively, you can use fuzzy inference blocks in
Simulink and simulate the fuzzy systems within a comprehensive model of the entire dynamic
system.
Fuzzy logic washing machines are gaining popularity. These machines offer the advantages of
performance, productivity, simplicity and less cost. Sensors continually monitor varying conditions
inside the machine and accordingly adjust operations for the best wash results. The fuzzy logic
checks for the extent of dirt and grease, the amount of soap and water to add, direction of spin, and
so on. The machine rebalances washing load to ensure correct spinning. Neuro fuzzy logic
incorporates optical sensors to sense the dirt in water and a fabric sensor to detect the type of
fabric and accordingly adjust wash cycle.
To model a system using fuzzy logic, the first step is to determine the inputs and outputs of it. A
washing machine’s most important duty is to clean the cloths without damaging them. In order to
achieve it, the output parameters of fuzzy logic, which are related to washing, must be paid
importance. Inputs and outputs of fuzzy logic system are shown in figure given below.
Fuzzy Logic
Input Variables 1.Type Model
of Dirt 2.Type of Cloth Output Variable
3.Dirtiness of Cloth Wash Time
"WashingMachine"
Input Output
To implement Fuzzy Logic System “Washing Machine” follow steps are followed:
After adding input variables, fuzzy logic designer will look like this.
Give name to the input variables i.e. 1. Type of cloth, 2. Type of dirt, 3. Dirtiness of cloth.
Define Output variable in Fuzzy Logic Designer
As already in fuzzy logic designer we have one output this is desired for our fuzzy logic system
“washing machine” so we just rename it as wash time.
Add membership functions for each input variable, see figure 2 for details.
Double click on any input a new window for Membership functions will be opened.
For Type of cloth are defined in silk, Woolen, Cotton. Note Specify range also that is 0-100 as
shown in diagrams below
Add membership functions for type of dirt i.e. non gressy , medium and gressy and specify
range 0-100 .
Add membership functions for dirtiness of cloth i.e. small, medium and large and specify range
0-100.
Add membership functions for output variable, see figure 2 for details.
1st remove all MIF’s for output variable and then add custom MIF that are 5. Also Define display
range and range 0-100.
Now define these custom 5 MIF’s that are very short, short, medium, long and very long.
Also add parameters range for each membership function of output variable.
i.e. for very short [-25 0 15] , short [15 25 35], medium [30 50 60], long [60 75 80] and for very long
[85 100 125] should be defined as parameters .
To view rules, go to view rules and a window known as rule viewer will appear.
For different input variables wash time will be different. Fuzzy rules have been established
for the modeling of washing machine. The whole system has been developed by using
MATLAB’s fuzzy logic toolbox.
6. Consider the same case study of washing machine; create a fuzzy logic model “Washing
Machine” by using fuzzy logic toolbox MATLAB with some more input, output variables and
rules. Attach all steps screenshots.
Task:
Step 01: Fuzzy logic designer with three inputs and one output.
Step: 02 Setting Cloth-type and its parameters.
Step: 03 Setting Dirt-type and its parameters.
Step: 04 Setting Degree of Dirtiness and its parameters.
Step: 05 Setting Output and its parameters.
Step: 06 writing up Rules for Fuzzy logic different parameters.
Step: 07 Surface View.
Step: 08 Final result in 3D.
Conclusion:
Have you become familiar Fuzzy Logic Toolbox in MATLAB? What concepts did you gain
from this practical? Comment
I have become familiar with Fuzzy Logic Toolbox in MATLAB, it is one of the best
techniques that can be used in data handling output prediction than the old
technique that gives only two results High or low on the other hand we have Fuzzy
Logic that always enables us to give intermediate results as well, in MATLAB we
can analyze our results using surface as well as in 3D graph.
References:
https://www.youtube.com/watch?v=K3K8OH61pRg
https://www.mathworks.com/products/fuzzy-logic.html
The End
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
Artificial Intelligence
Practical No. 7
Topic:Getting Familiar with visual PROLOG.
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand visual PROLOG environment.
Understand basic concepts of visual Prolog.
Create simple programs using visual Prolog.
Introduction
There are two types of programming languages: Procedural and Declarative. Procedural languages
are used to perform numerical computations like: Computing area of a circle, finding percentage
marks of a student, finding the person with greater age. All these problems involve some sort of
numerical computations (formulae). Some of the procedural programming languages are: C/C++,
JAVA, C#, BASIC FORTRAN etc. Whereas declarative languages are used to perform non-numerical
computations like: who is the mother of John? Finding all the students who like AI? Are John and
Tom brothers? Now all these problems involve non-numeric computations there is no formula to
find out who is the mother of John? you do not have any formula to conclude which students like AI;
you do not have formula to tell whether John and Tom are brothers of each other. These types of
problems cannot be solved by traditional procedural languages. Some of the declarative
programming languages are: PROLOG (Programming in Logic), LISP (List Processing) and ML (Meta
Language).
Visual PROLOG
Download visual PROLOG
https://www.visual-prolog.com/vip/download/default.htm
What is PROLOG?
Pam Tom
Bob Liz
Ann Pat
Jim
Here we choose parent as the name of a relation; tom and bob are its arguments.
For reasons that will become clear later we write names like tom with an initial lower-case letter.
The whole family tree of Figure 1 is defined by the following Prolog program:
parent(“pam”, “bob”).
Parent (“tom”, “bob”).
Parent(“tom”, “liz”).
parent(“bob”, “ann”).
parent(“bob”, “pat”).
Parent (“pat”, “jim”).
Basic elements of PROLOG (Facts, Rules and Questions)
Prolog programs are composed of declarative sentences to be asserted. These sentences are called
predicates. These predicates are of two types: Facts and Rules.
Facts
Facts are the declarative sentences which are always true. Facts can represent either relationships
between objects or properties of objects. For example:
o Syntax of Fact
Rules
Rules are the declarative sentences which depend on one or more other facts being true.
Example 1:Person1 is mother of Person2 if Person1 is female and Person1 is parent of person2.
mother(Person1, Person2) :- female(Person1) , parent(Person1,Person2).
Example 2:Person1 is friend of Person2 if Person1 knows Person2 and Person1 likes Person2.
friend(Person1, Person2) :- knows(Person1, Person2) , likes(Person1, Person2).
o Syntax of Fact
Symbol Read as
:- If or implies that
, And
; Or
Q
uestions
After writing facts and rules we will ask some questions. Those questions will be evaluated from
specified facts and rules. For example:
7) Goal Section (Mandatory): The GOAL section is where you put the built-in (internal) goal. A
VisualProlog program must always include exactly one GOAL section. Here we write questions.
Essentially, the GOAL section is the same as the body of a rule: it's simply a list of subgoals.
There aretwo differences between the GOAL section and a rule:
The GOAL keyword is not followed by ":-".
Prolog automatically executes the goal when the program runs.In a way, you can call Goal
section the main method of a prolog program.
Questions
Example Code
PREDICATES
nondeterm parent(string,string)
nondeterm male(string)
nondeterm female(string)
nondeterm mother(string,string)
nondeterm father(string,string)
nondeterm brother(string,string)
nondeterm sister(string,string)
nondeterm grandmother(string,string)
nondeterm grandfather(string,string)
CLAUSES
parent("salma","saleem").
parent("salma","ali").
parent("saeed","saleem").
parent("saeed","ali").
parent("saleem","erum").
parent("erum","kashif").
parent("erum","urooj").
female("salma").
female("erum").
female("urooj").
male("saeed").
male("saleem").
male("ali").
male("kashif").
mother(Person1,Person2):- parent(Person1,Person2),female(Person1).
father(Person1,Person2):- parent(Person1,Person2),male(Person1).
brother(Person1,Person2):- parent(Person3,Person1),parent(Person3,Person2) ,male(Person1).
sister(Person1,Person2):- parent(Person3,Person1),parent(Person3,Person2),female(Person1).
grandmother(Person1,Person2):-
parent(Person1,Person3),parent(Person3,Person2),female(Person1).
grandfather(Person1,Person2):-
parent(Person1,Person3),parent(Person3,Person2),male(Person1).
GOAl
father(Who,"ali").
Example Code
Note: Predicates declared nondeterm b/c program may have multiple solutions/
Lab Exercise
1. Covert following sentences into PROLOG FACTS and specify whether they represent
RELATIONSHIP or PROPERTY:
Conclusion:
Have you become familiar with visual PROLOG environment? What concepts did you gain
from this introductory practical on visual PROLOG? Comment
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____
References:
https://www.visual-prolog.com/vip/download/default.htm
https://www.visual-prolog.com/download/71/deBoer-BeginnersGuide.pdf
https://wiki.visual-prolog.com/index.php?title=Fundamental_Visual_Prolog
http://www.cse.unsw.edu.au/~billw/dictionaries/prolog/
http://www.aistudy.com/program/prolog/visual_prolog/Determinism%20Monitoring%20in
%20Visual%20Prolog.htm
The End
Lab#07 Tasks
CASE STUDY
EXAMPLE CODE
MEHRAN UNIVERSITY OF ENGINEERING AND TECHNOLOGY
S.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear
Artificial Intelligence
Practical No. 8
Topic:Understanding variables and rules in visual PROLOG.
Student’s Roll no:_K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand variables and rules in visual PROLOG.
Create rules in visual PROLOG.
Variables in PROLOG
Like other programming languages the variables are used to temporarily store certain values.
They are used in place of unknown values. Consider the following example:
Ali is child of Saleem.
Sara is child of Salma.
Ahmed is child of Ali.
Kashif is child of Salma.
Muneer is child of Saleem.
Following is a program based on the predicates created from these sentences.
Program
PREDICATES
child(string, string)
CLAUSES
child(“ali”, “saleem”).
child(“sara”, “salma”).
child(“ahmed”, “ali”).
child(“kashif”,”salma”).
child(“muneer”,”saleem”).
GOAL
child(“ali”,”saleem”).
Program
Rules in PROLOG
A rule is an expression that indicates that the truth of a particular fact depends upon one or more
otherfacts. The syntax can be
predicate1(arg1, arg2, ... argN):- predicate2(arg1, arg2, ... argN), predicate3(arg1, arg2, ...
argN),………,predicateN(arg1, arg2, ... argN).
This can be read as predicate1 is true only if predicate2 to predicateN are true.OrIt can be:
predicate1(arg1, arg2, ... argN):- predicate2(arg1, arg2, ... argN); predicate3(arg1, arg2, ...
argN);………;predicateN(arg1, arg2, ... argN).
This can be read as predicate1 is true if any one of predicate2 to predicateN is true (as ; represents
OR inProlog).The left hand side before :- of a rule is restricted to a single, positive, literal, which
means it mustconsist of a positive atomic expression. It cannot be negated and it cannot contain
logical connectives.Again taking the example of the program above, you can add a rule in the
Clauses likeparent(X,Y):- child(Y,X).This can be read as if Y is child of X then X is the parent of Y.
Similarly we can also haveGrandchild(X,Y):- child(Y,Z), child(Z,X).
This can be read as if Y is child of Z and Z is child of X then Y is Grandchild of X.It can also be
Grandchild(X,Y):-parent(Z,Y),parent(X,Z).
Symbol Read as
:- If or implies that
, And
; Or
not Not
RulesPROLOG Rules
Sara hates everything Kashiflikes.hates(“sara”,X):-likes(“kashif”,X).
Kashif likes everything saralikes.likes(“kashif”,X):-likes(“sara”,X).
Program
Questions (GOALS):
Does Kashif hate cricket? ?- hates(“kashif”,”cricket”).
Answer: No
Does Kashif like music? ?- likes(“kashif”,”music”).
Answer: Yes
What Sara likes? ?- likes(“sara”,X).
Answer:
X=chips
X=mobile
2 Solutions
Who likes music? ?-likes(X,”music”).
Answer:
X=kashif
1 Solution
Lab Exercise
There is a cricket team of 5 players; capabilities (properties) of each of the player are given
infollowing table.
Player Name Batsman Bowler Fielder
Sarfaraz ✓ ✓
Afridi ✓ ✓ ✓
Malik ✓ ✓ ✓
Hafiz ✓ ✓ ✓
Amir ✓ ✓
Write the facts from the above table create the rule for all-rounder and run following goals in
PROLOG.
1. Is Afridi all-rounder?
2. Is Malik all-rounder?
3. Who are all-rounders in the team?
4. Who is Batsman in the team?
5. Who is Bowler in the team?
CODE
1. Is Afridi all-rounder?
2. Is Malik all-rounder?
Have you become familiar with Variables and Rules in PROLOG? What concepts did you
gain from this practical? Comment
I have become familiar with visual prolog variables and on the basis of these variables
we designed different programs get output from these, its working it is quite easy to use.
From this lab I successfully understood the concept behind decision making on the basis
of knowledge we fed into any AI system.
References:
https://www.swi-prolog.org/pldoc/man?section=attvar
https://www.doc.gold.ac.uk/~mas02gw/prolog_tutorial/prologpages/vars.html
https://www.cpp.edu/~jrfisher/www/prolog_tutorial/4.html
The End
Lab#08 Tasks
PROGRAM
PREDICATES
child(string, string)
CLAUSES
child(“ali”, “saleem”).
child(“sara”, “salma”).
child(“ahmed”, “ali”).
child(“kashif”,”salma”).
child(“muneer”,”saleem”).
TASKS
FIND GOALS
If we want to find that is Kashif child of Salma? Then we will write the goal as:
child(“kashif”,”salma”).
But if we want to find that who are the Childs of Salma? Then the first argument is
unknown so in the first argument we will place some variable say Child. Then our goal
can be written as:child(Who,Whom).
Program
Questions (GOALS):
Does Kashif hate cricket? ?- hates(“kashif”,”cricket”).
Answer: No
There is a cricket team of 5 players; capabilities (properties) of each of the player are given in
following table.
CODE
Player Batsman Bowle Fielder
Name r
Sarfaraz ✓ ✓
Afridi ✓ ✓ ✓
Malik ✓ ✓ ✓
Hafiz ✓ ✓ ✓
Amir ✓ ✓
Write the facts from the above table create the rule for all-rounder and run following goals
in PROLOG.
1. Is Afridi all-rounder?
2. Is Malik all-rounder?
Artificial Intelligence
Practical No. 9
Topic:Exploring operators and built-in predicates of Visual PROLOG.
Student’s Roll no:K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand Operators in PROLOG.
Understand Working of built-in predicates of PROLOG.
Create simple programs using operators and built-in predicates of PROLOG.
Arithmetic Operators
Prolog can perform all four basic arithmetic operations (addition, subtraction, multiplication, and
division) between integral and real values; the type of the result is determined according to the
following table.
Operand 1 Operator Operand 2 Result
Integral +, -, * Integral integral
Real +, -, * Integral real
In case
of Integral +, -, * Real real
Real +, -, * Real real
integral or real / integral or real real
Relational Operators
Following is the list of relational operators used in PROLOG:
Note that Prolog's "=" relation is equality (not assignment); it is the same as the "==" relation in C.
Comparing Characteristics
Prolog converts the 'a' < 'b' to the equivalent arithmetic expression 97 < 98, using the
corresponding ASCII code value for each character.
Comparing String
When two strings or symbols are compared, the outcome depends on a character-by-character
comparison of the corresponding positions.The comparison "antony" > "antonia" evaluates to true,
since the two symbols first differ at the position where one contains the letter y (ASCII value 79)
and the other the letter i (ASCII value 69).
Built-in Predicates
In many programming languages there are some built-in functions available. For example in JAVA
there Math.sin(), Math.cos(), Math.abs(), System.out.println() etc. are built-in functions. Similarly, in
PROLOG predicates are like functions and there are some built-in predicates available in PROLOG
some of them are explained below.
write(value, value1,…..)
It prints the values concatenated with each other at output screen. E.g. write (“Hello World”,
1, A,B,b) will result in: Hello World1abb (assuming A and B are bound to a and b
respectively).
nl:-It generates a line feed (new line). The same can be achieved by using \n in write.
fail:- If this predicate is encountered in any rule, that rule automatically fails.
Example
PREDICATES
add3(integer, integer, integer, integer)
sub3(integer, integer, integer, integer)
CLAUSES
add3(A,B,C,Res):-Res=A+B+C.
sub3(A,B,C,Res):-Res=A-B-C.
GOAL
write("Enter 3 numbers, finishing each number with Enter key\n"),
readint(A),
readint(B),
readint(C),
add3(A,B,C,R1),
sub3(A,B,C,R2),
write("Result of A+B+C =",R1),
nl,
write("Result of A-B-C=",R2),
nl,
fail
Lab Exercise
1. Create a basic calculator prolog program for making basic calculations (add, subtract,
multiply,divide, average). Use separate goal statements for making each calculation (with
constant numeric values).
2. Continue calculator program with addition of using write() and read() predicates, for taking
numericinput from user and displaying text after program execution. Decorate your answer by
using morebuilt-in predicates.
Conclusion:
Have you become familiar with operators and built-in predicates in PROLOG? What
concepts did you gain from this practical? Comment
I have become familiar with visual prolog operators especially arithmetic operators it’s
working it is quite easy to use. We designed a simple arithmetic calculator that takes
input from user and performs different operations. From this lab I successfully
understood the concept behind decision making on the basis of knowledge we fed into
any AI system.
References:
http://www.aistudy.co.kr/program/prolog/visual_prolog/Comparisons.htm
http://www.aistudy.co.kr/program/prolog/visual_prolog/Arithmetic%20Expressions.htm
https://wiki.visual-prolog.com/index.php?title=Language_Reference/Terms
The End
Lab#09 Tasks
EXAMPLE
LAB EXERCISE
1. Create a basic calculator prolog program for making basic calculations (add, subtract,
multiply, divide, average). Use separate goal statements for making each calculation (with
constant numeric values).
3. Continue calculator program with addition of using write() and read() predicates, for taking
numeric input from user and displaying text after program execution. Decorate your answer
by using more built-in predicates.
MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear
Artificial Intelligence
Practical No. 10
Topic: Graph problem (A Path & Distance finding programin PROLOG).
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand graph theory.
Create simple programs to find path in an un-weighted graph using PROLOG.
Create simple programs to find distance in a weighted graph using PROLOG.
EQUIPMENT & TOOL:
personal computer (PC)
visual PROLOG
Graph Theory
Graph
A graph is an abstract representation of a set of objects where some pairs of the objects are
connectedby links. The interconnected objects are the links that connect some pairs of vertices are
called edges. Typically, a graph is depicted in diagrammatic form as a set of dots for the vertices,
joined by lines or curves for the edges. Graphs are one of the objects of study in discrete
mathematics.The edges may be directed (asymmetric) or undirected (symmetric) .points and edges
are also called lines. In the most common sense of the term a graph is an ordered pair G = (V, E)
comparing a set V of vertices or nodes together with a set E of edges or lines, which are 2-element
subsets of V (i.e., an edge is related with two vertices, and the relation is represented as unordered
pair of the vertices with respect to the particular edge). To avoid ambiguity, this type of graph may
be described precisely as undirected and simple.
Figure 20 Graph
Edges:
Each edge is defined by a pair of vertices
An edge connects the vertices that define it
In some cases, the vertices can be the same
Vertices:
Vertices also called nodes
Denote vertices with labels
Representation:
Represent vertices with circles, perhaps containing a label
Represent edges with lines between circles
Example:
V = {A,B,C,D}
E = {(A,B),(A,C),(A,D),(B,D),(C,D)}
Undirected graph
An undirected graph is one in which edges have no orientation. The edge (a, b) is identical to the
edge (b, a), i.e., they are not ordered pairs.
Directed graph
A directed graph or digraph is an ordered pair D = (V, A). Here V is a set whose elements are called
vertices or nodes and A is a set of ordered pairs of vertices, called arcs, directed edges, or arrows.
Figure 22 Directed Graphs
In Weighted graphs cost value, weight or numerical value is associated with a given edge and in un-
weighted graph there is no cost value, weight or numerical value is associated for given edges.
*Note: Weighted graph can be directed or undirected.
Un-weighted Graph
An un-weighted graph is one in which an edge does not have any cost or weight associated with it.
Figure below shows an un-weighted graph with 7 nodes (A, B. C. D. E. F& G).
Links between nodes
Sequence of edges connecting the nodes in between source and destination nodes is the path
between
source and destination nodes. For example from source node A to destination G there are four
paths:
Path 1 (A to G): A – B – D – F – G
Path 2 (A to G): A – B – D – E – F – G
Path 3 (A to G): A – C – D – E – F – G
Path 4 (A to G): A – C – D – F – G
The length of the path may vary. Minimum length of path is 1 and maximum can be any value
greater than one. Consider the path between the nodes A and B. Here the length of path is 1.
A B
In this case, if we want to determine whether path exists between A and B is simply to determine
whether link exists between A and B or not. If the link exists the path also exists, if link does not
exist the path does not exist.
So the prolog rule can be created as: path(N1,N2):-link(N1,N2).
Now consider another case in which we have to determine whether path exists between A and G or
not. Here the length of the path is 4.
There exists a path between nodes N1 and N2 if there is a path between N1 and N3; and N3 is
linked with N2.
This can be written in PROLOG as: path(N1,N2):-path(N1,N3),link(N3,N2).
Actually it is recursion in which the predicate “path” is calling itself. The recursive predicate is
executedin the manner shown below:
1stiteration: path(‘a’,’g’):-path(‘a’,’f’),link(‘f’,’g’).
2nditeration: path(‘a’,’f’):-path(‘a’,’d’),link(‘d’,’f’).
3rd iteration: path(‘a’,’d’):-path(‘a’,’c’),link(‘c’,’d’).
4thiteration: path(‘a’,’c’):-link(‘a’,’c’).
Which are the nodes to whom nodes B and C are connected? ?-link('b',X),link('c',X).
Answer:
X=d
Weighted Graph
Weighted Graph
A weighted graph is one in which each of the edge is associated with a number known as weight.
Figure below shows a weighted graph where each of the edge is bounded with certain weight.
4
A B
2 3
8
D C
6 5
E
In the above figure there are 5 nodes (A, B, C, D& E). The arrows show the link between the nodes,
whereas the number associated with each of the arrow is the weight or distance of respective edge.
It is obvious from the above figure that:
Distance between nodes A & B is 4.
Distance between nodes A & C is 8.
Distance between nodes A & D is 2.
Distance between nodes B & C is 3.
Distance between nodes C & E is 5.
Distance between nodes D & E is 6.
Similarly the distance between nodes B and E is the sum of weighted edges included in the path
between B and E.
The nodes which are connected together are said to have links between them.
From A to B 4 link(‘a’,’b’,4).
From A to C 8 link(‘a’,’c’,8).
From A to D 2 link(‘a’,’d’,2).
From B to C 3 link(‘b’,’c’,3).
From C to E 5 link(‘c’,’e’,5).
From D to E 6 link(‘d’,’e’,6).
Rule to determine path exists between two nodes and distance between the nodes
Consider the path between the nodes A and B. Here the length of path is 1 and weight/distance of
the path is 4.
A 4 B
In this case, if we want to determine whether path exists between A and B is simply to determine
whether link exists between A and B or not. If the link exists the path also exists, if link does not
exist the path does not exist. The distance between the paths is simply the distance of the link.
Now consider another case in which we have to determine whether path exists between A and E or
not. Here the length of the path is 3.
4
A B
5
E
There exists a path between nodes N1 and N2 if there is a path between N1 and N3; and N3 is
linked with N2 and the distance of the path is the sum of all the edges included in the path between
N1 and N2. This can be written in PROLOG as:
path(N1,N2,Distance):-path(N1,N3,Distance1),link(N3,N2,Distance2),Distance=Distance1+Distance2 .
4
A B Distance1
Distance = 12
5 Distance2
E
2 8 3
D C
6 5
Program
Distance of path between two nodes N1 and N2 is 8, the first node N1 is A find the second node N2.
?- path(‘a’,N2,8).
Answer:
N2=c
N2=e
2 solutions
Distance of path between two nodes N1 and N2 is 7, the first node N1 is A find the second node N2.
?- path(‘a’,N2,7).
Answer:
N2=c
1 solution
Distance of path between two nodes N1 and N2 is 12, the second node N2 is E find the first node N1.
?- path(N1,’e’,12).
Answer:
N1=a
1 solution
Lab Exercise
1. Implement the following un-weighted graph in PROLOG and run for following goals.
A B
C D
E F
2. Implement the following weighted graphs in PROLOG and run some goals.
3
4
A B C
2
F 2
3
6
1
Conclusion:
Have you become familiar with graph theory, can u create program to find path and
distance for a graph in PROLOG? What concepts did you gain from this practical? Comment
I have become familiar with visual prolog weighted and unweighted feature, its working
how we can generate different graphs and links between them according to our
requirement. We can also use distance function to measure distance between different
points. From this lab I successfully understood the concept behind decision making on
the basis of knowledge we fed into any AI system.
References:
https://rlgomes.github.io/work/prolog/2012/05/22/19.00-prolog-and-graphs.html
http://kti.ms.mff.cuni.cz/~bartak/prolog/graphs.html
https://stackoverflow.com/questions/21161624/define-graph-in-prolog-edge-and-path-finding-if-there-is-
a-path-between-two-ve
https://cs.ccsu.edu/~markov/ccsu_courses/prolog.txt
The End
Lab#10 Tasks
GRAPH PROGRAM:
Goal
Test Questions
4
A B
2 3
8
D C
6 5
E
Program
Distance of path between two nodes N1 and N2 is 7, the first node N1 is A find the second node N2.
?- path(‘a’,N2,7).
Distance of path between two nodes N1 and N2 is 12, the second node N2 is E find the first node N1.
?- path(N1,’e’,12).
Lab Exercise
3. Implement the following un-weighted graph in PROLOG and run for following goals.
A B
C D
E F
Artificial Intelligence
Practical No. 11
Topic: Simple Tic-Tac-Toe game in visual PROLOG.
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand tic-tac-toe game states.
Create simple programs in PROLOG to find states and winners for tic-tac-toe game.
Tic-Tac-Toe Game
Tic-Tac-Toe Game
Tic-tac-toe, also called noughts and rosses (in the British Commonwealth countries) and X's and O's
inthe Republic of Ireland, is a pencil-and paper game for two players, X and O, who take turns
marking the spaces in a 3×3 grid. The X player usually goes first. The player who succeeds in
placing three marks in a horizontal, vertical, or diagonal row wins the game.
Players soon discover that best play from both parties leads to a draw (often referred to as cat or
cat'sgame). Hence, tic-tac-toe is most often played by young children.
Here the predicate player contains two string arguments, first tells the name of the player and the
second tell whether the player chooses crosses or circles. For example if Ali chooses crosses and
Kashif chooses circles then the facts can be written as:
player(“ali”,”crosses”).
player(“kashif”,”circles”).
circle(integer)
cross(integer)
Both predicates contain one argument that is the box number in which cross or circle is placed. For
the state of tic-tac-toe shown in second figure the facts can be written as:
1 2 3 O X X
4 5 6 X O
circle(1).
circle(6).
circle(7).
circle(9).
cross(2).
cross(3).
cross(5).
cross(8).
The crosses will win if any one of the crosses positions is present in the current state of the game:
X X X X
X X X X
X X X X
X X X X
X X X X
X X X X
O O O O
O O O O
O O O O
O O O O
O O O O
O O O O
In order to determine which player wins we must know two things: First, whether player has
chosen crosses or circles. Second, whether cross wins or circle wins.
If circles win then the player who has chosen circles will win.
If crosses win then the player who has chosen crosses will win.
wins(Player):-crossesWin(),player(Player,”crosses”).
wins(Player):-circlesWin(),player(Player,”circles”).
Tic-Tac-Toe Example 1
Suppose there are two players: Player 1= Ali, he chooses circles and Player 2= Kashif, he chooses
crosses. The current state of the game is shown below. Write a PROLOG program to find who wins?
X O X
X O O
X O
PROLOG Program:
PREDICATES
player(string,string)
circle(integer)
cross(integer)
circlesWin()
crossesWin()
wins(string)
CLAUSES
player(“ali”,”circles”).
player(“kashif”,”crosses”).
cross(1).
cross(3).
cross(4).
cross(7).
circle(2).
circle(5).
circle(6).
circle(9).
wins(Player):-crossesWin(),player(Player,”crosses”).
wins(Player):-circlesWin(),player(Player,”circles”).
GOAL
wins(Who).
Tic-Tac-Toe Example 2
Suppose there are two players: Player 1= Saima, she chooses circles and Player 2= Salma, she chooses
crosses. The current state of the game is shown below. Write a PROLOG program to find who wins?
O O X
O X
X X O
PROLOG Program:
PREDICATES
player(string,string)
circle(integer)
cross(integer)
circlesWin()
crossesWin()
wins(string)
CLAUSES
player(“saima”,”circles”).
player(“salma”,”crosses”).
cross(3).
cross(6).
cross(7).
cross(8).
circle(1).
circle(2).
circle(5).
circle(9).
wins(Player):-crossesWin(),player(Player,”crosses”).
wins(Player):-circlesWin(),player(Player,”circles”).
GOAL
wins(Who).
Goal Test Questions
Does Salma win? ?-wins(“salma”).
Answer: No
Lab Exercise
1. Suppose there are two players: Player 1= Akhter, he chooses circles and Player 2= Shahid,
he
chooses crosses. The current state of the game is shown below.Write a PROLOG program
to findwho wins?
2. Suppose there are two players: Player 1= Ali, he chooses circles and Player 2= Kashif, he
choosescrosses. Now we extend our game to 4 X 4 square boxes. The current state of the
game is shownbelow.Write a PROLOG program to find who wins?
Conclusion:
Have you become familiar with states of Tic-Tac-Toe game? , can u create program to find
which player wins Tic-Tac-Toe game?
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
_____________________________________________________________________________________________________
____
References:
https://mezohelp.blogspot.com/2014/05/tictactoe-game-using-swi-prolog.html
https://github.com/GoodDeeds/Tic-Tac-Toe-Prolog
https://courses.cs.washington.edu/courses/cse341/03sp/slides/PrologEx/tictactoe.pl.txt
https://swish.swi-prolog.org/p/Tic-Tac-Toe.swinb
The End
MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear
Artificial Intelligence
Practical No. 12
Topic: Medical Expert System Case Study using PROLOG.
Student’s Roll no: K18ES15 Points Scored: __________________________
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
Understand expert system.
Create simple programsin SWI-PROLOG as a practical implementation of medical expert system
Case study.
Expert System
In artificial intelligence, an expert system is a computer system that emulates the decision-making
ability of a human expert. Expert systems are designed to solve complex problems by reasoning
through bodies of knowledge, represented mainly as if–then rules.
Figure 24 Expert system components
MYCIN
BLUE BOX
VM
ANNA
Download Tool SWI-PROLOG. As SWI-PROLOG provides us free prolog environment with many
advanced libraries and also provide us online environment to write and run code online.
https://swish.swi-prolog.org/download/stable
https://swish.swi-prolog.org/
To implement medical expert system in SWI-PROLOG.
Make rule so that questions can be asked from user and based on hypothesis disease will be
diagnosed and suggestions will be given to the patient.
go:-
hypothesis(Disease),
write(Disease),
nl,
undo.
hypothesis(cold) :- cold, !.
hypothesis(flu) :- flu, !.
hypothesis(typhoid) :- typhoid, !.
hypothesis(measles) :- measles, !.
hypothesis(malaria) :- malaria, !.
hypothesis(unknown). /* no diagnosis*/
cold :-
verify(headache),
verify(runny_nose),
verify(sneezing),
verify(sore_throat),
nl,
write('1: Tylenol/tab'),
nl,
write('2: panadol/tab'),
nl,
nl,
nl.
flu :-
verify(fever),
verify(headache),
verify(chills),
verify(body_ache),
nl,
write('1: Tamiflu/tab'),
nl,
write('2: panadol/tab'),
nl,
write('3: Zanamivir/tab'),
nl,
write('Please take a warm bath and do salt gargling Because'),
nl.
typhoid :-
verify(headache),
verify(abdominal_pain),
verify(poor_appetite),
verify(fever),
nl,
write('1: Chloramphenicol/tab'),
nl,
write('2: Amoxicillin/tab'),
nl,
write('3: Ciprofloxacin/tab'),
nl,
write('4: Azithromycin/tab'),
nl,
nl.
measles :-
verify(fever),
verify(runny_nose),
verify(rash),
verify(conjunctivitis),
nl,
write('1: Tylenol/tab'),
nl,
write('2: Aleve/tab'),
nl,
write('3: Advil/tab'),
nl,
nl,
nl.
malaria :-
verify(fever),
verify(sweating),
verify(headache),
verify(nausea),
verify(vomiting),
verify(diarrhea),
nl,
write('1: Aralen/tab'),
nl,
write('2: Qualaquin/tab'),
nl,
write('3: Plaquenil/tab'),
nl,
write('4: Mefloquine'),
nl,
write('Please do not sleep in open air and cover your full skin Because'),
nl.
ask(Question) :-
write(Question),
write('? '),
read(Response),
nl,
->
assert(yes(Question)) ;
assert(no(Question)), fail).
:- dynamic yes/1,no/1.
verify(S) :-
(yes(S)
->
true ;
(no(S)
->
fail ;
ask(S))).
undo :- retract(yes(_)),fail.
undo :- retract(no(_)),fail.
undo.
Or Run online.
Lab Exercise
3. Modify this medical expert system case study by adding some diseases and their
symptoms.Run the code , and test for different diseases.
Conclusion:
Have you become familiar with expert system? can you create programs using SWI-PROLOG to
practically implement expert systems?
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
_______________________________________________________________________________________________________________
References:
https://swish.swi-prolog.org/
https://swish.swi-prolog.org/
https://en.wikipedia.org/wiki/Comparison_of_Prolog_implementations
http://www.david-reitter.com/compling/prolog/compare.html
https://www.youtube.com/watch?v=pFdagVD2a-Y
https://www.amzi.com/ExpertSystemsInProlog/02usingprolog.php
https://github.com/topics/expert-system?l=prolog
https://www.metalevel.at/prolog/expertsystems
The End
Lab tasks
4. Modify this medical expert system case study by adding some diseases and their
symptoms.Run the code , and test for different diseases.
CODE
go:-
hypothesis(Disease),
nl,
undo.
hypothesis(covid) :- covid, !.
hypothesis(kidneystone) :- kidneystone, !.
hypothesis(diabetes) :- diabetes, !.
hypothesis(asthma) :- asthma, !.
hypothesis(cold) :- cold, !.
hypothesis(flu) :- flu, !.
hypothesis(typhoid) :- typhoid, !.
hypothesis(measles) :- measles, !.
hypothesis(malaria) :- malaria, !.
hypothesis(unknown). /* no diagnosis*/
covid :-
verify(difficulty_breathing),
verify(chest_pain),
verify(movement),
verify(diarrhoea),
nl,
nl,
write('2: mask'),
nl,
write('3: hand_wash'),
nl,
write('Please isolate'),
nl.
kidneystone :-
verify(pain_in_back ),
verify(vomiting),
verify(seeing_blood_in_urine),
verify(Fever),
nl,
nl,
write('2: ibuprofen'),
nl,
write('3: naproxen'),
nl,
nl.
diabetes :-
verify(urinate ),
verify(thirsty),
verify(hungry),
verify(tired),
nl,
nl,
write('2: glyburide'),
nl,
write('3: linagliptin'),
nl,
nl.
asthma :-
verify(Shortness_of_breath),
verify(chest_tightness),
verify(wheezing),
verify(flu),
nl,
write('1: albuterol'),
nl,
write('2: Xopenex'),
nl,
write('3: ProAir_HFA'),
nl,
nl.
covid :-
verify(difficulty_breathing),
verify(chest_pain),
verify(movement),
verify(diarrhoea),
nl,
write('2: mask'),
nl,
write('3: hand_wash'),
nl,
write('Please isolate'),
nl.
cold :-
verify(headache),
verify(runny_nose),
verify(sneezing),
verify(sore_throat),
nl,
write('1: Tylenol/tab'),
nl,
write('2: panadol/tab'),
nl,
nl,
nl.
cold :-
verify(headache),
verify(runny_nose),
verify(sneezing),
verify(sore_throat),
nl,
write('1: Tylenol/tab'),
nl,
write('2: panadol/tab'),
nl,
nl,
nl.
flu :-
verify(fever),
verify(headache),
verify(chills),
verify(body_ache),
write('1: Tamiflu/tab'),
nl,
write('2: panadol/tab'),
nl,
write('3: Zanamivir/tab'),
nl,
nl.
typhoid :-
verify(headache),
verify(abdominal_pain),
verify(poor_appetite),
verify(fever),
write('Advices and Sugestions:'),
nl,
write('1: Chloramphenicol/tab'),
nl,
write('2: Amoxicillin/tab'),
nl,
write('3: Ciprofloxacin/tab'),
nl,
write('4: Azithromycin/tab'),
nl,
nl.
measles :-
verify(fever),
verify(runny_nose),
verify(rash),
verify(conjunctivitis),
nl,
write('1: Tylenol/tab'),
nl,
write('2: Aleve/tab'),
nl,
write('3: Advil/tab'),
nl,
nl,
malaria :-
verify(fever),
verify(sweating),
verify(headache),
verify(nausea),
verify(vomiting),
verify(diarrhea),
nl,
write('1: Aralen/tab'),
nl,
write('2: Qualaquin/tab'),
nl,
write('3: Plaquenil/tab'),
nl,
write('4: Mefloquine'),
nl,
write('Please do not sleep in open air and cover your full skin Because'),
nl.
ask(Question) :-
write(Question),
write('? '),
read(Response),
nl,
assert(yes(Question)) ;
assert(no(Question)), fail).
:- dynamic yes/1,no/1.
verify(S) :-
(yes(S)
->
true ;
(no(S)
->
fail ;
ask(S))).
undo :- retract(no(_)),fail.
undo.
RESULT
TEST 01
TEST 02
TEST 03
MEHRAN UNIVERSITY OF ENGINEERING AND
TECHNOLOGYS.Z.A.B CAMPUS KHAIRPUR MIR’S,
Department of Electronic Engineering
8th Semester 4thYear
Artificial Intelligence
Practical No. 15
OBJECTIVES: Upon successful completion of this practical, the students will be able to:
To become familiar with neural networks learning algorithms from available examples.
Provide knowledge of learning algorithm in neural networks.
Have an understanding of the concepts and techniques of neural networks through the study
of the most important neural network models.
Discuss the main factors involved in achieving good learning and generalization performance
in neural network systems.
Use the current techniques and tools required for computing practice.
Theory:
Neural networks are a branch of ―Artificial Intelligence". Artificial Neural Network is a system
loosely modelled based on the human brain. Neural networks are a powerful technique to solve
many real world problems. They have the ability to learn from experience in order to improve
their performance and to adapt themselves to changes in the environment. In addition to that
they are able to deal with incomplete information or noisy data and can be very effective
especially in situations where it is not possible to define the rules or steps that lead to the
solution of a problem. In a nutshell a Neural network can be considered as a black box that is
able to predict an output pattern when it recognizes a given input pattern. Once trained, the
neural network is able to recognize similarities when presented with a new input pattern,
resulting in a predicted output pattern. In late 1950s, Frank Rosenblatt introduced a network
enhanced version of McCulloch-Pitts Threshold Logic Unit (TLU) model. Rosenblatt's model of neuron, a
perceptron, was the result of merger between two concepts from the 1940s, McCulloch-Pitts model of
an artificial neuron and Hebbian learning rule of adjusting weights. In addition to the variable weight
values, the perceptron model added an extra input that represents bias.
5. Algorithm:
Perceptron Learning Algorithm:
The perceptron learning rule was originally developed by Frank Rosenblatt in the late
1950s. Training patterns are presented to the network's inputs; the output is computed.
Then the connection weightswjare modified by an amount that is proportional to the
product of
the difference between the actual output, y, and the desired output, d, and
the input pattern, x.
Problem Statement:
Implement AND function using perceptron model
Truth table for AND function is:
6. Conclusion:
Single layer perceptron learning algorithm is implemented for AND function. It is used for
train the iterations of neural network. Neural network mimics the human brain and
perceptron learning algorithm trains the neural network according to the input given.