import numpy as np
import pandas as pd
# Input: service quality (0 to 10)
service = 7
# Define triangular membership functions
def poor(x): return max(min((5 - x) / 5, 1), 0)
def average(x): return max(min((x - 2.5) / 2.5, (7.5 - x) / 2.5), 0)
def good(x): return max(min((x - 5) / 5, 1), 0)
# Calculate membership values
degrees = {
'Poor': poor(service),
'Average': average(service),
'Good': good(service)
# Convert to DataFrame for easy handling
df = [Link].from_dict(degrees, orient='index', columns=['Degree'])
# Find label with highest membership value
classification = df['Degree'].idxmax()
# Output
print(f"Service Quality: {classification}")
🧩 Code Explanation:
1️⃣ Import Libraries
python
CopyEdit
import numpy as np
import pandas as pd
We use:
NumPy for math (not used much here, but good for future extensions).
Pandas to create a simple DataFrame and find the max value.
2️⃣ Input Value
python
CopyEdit
service = 7
This is the input — a number from 0 to 10 that represents the quality of service.
3️⃣ Define Membership Functions
These are triangular functions. They return a degree of membership between 0 and 1.
python
CopyEdit
def poor(x):
return max(min((5 - x) / 5, 1), 0)
If x = 0, output = 1 (very poor).
If x = 5, output = 0.
Between 0 and 5, it's a descending line.
python
CopyEdit
def average(x):
return max(min((x - 2.5) / 2.5, (7.5 - x) / 2.5), 0)
Triangle peaks at x = 5, ranges from 2.5 to 7.5.
Forms a symmetrical triangle.
python
CopyEdit
def good(x):
return max(min((x - 5) / 5, 1), 0)
If x = 5, output = 0.
If x = 10, output = 1.
Ascending line from 5 to 10.
4️⃣ Calculate Fuzzy Membership Degrees
python
CopyEdit
degrees = {
'Poor': poor(service),
'Average': average(service),
'Good': good(service)
This dictionary stores the degree to which the input value belongs to each category.
Example if service = 7:
python
CopyEdit
degrees = {
'Poor': 0.0,
'Average': 0.2,
'Good': 0.4
5️⃣ Convert to DataFrame
python
CopyEdit
df = [Link].from_dict(degrees, orient='index', columns=['Degree'])
We turn the dictionary into a Pandas DataFrame, which looks like this:
Degree
Poor 0.00
Average 0.20
Good 0.40
6️⃣ Choose the Category with the Highest Degree
python
CopyEdit
classification = df['Degree'].idxmax()
This finds the label (index) with the highest value.
So in our example:
'Good' has the highest degree (0.4),
Therefore, classification = 'Good'.
7️⃣ Print Final Result
python
CopyEdit
print(f"Service Quality: {classification}")
You'll get:
yaml
CopyEdit
Service Quality: Good
✅ Summary
This is fuzzy logic in its simplest form:
No external libraries,
No defuzzification,
Just fuzzy label classification using basic math.
If you want to:
Add another input like food quality,
Use plots to visualize the membership curves,
Extend it to multiple values (batch),