Introduction to Fuzzy Logic

Daniel Sioson
Jun 4, 2019 · 10 min read
Photo by Vladislav Nikonov on Unsplash

Have you ever thought of creating an algorithm where your app can make its own decision, or can handle some weird things that your client throws at it as they desperately want to break it?

As you create this algorithm, you realized that you’re just spamming if-else logic in your code (until it becomes a mess) and you thought to yourself it won’t just cut it.

So, look no further unless you despise math. This’s where Fuzzy Logic comes in! A little bit of background: the word Fuzzy refers to things that are hard to understand — like the code of your co-worker.

In this blog, I’m going to try to explain what Fuzzy Logic is and how it works.

What is Fuzzy Logic?

Simply put, it’s the logic that mimics how a person would think. Now combine the processing speed of your CPU and the way Fuzzy Logic works, it’s pretty obvious that it can make decisions faster than you.

It’s just an extension of the Boolean logic, that 0 and 1 stuff.

So why it was created?

Professor Zadeh, the guy who created Fuzzy Logic, says we humans don’t need an input that machines need, but we’re highly adaptive. You probably don’t need to install a program in your brain to know how to eat pizza, I think.

In order for Fuzzy Logic to think like us, it has to act like one of us. The rules we set around it are in a language we use in our daily lives. Here is an example of the rules for an air conditioning system:

  1. If the current room temperature is cold and you set the air conditioner to warm, the room temperature should be increased by the air conditioner.
  2. If the current room temperature is warm and the air conditioner is set to warm, the room temperature should not change.
  3. If the current room temperature is hot and you set the air conditioner to cold, the room temperature should be reduced by the air conditioner.

We’re going to elaborate those rules later.

Usage of Fuzzy Logic

If you’re wondering if there’s more use of Fuzzy Logic on programming stuff aside from the air conditioner freezing up the office room, well here you go:

  1. Spell Checker

When you were a kid, you probably had a school homework where you would choose a U.S. state and you have to copy and paste some information from a wiki site …

Okay, I’m just assuming things.

… and it turns out you’ve picked Mississippi. Well, that’s fine and all, but you didn’t know what the spelling of Mississippi is when you went to do your homework so you just guessed it.

Lucky for you, your search engine is so kind to provide the proper spelling through a fuzzy matching and spell checking capability.

Along with the result for Mississippi, of course.

2. Search

Now that you’ve done your homework and you’re off to your comfortable bed when you suddenly tripped over the internet cable and it broke. Your parent’s desktop no longer has an internet connection.

So before your parents come home and find out they’re going to have to spend some money replacing what you’ve just broken, you’ve taken it on yourself to buy the replacement cord.

You opened your favorite online shopping mall on your brother’s laptop and typed “Internet Cable.” Because you don’t know what an Ethernet cable is.

And ta-da! You are presented with Ethernet cables, even if your keyword is “internet” cables, thanks to the mall’s fuzzy search algorithm.

3. Suggestions

After shopping and just waiting for your Ethernet cable to be delivered, you decided to browse the clothes section because you just feel like it. A few seconds later you stumbled on a section called the Recommend Items section.

A fuzzy recommendation app will suggest product recommendations based on items you’ve previously purchased, or even products you’ve just looked into.

Now, in order for you to better understand how Fuzzy Logic works, we’ll need to go a little deeper to learn the basics. You’re ready?

Classical Set Theory

To start off with, we’ll first head to the simple branch of mathematics that deals with sets — the Classical Set Theory.

In classical set theory, a set is a collection of element and stuff. Take a look at the image below:

We can have a set of numbers of 1 to 5, a set of characters between A to E, and even a set of words such asHTML, JavaScript, CSS, and PHP.

Fuzzy Sets

Fuzzy sets can be considered as an extension of classical set. In classical set, it’s either you or you don’t belong in a set whereas in Fuzzy set, you can belong in one, either by half, quarter, or even a tiny bit.

For example, when we say cold, it doesn’t mean it’s entirely freezing cold, or that when we say hot, it doesn’t mean it’s entirely burning hot. We usually specify a degree of coldness or hotness, mostly in the form of temperature regardless of whether it is Celsius or it is Fahrenheit.

Of course, it’s up to you on how would you put those realistic values in a range of 0 and 1. Think of 0 and 1 as percentages written in decimal. 1 is 100% and is given to the best value while 0 is 0% and is given for the worst one.

Linguistic Variables and Values

Linguistic variables are variables where words or even sentences derived from the language we use on a daily basis. Linguistic values are essentially the values of linguistic variables.

temperature (t) = {cold, warm, hot}

With the above example, temperature is your linguistic variables, and cold, warm, and hot are the linguistic values.

