KURSUS PEMBANGUNAN
ARTIFICIAL INTELLIGENCE (AI)
Modul 2
Fuzzy Logic
INSTITUT TADBIRAN AWAM NEGARA
(INTAN)
Topik
• Pengenalan kepada Google Colab
• Definisi dan konsep Fuzzy Logic
• Aplikasi Fuzzy Logic
• Arkitektur Fuzzy Logic
• Aktiviti Hands On
Hasilan Pembelajaran
• Pada akhir sesi ini, peser dapat
• Menggunakan Google Colab dengan betul
• Menerangkan konsep Fuzzy Logic dengan jelas
• Megaplikasi algoritma Fuzzy Logic dengan betul
Introduction to Google
Colab
What is Google Colab
• Google Colab, short for Google Colaboratory, is a free cloud-based
platform provided by Google that allows users to write and execute
Python code in a browser-based interactive environment.
• It provides a hosted Jupyter Notebook service that enables users to
create and share documents containing live code, equations,
visualizations, and narrative text.
• Google Colab provides free access to powerful hardware
accelerators, including GPUs (Graphics Processing Units) and
TPUs (Tensor Processing Units), which significantly speed up the
training of machine learning models.
Google Colab Features
• Interactive Code Execution: Users can write and execute Python code
in a cell-based structure, making it easy to test and debug code in small
chunks.
• Rich Text Editing: Combine executable code with rich text, including
Markdown, LaTeX, and HTML, to create comprehensive and well-
documented notebooks.
• Data Importing: Easily import datasets from local files, Google Drive, or
directly from the web using URL links.
• Visualization Tools: Create and display plots and charts directly within
the notebook using libraries like Matplotlib and Seaborn.
Accessing Google Colab
• Go to:
[Link]
• Please make sure that you logged in into your Google Account
Google Colab Landing Page
Creating a
New
Notebook
Create new
notebook
Notebook name
Choose whether to
add code or text
Practice 1
• Rename the Jupyter notebook as
“My Python Code”
• Click + Text the type
“This is just a testing using Python
on Google Colab”
• Click + Code and type the
following code
print (“Hello World”)
Click the “Play”
button to run the
code
Practice 2
• Write and run the following code:
Practice 3
Definition
• An approach to
variable processing
that allows for multiple
possible truth values to
be processed through
the same variable
• Introduced by Lotfi
Zadeh in 1965
Concept
• Problem : Most classes are too precise. We need to generalize that
and introduce a class whose boundaries are un-sharp
• Used to imitate human reasoning and cognition.
• Human decision making includes a range of possibilities between
YES and NO.
Fuzzy Logic Applications
Control Systems Automotive Systems
• Washing Machines: Use fuzzy • Automatic Transmission:
logic to adjust wash cycles Determines the optimal gear
based on the load's weight, shift based on speed, engine
dirtiness, and fabric type. This load, and driving style.
optimizes water and detergent • Anti-lock Braking Systems
use, improving washing (ABS): Controls braking pressure
efficiency. to prevent wheel lockup while
• Air Conditioners: Adjust the maintaining vehicle control.
cooling power based on
temperature, humidity, and
occupancy to maintain a
comfortable environment.
Fuzzy Logics Application (cont.)
Consumer Electronics Transportation and Traffic
• Cameras: Adjust focus, Management
exposure, and white balance • Traffic Signal Control: Adjusts
automatically to capture the best signal timings based on real-time
possible images. traffic conditions to reduce
• Microwaves: Optimize cooking congestion.
time and power based on the • Navigation Systems: Provides
type and weight of the food. route recommendations based
on traffic, road conditions, and
user preferences.
Fuzzy Logics Application (cont.)
Finance Agriculture
• Credit Scoring: Evaluates the • Irrigation Systems: Adjusts
creditworthiness of individuals water supply based on soil
based on fuzzy criteria. moisture, weather conditions,
• Investment Analysis: Assists in and crop requirements.
making investment decisions by • Crop Management: Assists in
analyzing market trends and pest control and fertilizer
risks. application by analyzing various
environmental factors.
Fuzzy System Architecture
Fuzzy Rule
• The core component of a fuzzy logics system.
• Defines the relationship between input variables and output
variables using linguistic terms rather than precise numerical
values.
• designed to handle the ambiguity and uncertainty
• Made of two parts
• Antecedent (IF-part) - Describes the state of input variables using
linguistic terms and fuzzy sets.
Example: "If temperature is high“
• Consequent (THEN-part) - Describes the desired state of output
variables.
Example: "Then fan speed is high"
Fuzzy Rule Components
• Linguistic Variables: Variables described • Consider a system that controls
a fan based on temperature and
in natural language terms (e.g., humidity:
temperature, speed). 1. "If temperature is high and
• Fuzzy Sets: Groups or categories that humidity is low, then fan
speed is high.“
describe the values of linguistic variables 2. "If temperature is medium
(e.g., low, medium, high). and humidity is medium,
then fan speed is medium.“
• Membership Functions: Functions that
3. "If temperature is low and
define the degree to which a particular humidity is high, then fan
input belongs to a fuzzy set (e.g., a speed is low."
temperature of 75°F might belong to the
"high" fuzzy set with a membership degree
of 0.7).
Fuzzifier
• Fuzzifier is responsible for fuzzification: a process that converts
crisp (precise) input values into fuzzy values/fuzzy sets.
Converting Crisp Defining
Handling
Inputs to Fuzzy Membership
Uncertainty
Values Functions
Membership
Functions
• 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
• There are 4 types of
membership function:
Gaussian, Sigmoid, Triangular,
Trapezoidal
Membership
Functions - Example
• Example: A
temperature of 45°C
might have a
membership degree of
0.7 in the "warm" fuzzy
set and 0.1 in cold
fuzzy set
Fuzzy Inference
• The process of formulating the mapping from a given input to an
output using fuzzy logic.
• Involves several steps that combine fuzzy rules, membership
functions, and logical operations to make decisions based on
imprecise, vague, or ambiguous information.
Fuzzy
Inference
Example
Defuzzification
• The process of obtaining a single number from the output of the
aggregated fuzzy set
• Defuzzification methods : max membership principle, centroid
method, weighted average method, mean max membership,
center of sums, center of largest area and first of maxima, last of
maxima.
Fuzzy Logic
Hands-On
Temperature Control Problem
• In many modern air conditioning systems, maintaining a
comfortable room temperature is crucial. Adjusting the fan speed
appropriately based on the current room temperature to ensure
optimal comfort while minimizing energy consumption.
• Traditional control methods may not handle the gradual changes
and inherent uncertainties in temperature variations effectively.
Temperature Control Problem (cont.)
• To address this, we employ a fuzzy logic-based approach. The
system takes the current room temperature as input and adjusts
the fan speed accordingly.
• The temperature is categorized into three fuzzy sets: cold, warm, and hot,
each with corresponding
• fan speed settings: low, medium, and high.
• Fuzzy rules:
• If the temperature is cold, then the fan speed should be low.
• If the temperature is warm, then the fan speed should be medium.
• If the temperature is hot, then the fan speed should be high.
• STEP 1: Install scikit-fuzzy library
pip install scikit-fuzzy
• STEP 2: Import necessary
import numpy as np
import skfuzzy as fuzz from skfuzzy
import control as ctrl
• STEP 3: Define the universe of discourse for temperature and
fan speed
temperature = [Link]([Link](0, 41, 1),
'temperature')
fan_speed = [Link]([Link](0, 101, 1),
'fan_speed')
• STEP 4: Define the fuzzy membership functions for temperature
temperature['cold'] = [Link]([Link], [0,
0, 15])
temperature['warm'] = [Link]([Link],
[10, 20, 30])
temperature['hot'] = [Link]([Link], [25,
40, 40])
• STEP 5: Define the fuzzy membership functions for fan speed
fan_speed['low'] = [Link](fan_speed.universe, [0, 0,
50])
fan_speed['medium'] = [Link](fan_speed.universe, [30,
50, 70])
fan_speed['high'] = [Link](fan_speed.universe, [60,
100, 100])
• STEP 6: Define the fuzzy rules
rule1 = [Link](temperature['cold'], fan_speed['low'])
rule2 = [Link](temperature['warm'],
fan_speed['medium'])
rule3 = [Link](temperature['hot'], fan_speed['high'])
• STEP 7: Create the control system
temperature_control = [Link]([rule1, rule2,
rule3])
temperature_simulation =
[Link](temperature_control)
• STEP 8: Simulate the control system with a specific
temperature input
temperature_simulation.input['temperature'] = 15
temperature_simulation.compute()
• STEP 9: Print and visualize the result
print(f"Fan speed: {temperature_simulation.output
['fan_speed'] :.2f}")
[Link](sim=temperature_simulation)
fan_speed.view(sim=temperature_simulation)
Result
Input (Temp) = 28
Fan speed: 65.99
Sprinkler System
• Design a fuzzy logic control system for a sprinkler system that determines the
appropriate watering duration based on two environmental factors: soil
moisture and temperature. This system aims to optimize water usage by
adjusting the sprinkler duration according to the current conditions.
Soil Moisture Temperature Sprinkler Duration
• Dry: Low soil moisture, • Cold: Low temperatures, • Short: Minimal watering
requiring more water typically requiring less watering required
• Moist: Moderate soil moisture, • Warm: Moderate temperatures, • Medium: Moderate watering
requiring less water. requiring standard watering. required.
• Wet: High soil moisture, • Hot: High temperatures, • Long: Extended watering
requiring little to no additional typically requiring more required
water. watering to prevent plant
stress.
• Fuzzy Rules
1. If soil moisture is dry and temperature is hot, then sprinkler duration is long.
2. If soil moisture is dry and temperature is warm, then sprinkler duration is
medium.
3. If soil moisture is dry and temperature is cold, then sprinkler duration is short.
4. If soil moisture is moist and temperature is hot, then sprinkler duration is
medium.
5. If soil moisture is moist and temperature is warm, then sprinkler duration is
short.
6. If soil moisture is moist and temperature is cold, then sprinkler duration is
short.
7. If soil moisture is wet and temperature is hot, then sprinkler duration is short.
8. If soil moisture is wet and temperature is warm, then sprinkler duration is
short.
9. If soil moisture is wet and temperature is cold, then sprinkler duration is short.
• STEP 1 & 2: Install scikit-fuzzy library and import necessary
libraries
• STEP 3: Define the universe of discourse for inputs and output
soil_moisture = [Link]([Link](0, 101, 1),
'soil_moisture’)
temperature = [Link]([Link](0, 41, 1),
'temperature’)
sprinkler_duration = [Link]([Link](0, 61, 1),
'sprinkler_duration')
• STEP 4: Define the fuzzy membership functions for soil moisture
soil_moisture['dry'] = [Link](soil_moisture.universe,
[0, 0, 50])
soil_moisture['moist'] =
[Link](soil_moisture.universe, [30, 50, 70])
soil_moisture['wet'] = [Link](soil_moisture.universe,
[50, 100, 100])
• STEP 5: Define the fuzzy membership functions for temperature
temperature['cold'] = [Link]([Link], [0,
0, 15])
temperature['warm'] = [Link]([Link],
[10, 20, 30])
temperature['hot'] = [Link]([Link], [25,
40, 40])
• STEP 6: Define the fuzzy membership functions for sprinkler
duration
sprinkler_duration['short'] =
[Link](sprinkler_duration.universe, [0, 0, 20])
sprinkler_duration['medium'] =
[Link](sprinkler_duration.universe, [10, 30, 50])
sprinkler_duration['long'] =
[Link](sprinkler_duration.universe, [40, 60, 60])
• STEP 7: Define the fuzzy rules
rule1 = [Link](soil_moisture['dry'] & temperature['hot'],
sprinkler_duration['long’])
rule2 = [Link](soil_moisture['dry'] & temperature['warm'],
sprinkler_duration['medium’])
rule3 = [Link](soil_moisture['dry'] & temperature['cold'],
sprinkler_duration['short’])
rule4 = [Link](soil_moisture['moist'] & temperature['hot'],
sprinkler_duration['medium’])
rule5 = [Link](soil_moisture['moist'] & temperature['warm'],
sprinkler_duration['short’])
rule6 = [Link](soil_moisture['moist'] & temperature['cold'],
sprinkler_duration['short’])
rule7 = [Link](soil_moisture['wet'] & temperature['hot’],
sprinkler_duration['short’])
rule8 = [Link](soil_moisture['wet'] & temperature['warm'],
sprinkler_duration['short’])
rule9 = [Link](soil_moisture['wet'] & temperature['cold'],
sprinkler_duration['short'])
• STEP 8: Create the control system
sprinkler_control = [Link]([rule1, rule2,
rule3, rule4, rule5, rule6, rule7, rule8, rule9])
sprinkler_simulation =
[Link](sprinkler_control)
• STEP 9: Simulate the control system with specific inputs
sprinkler_simulation.input['soil_moisture'] = 40
sprinkler_simulation.input['temperature'] = 25
sprinkler_simulation.compute()
• STEP 10: Print and visualize the result
print(f"Sprinkler duration:
{sprinkler_simulation.output['sprinkler_duration']:.2f}
minutes")
soil_moisture.view(sim=sprinkler_simulation)
[Link](sim=sprinkler_simulation)
sprinkler_duration.view(sim=sprinkler_simulation)
Result
Sprinkler duration:
18.99 minutes