Nexus Learn

Practical 9A: Mamdani Inference by Hand

Lab Practical CS-511 Artificial Intelligence 9 min read Updated 8 Nov 2026
On this page
  1. 1. Objectives
  2. 2. Word Bank
  3. 3. Background
  4. 4. Time Plan (50 minutes)
  5. Part A - Guided Warm-up (type, run, observe)
  6. Part B - Predict the Output
  7. Part C - Bug Hunt
  8. Part D - Graded Tasks (10 marks)
  9. Part E - Post-Lab Questions (finish as homework if time runs out)
  10. Marking Rubric (applied to Part D)
  11. Submission

1. Objectives

  1. Carry out the five steps of Mamdani inference in NumPy: fuzzify, fire rules, implication, aggregation, defuzzification.
  2. Write fire() and mamdani() functions for the P08 fan controller.
  3. Check your own inference against skfuzzy.control.
  4. Compare clipping (min) and scaling (product) implication.

2. Word Bank

Word

Simple meaning

Real-world example

Mamdani system

A fuzzy system whose rule outputs are fuzzy sets, joined and defuzzified

The P08 fan controller

Fuzzify

Turn a crisp input into degrees of each term

36 °C -> hot 0.8

Firing strength

How true a rule's IF part is (AND = min, NOT = 1 - μ)

hot AND NOT dry = 0.2

Implication

Cut (clip) or shrink (scale) the THEN set by the firing strength

'fast' clipped at 0.8

Aggregation

Join all rule outputs into one shape with max

slow + medium + fast pieces

Defuzzify

Turn the joined shape into one number (centroid)

45 % fan speed

3. Background

Opening the black box

In P08 sim.compute() gave the answers. Today we write compute() ourselves. Ebrahim Mamdani built the first fuzzy controller in 1975 for a steam engine; his method is still the most common. Five steps: (1) FUZZIFY each input with interp_membership; (2) FIRE each rule: AND = min, OR = max, NOT = 1 - μ; (3) IMPLICATION: clip the THEN set at the rule's strength (np.fmin); (4) AGGREGATION: join all clipped sets with np.fmax; (5) DEFUZZIFY with the centroid.

Clip or scale?

Mamdani clips the output set (min). Another choice, the Larsen method, SCALES it (multiplies the set by the strength), which keeps the triangle's shape. Both are allowed; they give slightly different answers when several rules fire.

Today's inputs

The same rules, sets and test days as P08. Our own code must give exactly what skfuzzy.control gave: 82.78 % at 36 °C, 70 % and 45.0 % at 30 °C, 40 %.

Data files for this lab

No data file is needed - the programs make their own data.

4. Time Plan (50 minutes)

Minutes

Activity

Part

0-5

Background: the five Mamdani steps

1-3

5-10

Guided warm-up: fuzzify; one full inference by hand

Part A

10-13

Predict the output

Part B

13-17

Bug hunt

Part C

17-47

Graded tasks 1-3

Part D

47-50

Wrap-up; post-lab questions set as homework

Part E

Part A - Guided Warm-up (type, run, observe)

A1. Step 1 - fuzzify the inputs

Read the degree of each term at 30 °C and 40 % humidity. One crisp value belongs to several sets at once.

import numpy as np

import skfuzzy as fuzz

t_x = np.arange(0, 51, 1) # temperature, C

h_x = np.arange(0, 101, 1) # humidity, %

f_x = np.arange(0, 101, 1) # fan speed, %

T = {"cold": fuzz.trapmf(t_x, [0, 0, 10, 20]), "comfortable": fuzz.trimf(t_x, [15, 24, 33]),

"hot": fuzz.trapmf(t_x, [28, 38, 50, 50])}

H = {"dry": fuzz.trapmf(h_x, [0, 0, 20, 50]), "normal": fuzz.trimf(h_x, [30, 50, 70]),

"humid": fuzz.trapmf(h_x, [50, 80, 100, 100])}

F = {"slow": fuzz.trimf(f_x, [0, 0, 50]), "medium": fuzz.trimf(f_x, [25, 50, 75]),

"fast": fuzz.trimf(f_x, [50, 100, 100])}

mu = lambda x_axis, mf, value: float(fuzz.interp_membership(x_axis, mf, value))

import matplotlib.pyplot as plt

t, h = 30, 40

for k in T: print(f"{t} C is {k:<12} {mu(t_x, T[k], t):.2f}")

for k in H: print(f"{h} % is {k:<7} {mu(h_x, H[k], h):.2f}")

plt.figure(figsize=(7, 2.4))

for k, mf in T.items(): plt.plot(t_x, mf, label=k)

