Fuzzy Logic
Fuzzy sets, membership functions, linguistic variables, rule evaluation, aggregation, defuzzification, and controller design.
Many useful concepts have gradual boundaries. A room can be somewhat warm, traffic can be very heavy, and a risk can be moderately high. Classical sets require membership to be either 0 or 1. Fuzzy sets represent degree of membership between them.
Fuzziness is not randomness. If temperature is known to be 28°C, membership in “warm” may be 0.7. That does not mean there is a 70% chance the temperature is warm; it describes how well a known value fits a vague concept.
Expert Systems
An expert system stores domain knowledge separately from the mechanism that applies it. Its main parts are:
- a knowledge base containing facts, concepts, relationships, or rules;
- an inference engine that derives conclusions from current facts;
- working memory holding case-specific information;
- a user or software interface for entering facts and receiving advice;
- an explanation facility that records which knowledge supported a conclusion.
The separation matters. A medical rule can change without rewriting the inference engine, and the same engine can support another rule base.
Common forms include:
- a rule-based system, whose knowledge is written as
IF condition THEN conclusion; - a frame-based system, which organizes concepts as structured objects with attributes, defaults, and relationships;
- a fuzzy expert system, whose facts and rules use graded concepts such as low, moderate, and high.
A crisp rule might require temperature > 30. Near that boundary, 29.9 and 30.1 produce completely different results. A fuzzy rule can change its firing strength gradually. This is useful when expert language is inherently vague, but it does not replace probabilistic reasoning about unknown events.
Fuzzy Sets
For universe X, a fuzzy set A has membership:
μ_A(x) ∈ [0,1]
Membership functions may be:
- triangular;
- trapezoidal;
- Gaussian;
- sigmoid;
- learned or expert-defined.
Overlapping sets are expected. At 28°C, both Warm and Hot can have nonzero membership, allowing smooth transitions.
Linguistic Variables
A linguistic variable uses words as values:
Temperature = {Cold, Warm, Hot}
FanSpeed = {Low, Medium, High}
Each label corresponds to a membership function. The design should cover the input range without unexplained gaps and should reflect domain meaning rather than arbitrary shapes.
Fuzzy Rules
Rules have the form:
IF temperature is Hot AND humidity is High
THEN fan is Fast
Common operators:
- AND as minimum;
- OR as maximum;
- NOT as
1 - μ.
Other t-norms and t-conorms exist. Operator choice affects behavior and should be documented.
Rule implication also needs a choice. In Mamdani inference, a rule’s firing strength commonly clips or scales the consequent membership function. Clipping preserves its shape up to a height; scaling reduces every membership value proportionally. The difference can change the aggregated output even when the rule strengths match.
Inference Cycle
A Mamdani-style system uses four stages:
- Fuzzification — convert crisp inputs into memberships.
- Rule evaluation — compute each rule’s firing strength.
- Aggregation — combine consequent fuzzy sets.
- Defuzzification — convert the result to a crisp action.
Worked controller
At 18°C:
μ_Cold(18) = 0.8
μ_Warm(18) = 0.2
Rules:
IF Cold THEN HeaterHigh
IF Warm THEN HeaterLow
The outputs activate at strengths 0.8 and 0.2. Aggregation combines them. Centroid defuzzification selects the balance point of the aggregated output area.
A shortcut weighted-center calculation may illustrate the idea, but a full Mamdani controller should integrate the clipped output membership shapes.
Controller Example
This implementation uses only the Python standard library so every inference step remains visible. The same triangular function defines input and output sets, while the rule list stores a firing strength and consequent label.
def triangular(x, a, b, c):
if not a <= b <= c or a == c:
raise ValueError("expected a <= b <= c with nonzero width")
if a == b and x <= b:
return 1.0
if b == c and x >= b:
return 1.0
if x <= a or x >= c:
return 0.0
if x == b:
return 1.0
if x < b:
return (x - a) / (b - a)
return (c - x) / (c - b)
TEMPERATURE = {
"cold": (0, 0, 20),
"warm": (15, 25, 35),
"hot": (30, 40, 40),
}
HUMIDITY = {
"dry": (0, 0, 40),
"comfortable": (30, 50, 70),
"humid": (60, 100, 100),
}
POWER = {
"low": (0, 0, 50),
"medium": (30, 50, 70),
"high": (60, 100, 100),
}
def memberships(value, sets):
result = {}
for label in sets:
a, b, c = sets[label]
result[label] = triangular(value, a, b, c)
return result
def controller(temperature, humidity):
t = memberships(temperature, TEMPERATURE)
h = memberships(humidity, HUMIDITY)
rules = (
(min(t["cold"], h["dry"]), "low"),
(min(t["cold"], h["comfortable"]), "low"),
(min(t["warm"], h["comfortable"]), "medium"),
(max(t["hot"], h["humid"]), "high"),
(min(t["warm"], h["humid"]), "high"),
(min(t["cold"], h["humid"]), "medium"),
(min(t["warm"], h["dry"]), "medium"),
)
universe = range(101)
aggregated = []
for output in universe:
activated = [
min(strength, triangular(output, *POWER[label]))
for strength, label in rules
]
aggregated.append(max(activated))
area = sum(aggregated)
if area == 0:
raise ValueError("no fuzzy rule covers this input")
return sum(
output * membership
for output, membership in zip(universe, aggregated)
) / area
recommended = controller(temperature=29, humidity=65)
assert 0 <= recommended <= 100
print(f"recommended power: {recommended:.2f}%")
The implementation follows a consistent separation: membership functions encode vocabulary, the controller evaluates rules, and the caller handles input and output. No rule is hidden in a library default.
For larger systems, represent rules as data rather than manually writing each expression. The explicit form above is preferable while learning because the exact min and max operations can be traced.
Membership Design
Membership functions can come from:
- expert elicitation;
- observed operating ranges;
- clustering;
- optimization;
- adaptive learning.
Ask:
- Are boundaries smooth?
- Is every realistic input covered?
- Do labels mean the same thing to stakeholders?
- Are outputs stable near boundaries?
- Does extrapolation behave safely?
More sets increase resolution but also rules and tuning effort.
Rule Bases
A two-input controller can require many combinations. Check for:
- missing combinations;
- contradictory consequents;
- rules that never fire;
- one rule dominating all others;
- unsafe behavior outside normal ranges.
Rules should be testable individually and as a system. A readable rule base is not automatically correct.
Rule Interaction
Several rules commonly fire for one input because membership regions overlap. This is intentional: smooth behavior comes from blending recommendations. It also means a rule cannot be validated only at the center of its named sets.
Conflicts may arise when equally strong rules activate incompatible consequents. Aggregation will blend them, possibly producing a moderate output that no expert intended. Diagnose conflicts by recording:
- every nonzero rule strength;
- the clipped or scaled consequent;
- each rule’s contribution near the centroid;
- the final aggregated output shape.
A broad rule such as IF temperature is hot THEN power is high can dominate a more specific exception. Rule priority is one possible remedy, but it changes ordinary Mamdani semantics. Often the clearer repair is to narrow memberships or add inputs that express the missing condition.
Rule count can grow as the product of input labels. Hierarchical fuzzy systems reduce this explosion by computing intermediate concepts, but intermediate outputs must retain interpretable meaning and avoid amplifying approximation error.
Defuzzification
Methods include:
- centroid;
- bisector;
- mean of maxima;
- weighted average for singleton or Sugeno outputs.
Centroid gives smooth results but can be computationally heavier. Maximum-based methods may jump abruptly. The method should match control requirements.
Sugeno Systems
A Sugeno system gives each rule a constant or mathematical function as its consequent:
IF temperature is Hot AND humidity is High
THEN fan_speed = 0.7 × temperature + 0.2 × humidity
The final result is a weighted average of rule outputs, using firing strengths as weights. This is computationally convenient, differentiable in many formulations, and suitable for adaptive tuning.
Mamdani systems often provide more intuitive output concepts because consequents are fuzzy sets such as Fast. Sugeno systems make crisp computation and optimization easier. The choice depends on whether linguistic transparency or compact numerical control is more important.
Fuzzy Experts
A fuzzy expert system combines domain rules with graded concepts. It is appropriate when experts can describe behavior linguistically but precise mathematical models are unavailable. A typical consultation:
- translates crisp observations into fuzzy memberships;
- matches those memberships against rules;
- aggregates the supported conclusions;
- returns a linguistic class, a crisp score, or both;
- explains the strongest rules and memberships behind the result.
It is less suitable when calibrated probabilities, causal uncertainty, or strong optimality guarantees are required.
Validation
Test a fuzzy system as a function over its whole input space, not only at a few familiar values. Useful checks include:
- plot output surfaces for discontinuities and unexpected ridges;
- sample every boundary and overlap region;
- verify monotonic behavior where the domain requires it;
- test missing, extreme, and out-of-range inputs;
- compare against expert decisions and operational data;
- perturb membership parameters to measure sensitivity.
For a fan controller, increasing temperature should not reduce fan speed when humidity is fixed unless an explicit rule justifies it. Such domain invariants catch errors that rule-by-rule inspection may miss.
Optimization can tune membership functions, but it may also make labels lose their intended meaning. If interpretability matters, constrain the order, overlap, and semantic range of learned sets.
Controller Tuning
Tune against explicit objectives such as comfort error, energy consumption, actuator wear, overshoot, and settling time. These goals may conflict. A controller that reacts aggressively can reduce immediate error while causing oscillation and consuming more energy.
Separate training scenarios from evaluation scenarios. If membership parameters are optimized on the same temperature traces used for reporting, apparent improvement may be overfitting. Test seasonal ranges, sensor noise, delayed response, and conditions just outside the normal envelope.
Fuzzy control does not remove the need for dynamics. A rule base maps current inputs to current output; a physical system has inertia and delay. Simulation or controlled deployment must evaluate the closed loop, not only isolated input-output pairs.
The controller can be checked across its full operating grid:
surface = {
(temperature, humidity): controller(temperature, humidity)
for temperature in range(0, 41, 5)
for humidity in range(0, 101, 10)
}
assert all(0 <= power <= 100 for power in surface.values())
for humidity in range(0, 101, 10):
column = [
surface[(temperature, humidity)]
for temperature in range(0, 41, 5)
]
drops = [
(before, after)
for before, after in zip(column, column[1:])
if after + 1e-9 < before
]
if drops:
print("review non-monotonic region:", humidity, drops)
The diagnostic prints rather than asserts monotonicity because the current rule base may intentionally have shapes that violate it. The design team must decide whether monotonicity is a domain requirement; only then should it become a hard test.
Applications
- temperature control;
- camera autofocus;
- risk scoring;
- vehicle control;
- industrial processes;
- decision support;
- comfort systems.
Common Mistakes
- Calling membership probability.
- Leaving gaps in input coverage.
- Using arbitrary membership shapes.
- Creating contradictory rules.
- Ignoring extreme inputs.
- Defuzzifying with an unexplained shortcut.
- Assuming interpretability guarantees correctness.
- Tuning memberships until their linguistic labels become misleading.
Exercises
- Design overlapping sets for temperature.
- Evaluate three rules for a given input.
- Compare minimum and product AND operators.
- Compute a weighted defuzzified output.
- Build a two-input fan controller with nine rules.
- Test boundary and extreme cases.
- Explain when probability is preferable to fuzzy logic.
- Compare Mamdani and Sugeno outputs on the same controller.
- Plot an output surface and identify a domain invariant to test.