Design a Fuzzy Logic Inference System from Scratch

In a Fuzzy logic system we make relations between inputs and outputs by creating rules between input and outputs, it can be single or multiple inputs and outputs. A word Fuzzy means something vague or indistinct. Let’s understand it with an example of a washing machine. You put some clothes in the washing machine to wash but you are confused or indistinct how much time is needed to make your clothes completely clean. So there is a fuzzy controller in your washing machine, based on weight of the clothes or type of the clothes. A Fuzzy logic controller will set the time automatically. Likewise there are many other applications of fuzzy logic. We will discuss them below.

What is Fuzzy Logic?

The concepts of fuzzy logic rely on skills of human reasoning. Fuzzy logic is many valued logical systems between 0 and 1. In other words, we can say that the fuzzy logic concept is based on fully true, fully false, partially true and partially false. Unlike a fuzzy logic system, a Boolean logical system can be fully true or fully false that is 0 or 1 only. Let’s understand with an example.
If I have to assign values to weekdays and weekend days, then according to the Boolean logic the weekend will be assigned 1 or 0 and the weekdays will be assigned 0 or 1. But Fuzzy says Saturday can be a partially weekday and partially a weekend and the value will be between 0 and 1. The left side figure resembles Boolean logic and the right side figure resembles fuzzy logic.

Why Use Fuzzy Logic?

When You don’t have data or you have to use your reasoning to create data
If you have a proper data set for inputs and outputs then you can go for machine learning and neural network, but if you have to use your logic to create data then go for fuzzy logic. For example, in the case of the washing machine your input is clothes and output is time (till what time washing machine will be on), but there is no such numeric data for clothes, so you have to create data for clothes in such a way that you can train the fuzzy logic. Let’s say to light clothes I assigned value 1 to 3, to medium heavy clothes I assigned value between 3 to 7, and to heavy clothes values lied between 6 to 10, in this case I used my reasoning to create data and this kind of data can be applied in fuzzy logic only. Sometimes we use fuzzy logic to create data for ML and DL.

Flexibility
It is based on human reasoning logic, so whenever you want you can modify according to you.

It can tolerate imprecise data
Fuzzy logic depends on partially true or partially false, so If you have imprecise data, there will be no issue while designing Fuzzy.

It is based on natural language
As it is based on a natural language, anyone can design it, it maybe an engineer or a non-engineer, it can be a technical or non-technical person.

It can model data from both, linear and non-linear systems
It is based on rules, so it doesn’t matter what kind of data you have. You only require to know maximum and minimum values and your reasoning ability.

Fuzzy Inference Process

Fuzzy inference is a process of mapping from an input to an output using fuzzy logic as discussed above. The process of fuzzy inference involves assigning Membership Functions (in Boolean function will be a square wave 0 or 1), applying logical operations, and If-Then, and or-Rules.

1. Fuzzy Inputs and Membership Functions

First, process your all inputs and outputs in fuzzy inputs through membership functions. Membership functions are the calibrated graphs of your measured input and output data to make fuzzy inputs values lie between 0 and 1. Membership functions can be triangular, trapezium, Gaussian, bell curve etc. It is also called a fuzzification process.

2. Apply Fuzzy Operator

After fuzzification, we apply operators (and/or) in inputs, like if A is ….. AND B is ….. OR C is….. here A,B and C are inputs, AND/OR are operators. If AND operator is used then output can be min of A and B. If OR operator is used between A and B then output can be max of both. There are other methods too instead of min and max.

3. Implication

After applying a fuzzy operator between the inputs, next step is to apply and or product implication between output and output of the above second step.
If A is …… AND B is…… OR C is ….. then D is… here D is an output, there can be one or more outputs. Step 2 is called Antecedent and step 3 is called Consequent. Like this you have to make all rules. Before applying the implication method if you have any weight for rules then apply it.

4. Aggregation of All Rules

In aggregation we always take max of all rules, or as given below:
– probabilistic;
– sum of each rule’s output set.

5. Defuzzification

An Output of step 4 will be a curve or you may say a fuzzy set, however, defuzzification for each variable will be a single value. You can choose some methods for defuzzification, like bisector, calculation of centroid, average of maximum etc., in which centroid method is the most popular.

Fuzzy Logic System Designing with MATLAB

In MATLAB you can design a fuzzy logic system in two ways: first is an interactive way which I will use below in an application of agriculture, and the second one is programmatic.
When your model is ready, you can use it as a standalone application, or you can interface it with Simulink for real-time testing, or you can deploy it in a hardware directly from MATLAB or you can interface it with other toolboxes of MATLAB.

Objective, Goal, Challenges and Data

Objectives

  • To save water in Irrigation system.
  • Design a controller which can control the valve of water pump.

Challenges

  • Controller has to be based on human reasoning because there is no sensor to measure water pump valve opening or closing.
  • A software which gives an interactive way to design FIS system, so it can be easier for anyone to design.

Data

  • Moisture
  • Relative Humidity
  • Temperature
  • Based on above data we have to design a FIS System which can control opening of water valve
Input/otputMeasured asRangeGroup 
Soil moistureCentibars[1       60]Dry, Normal, Wet, Saturated
Relative Humidity% (Percentage)[0       90]Low, Medium, Normal, High
TemperatureC (Degree)[0       50]Low, Medium, Normal, High
Valve Opening of pump% (Percentage)[0       100]10% open 25% open 50% open 75% open 100% open  
Above table shows range of data and groups for every variable

We will use above table to design a FIS (Fuzzy inference System) , in the group column we’ve divided our data in linguistic variables. While partitioning the data you have to assign minimum and maximum values to each group, additionally some part of data of the first group will be assigned to the next group, likewise every group will have some common data of its preceding group. That’s because fuzzy is based on partially true and partially false.

Step 1:- Open a Fuzzy Logic Designer in MATLAB

You can go in app section of MATLAB from there in control System Design and analysis as the given below figure. Or you can give command fuzzyLogicDesigner in MATLAB command window.

When you click on Fuzzy Logic Designer, a new GUI will be opened in MATLAB as the figure given below.

Step2:- Add variables

Next step is to add all variables: both, inputs and outputs. To do this click on Edit-Add Variable-Input or Output , also assign your variable names. In below figure number at 2 you can assign variable name. You have to add all variables one by one as in the figure under 1.

After assigning all variables the GUI will look like the figure given below.
There are three inputs and one output, soil moisture is named as SoilMOis, the second input is relative humidity named as relHum , the third input is temperature named as temp, and output is water valve opening in percentage, it is named Waterval in below figure.

Step3:- Assign MF for every variable and range for every group

There are many membership functions like triangular, trapezium, Gaussian etc., even you can design your customized MF. There are 11 inbuilt membership functions in MATLAB. Some you can see below.

Gaussian distribution curve(taken from MATLAB documentation to understand)
Triangular membership function and Trapezoidal membership function (taken from MATLAB documentation to understand)

Click on edit tab- Membership Functions a new window will be opened where you can assign MF and range to all the groups.

Click on Membership Functions

Check the figures below for every variable, range of a group you can assign in params.

4 Trapezoidal MF for Soil Mositure

4 Triangular MF for Relative Humidity

4 Triangular MF for Relative Temperature

5 Triangular MF for Water valve

Step4:- Create rules (here human experience and reasoning will work)

First follow the figure below, and click on rules to write rules.

While writing rules your reasoning will work. For example, one rule can be if soil moisture is dry and relative humidity is medium and temperature is high then valve opening will be 75%. Likewise you can make many rules, just remember, don’t make rules randomly, use proper reasoning or check your data sheet to make rules. Your data sheet will look like below.

Original Measured Data

Interpreted Data as group names

The above data I used for the reference purpose, you may not require to interpret the data. If you want to create reference data and work on it, you can use the MATLAB code given below.