plt.axvline(t, color="red", ls="--"); plt.xlabel("Temperature (°C)"); plt.ylabel("Degree"); plt.legend(); plt.grid(alpha=0.3)

plt.tight_layout(); plt.savefig("fuzzify.png", dpi=90)

print("Saved fuzzify.png")

Output

30 C is cold 0.00

30 C is comfortable 0.33

30 C is hot 0.20

40 % is dry 0.33

40 % is normal 0.50

40 % is humid 0.00

Saved fuzzify.png

A2. Steps 2-5 - one full Mamdani inference (30 °C, 40 %)

Fire the five rules, clip each THEN set, join with max and take the centroid.

# ... set-up: imports, universes and the P08 fuzzy sets (copy from Part A1) ...

import matplotlib.pyplot as plt

t, h = 30, 40

cold, comf, hot = (mu(t_x, T[k], t) for k in ("cold", "comfortable", "hot"))

dry = mu(h_x, H["dry"], h)

rules = [("R1", "slow", cold), ("R2", "slow", min(comf, dry)), ("R3", "medium", min(comf, 1 - dry)),

("R4", "medium", min(hot, dry)), ("R5", "fast", min(hot, 1 - dry))]

agg = np.zeros_like(f_x, dtype=float)

for name, term, w in rules:

print(f"{name} -> {term:<6} strength {w:.2f}")

agg = np.fmax(agg, np.fmin(F[term], w)) # clip, then join

speed = fuzz.defuzz(f_x, agg, "centroid")

print(f"Centroid: fan {speed:.2f} % (P08a skfuzzy.control: 45.0 %)")

plt.figure(figsize=(7, 2.4))

for mf in F.values(): plt.plot(f_x, mf, ":", c="grey")

plt.fill_between(f_x, agg, alpha=0.5); plt.axvline(speed, c="red")

plt.xlabel("Fan speed (%)"); plt.ylabel("Degree"); plt.grid(alpha=0.3); plt.tight_layout(); plt.savefig("aggregate.png", dpi=90)

print("Saved aggregate.png")

Output

R1 -> slow strength 0.00

R2 -> slow strength 0.33

R3 -> medium strength 0.33

R4 -> medium strength 0.20

R5 -> fast strength 0.20

Centroid: fan 45.04 % (P08a skfuzzy.control: 45.0 %)

Saved aggregate.png

Part B - Predict the Output

Write your prediction BEFORE running the code. Then run it and correct yourself in a different colour.

B1.

hot, dry = 0.2, 0.33

print(round(min(hot, 1 - dry), 2), round(max(hot, dry), 2))

My prediction

B2.

# ... set-up: imports, universes and the P08 fuzzy sets (copy from Part A1) ...

clipped = np.fmin(F["fast"], 0.8)

print(clipped.max(), round(clipped.sum(), 1), round(F["fast"].sum(), 1))

My prediction

B3.

# ... set-up: imports, universes and the P08 fuzzy sets (copy from Part A1) ...

clip = fuzz.defuzz(f_x, np.fmin(F["fast"], 0.8), "centroid")

scale = fuzz.defuzz(f_x, F["fast"] * 0.8, "centroid")

print(round(clip, 2), round(scale, 2))

My prediction

Part C - Bug Hunt

Each program has ONE bug. Some crash with an error message; others run but give a wrong answer (silent logic error - the dangerous kind). Find the bug, explain it and write the fix.

C1.

# ... set-up: imports, universes and the P08 fuzzy sets (copy from Part A1) ...

def fire(t, h):

"""Firing strength of the five P08 rules: (output term, strength)."""

cold, comf, hot = (mu(t_x, T[k], t) for k in ("cold", "comfortable", "hot"))

dry = mu(h_x, H["dry"], h)

return [("slow", cold), # R1 IF cold THEN slow

("slow", min(comf, dry)), # R2 IF comfortable AND dry THEN slow

("medium", min(comf, 1 - dry)), # R3 IF comfortable AND NOT dry THEN medium

("medium", min(hot, dry)), # R4 IF hot AND dry THEN medium

("fast", min(hot, 1 - dry))] # R5 IF hot AND NOT dry THEN fast

agg = np.zeros_like(f_x, dtype=float)

for term, w in fire(36, 70):

agg = np.fmax(agg, np.fmax(F[term], w)) # implication

print("fan at 36 C, 70 %:", round(fuzz.defuzz(f_x, agg, "centroid"), 2))

It runs and prints

fan at 36 C, 70 %: 50.0

Bug, why it happens, and the fixed line(s)

C2.

# ... set-up: imports, universes and the P08 fuzzy sets (copy from Part A1) ...