Membership Function and Fuzzy Rules

In a fuzzy set, the membership function defines a value or point.

For this example, we can have three membership functions as an input, say:

  1. Cold
  2. Warm
  3. Hot

While we can also have three membership functions as output:

  1. Cool
  2. No change
  3. Heat

Fuzzy Rules takes in the simple IF-THEN rule with a condition and conclusion.

Mapping the membership functions above into Fuzzy Rules, we have the following statements:

IF (temperature is COLD) AND (target is COLD) THEN command is NO-CHANGE
IF (temperature is COLD) AND (target is WARM) THEN command is HEAT
IF (temperature is COLD) AND (target is HOT) THEN command is HEAT
IF (temperature is WARM) AND (target is COLD) THEN command is COOL
IF (temperature is WARM) AND (target is WARM) THEN command is NO-CHANGE
IF (temperature is WARM) AND (target is HOT) THEN command is HEAT
IF (temperature is HOT) AND (target is COLD) THEN command is COOL
IF (temperature is HOT) AND (target is WARM) THEN command is COOL
IF (temperature is HOT) AND (target is HOT) THEN command is NO-CHANGE

The table below shows the 3 x 3 representation for the fuzzy rules:

Fuzzy Set Operations

The evaluations of the fuzzy rules and the combination of the results of the individual rules are performed using fuzzy set operations. Fuzzy set operations differ from standard logic operations.

  1. Union

This is where the output contains all the elements of both sets.

2. Intersection

This is where the output contains only the common element of both sets.

3. Negation

This is where the output contains everything that is not found in the set.

4. Aggregation

This is where the output contains the combination of fuzzy sets representing the outputs of each rule.

Defuzzification

Because the output of Fuzzy Set Operations is a fuzzy value, we need some way to convert it into values that machines can understand. This is known as defuzzification.

A fuzzy value can be defuzzified in different ways. Some of them are:

  1. Center of Sums
  2. Centroid Method
  3. Center of Area
  4. Weighted Average Method
  5. Max-Membership Principal

Applying Fuzzy Logic in PHP

As developers, we were asked by the HR team to create an app that needs to pick the best candidate out of the applicants applying for the Web Developer position.

To keep things simple for this blog, we were given only the following criteria to judge:

● The applicants’ year of experience in developing web applications.
● Their score in their practical test.
● Their score in Team and HR interview.

Imagine that we have the following list of applicants with their features:

Constructing the code

First, we’re going to implement the membership and aggregation functions that we need. There are many aggregation functions, but for simplicity we will use one of the famous aggregation functions, which is the arithmetic mean.

/**
* Get the arithmetic mean of the features.
*
@param array $aParams
*
@return float|int
*/
private function
getArithmeticMean(array $aParams)
{
$mCount = (float)count($aParams);
$mSum = (float)array_sum($aParams);

return $mSum / $mCount;
}

Then we will use the triangular function as the membership function.

/**
* Triangular membership function
*
@param $fApplicantValue
*
@param $aTrimfValues
*
@return float|int
*/
private function
getTrimf(float $fApplicantValue, array $aTrimfValues)
{
$aTrimfValues[0] = (float)$aTrimfValues[0];
$aTrimfValues[1] = (float)$aTrimfValues[1];
$aTrimfValues[2] = (float)$aTrimfValues[2];


if ($fApplicantValue < $aTrimfValues[0]) {
return 0;
}

if ($fApplicantValue >= $aTrimfValues[0] && $fApplicantValue <= $aTrimfValues[1]) {
return ($fApplicantValue - $aTrimfValues[0]) / ($aTrimfValues[1] - $aTrimfValues[0]);
}

if ($fApplicantValue > $aTrimfValues[1] && $fApplicantValue <= $aTrimfValues[2]) {
return ($aTrimfValues[1] - $fApplicantValue) / ($aTrimfValues[2] - $aTrimfValues[1]) + 1;
}


return 0;
}

After the aggregate and membership function has been implemented, we need to add the rest of the code to process the input.

/**
* Analyze the following features, and applicants
*
@param array $aSetFeatures
*
@param array $aApplicants
*
@return array
*/
public function
analyzeItems(array $aSetFeatures, array $aApplicants): array
{
$aResults = [];

for ($iCount = 0, $iCountMax = count($aApplicants); $iCount < $iCountMax; $iCount++) {
$aResults[$iCount]['identifier'] = $aApplicants[$iCount]['identifier'];
$aResults[$iCount]['score'] = $this->aggregateSet($aApplicants[$iCount], $aSetFeatures);
}

return $aResults;
}