%Generate Data
SoilMois=randi([1 60],30,1); % in centibars
relHum=randi([0,90],30,1); % in %
 temp=randi([0, 50],30,1); % in C
 WaterVal=randi([0,100],30,1); % in %
 irrigtable=table(SoilMois,relHum,temp,WaterVal);
 writetable(irrigtable,'irrigationData.xlsx');
 

%Assign Group 
SoilMoisC = discretize(SoilMois,[1 15 30 45 60],'categorical',{'Dry','Normal','Wet','Saturated'});

relHumC = discretize(relHum,[0 15 30 60 90],'categorical',{'Low','Medium','Normal','High'});

tempC = discretize(temp,[0 10 25 35 50],'categorical',{'Low','Medium','Normal','High'});

WaterValC = discretize(WaterVal,[0 10 25 50 75 100],'categorical',{'10%','25%','50%','75%','100%'});
 irrigtableC=table(SoilMoisC,relHumC,tempC,WaterValC);
 writetable(irrigtableC,'irrigationCat.xlsx');

After rule assigning your rule editor will look like below, you can add more rules if you want.

Rule Editor( Select group from every variable and click on Add rule to make rules)

Step5:- Check graph of variations and rules.

If there are few variations in your graph then you need to modify your rules. To check the graph follow both the figures below.

Click on surface to open graph
You can see the relationship between Humid, Moisture and Water valve.
To check the relationship with other variables you can select from X (input) and Y (input)

Step6:- Check your fuzzy inference system rules

The final step where you are going to check your rules is now a black-box. Just change inputs and your output will be changed accordingly. Follow the figures below.

How to open rules
Rule Viewer

You have to move the vertical red lines of inputs and based on that you can find out in what percent valve will be opened.
Further you can export your model to create standalone applications or you can deploy in a hardware or you can interface with Simulink for real-time applications.

Some useful codes which you can use after exporting your Fuzzy inference system

%Transform Mamdani FIS into Sugeno FIS
%Load a Mamdani fuzzy inference system.
load irrigfinal

%Convert this system to a Sugeno fuzzy inference system.
sug_fismat = convertToSugeno(irrigfinal);

%Plot the output surfaces for both fuzzy systems.
subplot(2,2,1)
gensurf(irrigfinal)
title('Mamdani system ')
subplot(2,2,2)
gensurf(sug_fismat)
title('Sugeno system')

%evalfis  Evaluate fuzzy inference system
valveOpening=evalfis(irrigfinal,[35 34 12]) % Soul Mois, Humid, Temp

%plotfis	Display fuzzy inference system
plotfis(irrigfinal)

plotmf	Plot membership functions for input or output variable
plotmf(irrigfinal,'input',1)
plotmf(irrigfinal,'output',1)

%showrule	Display fuzzy inference system rules
showrule(irrigfinal)

List of Applications of Fuzzy Logic System

Above model is an application of agriculture and irrigation. More applications are give below.

  • Agriculture
  • Aerospace
  • Controller for any autonomous system
  • Medical
  • Security systems
  • Household equipment like washing machine and refrigerator
  • Clustering pattern and recognition
  • Finance and econometric
  • Defence and Marine

21 thoughts on “Design a Fuzzy Logic Inference System from Scratch”

  1. Hi there! This post could not be written much better! Looking through this post reminds me of my previous roommate! He continually kept talking about this. I’ll send this information to him. Pretty sure he’ll have a good read. Thank you for sharing!

  2. Hi! I’m at work surfing around your blog! Just wanted to say I love reading through your blog and look forward to all your posts! Keep up the fantastic work!

  3. It’s a shame you don’t have a donate button! I’d most certainly donate to this superb blog! I suppose for now i’ll settle for book-marking and adding your RSS feed to my Google account. I look forward to new updates and will talk about this website with my Facebook group. Talk soon!

  4. Just want to say your article is as surprising. The
    clearness on your put up is simply nice and i can assume you are an expert on this subject.

    Well along with your permission allow me to grab your feed
    to keep updated with imminent post. Thanks a million and please carry on the rewarding
    work.

Leave a Reply

Your email address will not be published.