dry = fuzz.interp_membership(t_x, H["dry"], 40)

print(dry)

Bug, why it happens, and the fixed line(s)

C3.

# ... set-up: imports, universes and the P08 fuzzy sets (copy from Part A1) ...

t, h = 34, 30

hot, dry = mu(t_x, T["hot"], t), mu(h_x, H["dry"], h)

r4 = min(hot, dry) # IF hot AND dry THEN medium

r5 = min(hot, dry) # IF hot AND NOT dry THEN fast

agg = np.fmax(np.fmin(F["medium"], r4), np.fmin(F["fast"], r5))

print(f"R4 {r4:.2f}, R5 {r5:.2f} -> fan {fuzz.defuzz(f_x, agg, 'centroid'):.2f} %")

It runs and prints

R4 0.60, R5 0.60 -> fan 65.92 %

Bug, why it happens, and the fixed line(s)

Part D - Graded Tasks (10 marks)

Task

Level

Title

Marks

T1

Easy

Write fire()

3

T2

Medium

Write mamdani() and check it

3

T3

Challenge

Clip or scale?

4

Total

10

Task 1 (Easy, 3 marks): Write fire()

Write a function fire(t, h) that returns the five P08 rules as a list of (output term, firing strength) pairs (R1 cold -> slow; R2 comfortable AND dry -> slow; R3 comfortable AND NOT dry -> medium; R4 hot AND dry -> medium; R5 hot AND NOT dry -> fast). Print the strengths for (30 °C, 40 %), (34 °C, 65 %) and (20 °C, 70 %). Which rules fire for each input?

Sample run (your output must match):

Output

30 C, 40 %: R1=0.00 R2=0.33 R3=0.33 R4=0.20 R5=0.20

fired: ['R2', 'R3', 'R4', 'R5']

34 C, 65 %: R1=0.00 R2=0.00 R3=0.00 R4=0.00 R5=0.60

fired: ['R5']

20 C, 70 %: R1=0.00 R2=0.00 R3=0.56 R4=0.00 R5=0.00

fired: ['R3']

Your code (or attach the file)

Task 2 (Medium, 3 marks): Write mamdani() and check it

Using fire(), write mamdani(t, h) that clips each rule's output set with np.fmin, joins them with np.fmax and returns the centroid. Compute the fan speed for the five P07b days (30, 40), (34, 65), (38, 75), (41, 55), (36, 90), and compare with skfuzzy.control built from the same rules (print both and the largest difference).

Sample run (your output must match):

Output

30 C, 40 %: mine 45.04 % skfuzzy 45.05 %

34 C, 65 %: mine 81.43 % skfuzzy 81.43 %

38 C, 75 %: mine 83.33 % skfuzzy 83.33 %

41 C, 55 %: mine 83.33 % skfuzzy 83.33 %

36 C, 90 %: mine 82.78 % skfuzzy 82.78 %

largest difference: 0.003284

Your code (or attach the file)

Task 3 (Challenge, 4 marks): Clip or scale?

Add a second implication method: scale each output set by its strength (F[term] * w) instead of clipping. For the five days and for (30 °C, 40 %), print the clip and scale results. Plot the two aggregated shapes for (30 °C, 40 %) on one figure (save task3.png). When do the two methods agree, and why?

Sample run (your output must match):

Output

input clip scale

30 C, 40 % 45.04 44.51

34 C, 65 % 81.43 83.33

38 C, 75 % 83.33 83.33

41 C, 55 % 83.33 83.33

36 C, 90 % 82.78 83.33

Saved task3.png

Your code (or attach the file)

Part E - Post-Lab Questions (finish as homework if time runs out)

E1. List the five steps of Mamdani inference and the NumPy / scikit-fuzzy call for each.

Your answer

E2. Why did np.fmax as implication give 50 % at 36 °C, 70 %?

Your answer

E3. What is the difference between clipping and scaling implication?

Your answer

Marking Rubric (applied to Part D)

Criterion

Full

Partial

None

Code runs without errors

Runs fully

Small fixable error

Does not run

Correct fuzzify, fire (min / 1 - μ), clip and aggregate

All correct

One slip

Several wrong

Results match skfuzzy.control; table and plot present

All present

Some missing

None

Explanation of clip vs scale

Clear and correct

Partly correct

Missing

Submission

  • Make a folder RollNo_P09a with task1.py, task2.py, task3.py (or P09a.ipynb) and task3.png.
  • Upload the zipped folder to the LMS / Google Classroom by the end of the day.
  • Copy Task 1 and Task 2 code and output into your Lab Book (Practical 09a page).
  • Keep fire() - P09b uses it for the Sugeno system.

← All CS-511 material