/**
*
@param array $aApplicant
*
@param array $aSetFeatures
*
@return float|int
*/
private function
aggregateSet(array $aApplicant, array $aSetFeatures)
{
$aFeatureScores = [];

for ($iCount = 0, $iCountMax = count($aSetFeatures); $iCount < $iCountMax; $iCount++) {
$aFeatureScores[$iCount] = $this->getTrimf($aApplicant['features'][$aSetFeatures[$iCount]['identifier']], $aSetFeatures[$iCount]['values']);
}

return $this->getArithmeticMean($aFeatureScores);
}

After adding the process, we need to specify the features we will use when analyzing the list of applicants. Since we’re using the triangular membership function, the second parameter in the values parameter is our ideal value.

For example, in experience_years, we have the following values: 0, 3, 5. This means that the preferred year of experience is 3 among those who don’t have a year of experience yet and those who already had 5 years of experience and above.

$this->aSetFeatures = [
[
'identifier' => 'experience_years',
'values' => [0, 3, 5]
], [
'identifier' => 'practical_test_score',
'values' => [0, 100, 100]
], [
'identifier' => 'team_interview_score',
'values' => [0, 5, 5]
], [
'identifier' => 'hr_interview_score',
'values' => [0, 10, 10]
]
];

We will now need to specify the inputs for each applicant:

$this->aApplicants = [
[
'identifier' => 'Applicant A',
'features' => [
'experience_years' => 3,
'practical_test_score' => 87.30,
'team_interview_score' => 5,
'hr_interview_score' => 9
]
], [
'identifier' => 'Applicant B',
'features' => [
'experience_years' => 4,
'practical_test_score' => 88.25,
'team_interview_score' => 3,
'hr_interview_score' => 8
]
], [
'identifier' => 'Applicant C',
'features' => [
'experience_years' => 4,
'practical_test_score' => 81.67,
'team_interview_score' => 5,
'hr_interview_score' => 7
]
], [
'identifier' => 'Applicant D',
'features' => [
'experience_years' => 1,
'practical_test_score' => 91.90,
'team_interview_score' => 4,
'hr_interview_score' => 7
]
], [
'identifier' => 'Applicant E',
'features' => [
'experience_years' => 1,
'practical_test_score' => 89.58,
'team_interview_score' => 4,
'hr_interview_score' => 8
]
], [
'identifier' => 'Applicant F',
'features' => [
'experience_years' => 2,
'practical_test_score' => 89.49,
'team_interview_score' => 4,
'hr_interview_score' => 7
]
], [
'identifier' => 'Applicant G',
'features' => [
'experience_years' => 4,
'practical_test_score' => 98.94,
'team_interview_score' => 4,
'hr_interview_score' => 8
]
], [
'identifier' => 'Applicant H',
'features' => [
'experience_years' => 4,
'practical_test_score' => 80.80,
'team_interview_score' => 4,
'hr_interview_score' => 8
]
], [
'identifier' => 'Applicant I',
'features' => [
'experience_years' => 2,
'practical_test_score' => 82.97,
'team_interview_score' => 4,
'hr_interview_score' => 8
]
], [
'identifier' => 'Applicant J',
'features' => [
'experience_years' => 2,
'practical_test_score' => 81.91,
'team_interview_score' => 3,
'hr_interview_score' => 7
]
]
];

Finally, we have to add the code to run the analyzer and display the results.

/**
* Run analyzer and return the results.
*
@return Factory|View
*/
public function
index()
{
$aResults = $this->analyzeItems($this->aSetFeatures, $this->aApplicants);
return view('index', compact($aResults));
}

Output:

Using the triangle membership function and the arithmetic mean aggregation, we could say that among others, Applicant A is the most preferred applicant to be hired.

But take note, however, we didn’t specify any weights in this demo. Also, the Arithmetic Mean and Triangular Membership function doesn’t really fit with this kind of scenario — we’ve only used this because it’s simple and should give you an idea of how Fuzzy Logic works in PHP.

You could also visit this GitHub repository to learn more. This is where most of the demo code was based. If you like, you can also read the references below.

Anyways, peace out! ✌

References:

  1. Fuzzy Sets* by L.A. Zadeh
  2. A Short Fuzzy Logic Tutorial
  3. What is Fuzzy Logic?
  4. Introduction to fuzzy logic
  5. Temperature Control using Fuzzy Logic
  6. Artificial Intelligence — Fuzzy Logic Systems
  7. ketili/fuzzydm

SimpleX Internet PHILIPPINES

Blogs made by SimpleX Internet Philippines’ developers

Daniel Sioson

Written by

SimpleX Internet PHILIPPINES

Blogs made by SimpleX Internet Philippines’ developers

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade