Soft Computing
Assignment-1
Aryan Chahil
21CS3008
Task 1
Using Python or C/C++ or R, Implement the following membership function and
draw their graphs: triangular, Trapezoidal, Gaussian, Generalized Bell Shaped,
and Sigmoid.
Implementation of membership functions in Python using numpy
and matplotlib
Below is the code to define and plot the following fuzzy membership functions:
1. Triangular Membership Function
2. Trapezoidal Membership Function
3. Gaussian Membership Function
4. Generalized Bell-Shaped Membership Function
5. Sigmoid Membership Function
Python Implementation:
import numpy as np
import [Link] as plt
# Triangular Membership Function
def triangular(x, a, b, c):
return [Link]([Link]((x - a) / (b - a), (c - x) / (c - b)), 0)
# Trapezoidal Membership Function
def trapezoidal(x, a, b, c, d):
return [Link]([Link]([Link]((x - a) / (b - a), 1), (d - x) / (d - c)),
0)
# Gaussian Membership Function
def gaussian(x, mean, sigma):
return [Link](-0.5 * ((x - mean) / sigma) ** 2)
# Generalized Bell Membership Function
def generalized_bell(x, a, b, c):
return 1 / (1 + [Link]((x - c) / a) ** (2 * b))
# Sigmoid Membership Function
def sigmoid(x, a, c):
return 1 / (1 + [Link](-a * (x - c)))
# Generate x values
x = [Link](-10, 10, 400)
# Plot all membership functions
[Link](figsize=(12, 8))
[Link](2, 3, 1)
[Link](x, triangular(x, -5, 0, 5), label="Triangular")
[Link]("Triangular Membership Function")
[Link]()
[Link](2, 3, 2)
[Link](x, trapezoidal(x, -6, -2, 2, 6), label="Trapezoidal")
[Link]("Trapezoidal Membership Function")
[Link]()
[Link](2, 3, 3)
[Link](x, gaussian(x, 0, 2), label="Gaussian")
[Link]("Gaussian Membership Function")
[Link]()
[Link](2, 3, 4)
[Link](x, generalized_bell(x, 2, 2, 0), label="Generalized Bell")
[Link]("Generalized Bell Membership Function")
[Link]()
[Link](2, 3, 5)
[Link](x, sigmoid(x, 1, 0), label="Sigmoid")
[Link]("Sigmoid Membership Function")
[Link]()
plt.tight_layout()
[Link]()
Output
Explanation:
● Triangular: Defined by three points (a, b, c), where b is the peak.
● Trapezoidal: Defined by four points (a, b, c, d), with a flat top between b
and c.
● Gaussian: Defined by mean and standard deviation.
● Generalized Bell: Defined by parameters (a, b, c) affecting width and
shape.
● Sigmoid: Controlled by (a, c), where a determines slope and c the center.
Task 2
2. Implement a membership function to compute the alpha-cut of a given fuzzy
set for a specified alpha level. Show it on a graph.
Implementation of α-Cut for a Fuzzy Set in Python
The α-cut of a fuzzy set extracts all elements whose membership values are at
least α. We will:
● Define a fuzzy set using a membership function.
● Compute the α-cut for a given α level.
● Visualize the fuzzy set and its α-cut.
Python Implementation
import numpy as np
import [Link] as plt
# Define a fuzzy membership function (Triangular in this example)
def triangular(x, a, b, c):
return [Link]([Link]((x - a) / (b - a), (c - x) / (c - b)), 0)
# Function to compute α-cut
def alpha_cut(x, membership_values, alpha):
return x[membership_values >= alpha] # Select x values where membership >= alpha
# Generate x values
x = [Link](-10, 10, 400)
membership_values = triangular(x, -5, 0, 5) # Example triangular function
# Specify α level
alpha = 0.5
x_alpha_cut = alpha_cut(x, membership_values, alpha)
# Plot the fuzzy set
[Link](figsize=(8, 5))
[Link](x, membership_values, label="Fuzzy Set", color="blue")
[Link](y=alpha, color="red", linestyle="--", label=f"α-cut (α = {alpha})")
[Link](x_alpha_cut, [alpha] * len(x_alpha_cut), color="red", marker="o",
label="α-Cut Elements")
[Link]("α-Cut of a Fuzzy Set")
[Link]("x")
[Link]("Membership Value")
[Link]()
[Link]()
[Link]()
Output
Explanation
1. Define a Membership Function
○ A triangular function is used as an example.
2. Compute the α-Cut
○ The α-cut consists of all x values where membership >= ɑ.
3. Plot the Results
○ The fuzzy set is plotted.
○ A horizontal dashed red line represents the α level.
○ The selected α-cut points are marked in red.
This visualization effectively shows how the α-cut extracts specific values from
the fuzzy set.
Task 3
3. Implement a function that takes two fuzzy sets with triangular membership
function using specific values of the parameters and returns their union and
intersection. Also show the results graphically.
Implementation of Union and Intersection of Two Fuzzy Sets with
Triangular Membership Functions
In fuzzy logic, the union and intersection of two fuzzy sets are computed as
follows:
● Union (max operation): μA∪B(x) = max ( μA(x) , μB(x) )
● Intersection (min operation): μA∩B(x) = min ( μA(x) , μB(x) )
We will:
1. Define two fuzzy sets using triangular membership functions.
2. Compute their union and intersection.
3. Visualize the results.
Python Implementation
import numpy as np
import [Link] as plt
# Define the triangular membership function
def triangular(x, a, b, c):
return [Link]([Link]((x - a) / (b - a), (c - x) / (c - b)), 0)
# Function to compute union and intersection of two fuzzy sets
def fuzzy_union(mu_A, mu_B):
return [Link](mu_A, mu_B)
def fuzzy_intersection(mu_A, mu_B):
return [Link](mu_A, mu_B)
# Generate x values
x = [Link](-10, 10, 400)
# Define two fuzzy sets using triangular membership functions
mu_A = triangular(x, -6, -2, 4) # Fuzzy set A
mu_B = triangular(x, -3, 2, 7) # Fuzzy set B
# Compute union and intersection
mu_union = fuzzy_union(mu_A, mu_B)
mu_intersection = fuzzy_intersection(mu_A, mu_B)
# Plot results
[Link](figsize=(12, 6))
# Plot original fuzzy sets
[Link](1, 2, 1)
[Link](x, mu_A, label="Fuzzy Set A", color="blue")
[Link](x, mu_B, label="Fuzzy Set B", color="green")
plt.fill_between(x, mu_A, alpha=0.3, color="blue")
plt.fill_between(x, mu_B, alpha=0.3, color="green")
[Link]("Fuzzy Sets A and B")
[Link]("x")
[Link]("Membership Value")
[Link]()
[Link]()
# Plot union and intersection
[Link](1, 2, 2)
[Link](x, mu_union, label="Union (A ∪ B)", color="red")
[Link](x, mu_intersection, label="Intersection (A ∩ B)", color="purple")
plt.fill_between(x, mu_union, alpha=0.3, color="red")
plt.fill_between(x, mu_intersection, alpha=0.3, color="purple")
[Link]("Fuzzy Union and Intersection")
[Link]("x")
[Link]("Membership Value")
[Link]()
[Link]()
plt.tight_layout()
[Link]()
Output
Explanation
1. Triangular Membership Functions
○ We define two fuzzy sets A and B with different triangular
membership functions.
2. Union and Intersection
○ Union: Uses the max function.
○ Intersection: Uses the min function.
3. Graphical Representation
○ The first subplot shows the original fuzzy sets.
○ The second subplot visualizes their union and intersection.
Task 4
4. Construct a fuzzy relation matrix from two fuzzy sets. Given two fuzzy sets:
A = { (x1, 0.2) , (x2, 0.5) , (x3, 0.8)}
B = {(y1, 0.3) , (y2, 0.6) , (y3, 0.9)}
Construct the fuzzy relation matrix R using the Cartesian product defined by:
μR(xi, yj) = min ( μA(xi) , μB(yj) )
Constructing a Fuzzy Relation Matrix from Two Fuzzy Sets
Given two fuzzy sets:
A = { (x1, 0.2) , (x2, 0.5) , (x3, 0.8)}
B = {(y1, 0.3) , (y2, 0.6) , (y3, 0.9)}
The fuzzy relation matrix R is constructed using the Cartesian product:
μR(xi, yj) = min ( μA(xi) , μB(yj) )
Python Implementation
import numpy as np
import [Link] as plt
# Define fuzzy sets A and B
A_labels = ["x1", "x2", "x3"]
B_labels = ["y1", "y2", "y3"]
A = [0.2, 0.5, 0.8] # Membership values of A
B = [0.3, 0.6, 0.9] # Membership values of B
# Construct the fuzzy relation matrix using the min operation
R = [Link]((len(A), len(B)))
for i in range(len(A)):
for j in range(len(B)):
R[i, j] = min(A[i], B[j])
# Plot heatmap
[Link](figsize=(6, 5))
[Link](R, cmap="Blues", aspect="auto")
# Annotate values in the heatmap
for i in range(len(A)):
for j in range(len(B)):
[Link](j, i, f"{R[i, j]:.1f}", ha="center", va="center", color="black",
fontsize=12)
# Axis labels
[Link](ticks=[Link](len(B_labels)), labels=B_labels)
[Link](ticks=[Link](len(A_labels)), labels=A_labels)
[Link]("Set B Elements")
[Link]("Set A Elements")
[Link]("Fuzzy Relation Matrix (Heatmap)")
# Show the plot
[Link](label="Membership Value")
[Link]()
Output
Explanation
1. Heatmap Representation
○ The color intensity indicates the membership values in the fuzzy
relation matrix.
○ Darker shades represent higher relationships, and lighter shades
represent lower relationships.
2. Matrix Values
○ Each cell contains μR(xi, yj) = min ( μA(xi) , μB(yj) ).
○ The values are annotated inside the heatmap.
3. Axes Labels
○ Y-axis: Elements from fuzzy set A.
○ X-axis: Elements from fuzzy set B.
Example Output
Output is a heatmap with labels and values like:
y1 y2 y3
x1 0.2 0.2 0.2
x2 0.3 0.5 0.5
x3 0.3 0.6 0.8
Task 5
5. Implement a function to compute the composition of two fuzzy relations using
max-min composition. Given the following fuzzy relations:
R = 0.2 0.5 0.7
0.3 0.6 0.8
0.4 0.7 0.9
S = 0.3 0.6 0.9
0.2 0.5 0.8
0.1 0.4 0.7
Compute the max-min composition T = R ◦ S, where:
μT(xi, zk) = maxj min ( μR(xi, yj) , μS(yj , zk) )
Max-Min Composition of Two Fuzzy Relations
The max-min composition of two fuzzy relations R and S is computed using:
μT(xi, zk) = maxj min ( μR(xi, yj) , μS(yj , zk) )
where:
● R is a 3×3 fuzzy relation.
● S is also a 3×3 fuzzy relation.
● The resulting relation T will also be 3×3 3.
Python Implementation
import numpy as np
import [Link] as plt
# Define fuzzy relations R and S
R = [Link]([
[0.2, 0.5, 0.7],
[0.3, 0.6, 0.8],
[0.4, 0.7, 0.9]
])
S = [Link]([
[0.3, 0.6, 0.9],
[0.2, 0.5, 0.8],
[0.1, 0.4, 0.7]
])
# Compute the correct max-min composition T = R ∘ S
num_rows = [Link][0] # Rows of R
num_cols = [Link][1] # Columns of S
T = [Link]((num_rows, num_cols))
for i in range(num_rows): # Iterate over rows of R
for k in range(num_cols): # Iterate over columns of S
min_values = [min(R[i, j], S[j, k]) for j in range([Link][1])]
T[i, k] = max(min_values) # Take max of min values
# Print the corrected result
print("Corrected Max-Min Composition Matrix T:")
print(T)
# Labels for heatmap
x_labels = ["z1", "z2", "z3"] # Columns of T (Z elements)
y_labels = ["x1", "x2", "x3"] # Rows of T (X elements)
# Plot heatmap
[Link](figsize=(6, 5))
[Link](T, cmap="Blues", aspect="auto")
# Annotate heatmap with values
for i in range([Link][0]):
for j in range([Link][1]):
[Link](j, i, f"{T[i, j]:.1f}", ha="center", va="center", color="black",
fontsize=12)
# Axis labels
[Link](ticks=[Link](len(x_labels)), labels=x_labels)
[Link](ticks=[Link](len(y_labels)), labels=y_labels)
[Link]("Set Z Elements")
[Link]("Set X Elements")
[Link]("Corrected Max-Min Composition Matrix (Heatmap)")
# Show color bar
[Link](label="Membership Value")
[Link]()
Output
Explanation
1. Min Operation:
○ For each (xi,zk), find the minimum of μR(xi,yj) and μS(yj,zk) for all j.
2. Max Operation:
○ After computing the minimum values for all j, take the maximum
among them.
3. Resulting Matrix T:
○ The final matrix represents the strength of the indirect relation
between elements in R and S.
4. Heatmap Representation
○ Darker shades represent higher membership values (stronger
relationships).
○ Lighter shades represent lower membership values (weaker
relationships).
5. Matrix Values
○ Each cell represents the computed max-min composition T(i, k).
6. Axis Labels
○ X-axis: Represents elements from set Z.
○ Y-axis: Represents elements from set X.
The output matrix T represents the max-min composition of R and S.
Task 6
6. Write a Python function to determine the reflexivity, symmetry, and transitivity
of a fuzzy relation. Given a fuzzy relation:
R = 1.0 0.6 0.4
0.6 1.0 0.5
0.4 0.5 1.0
Check if the relation satisfies the following properties:
• Reflexivity: ∀i, μR(xi, xi) = 1
• Symmetry: ∀i, j, μR(xi, xj) = μR(xj, xi)
• Transitivity: μR(xi, xk) ≥ maxj min (μR(xi, xj), μR(xj , xk))
Write a Python function to verify these properties.
Python function for reflexivity, symmetry, and transitivity of a
fuzzy relation matrix
Steps to Check Each Property
1. Reflexivity:
○ Check if all diagonal elements are 1 (i.e., R[i,i] = 1 for all i).
2. Symmetry:
○ Check if R[i,j] = R[j,i] for all pairs (i,j).
3. Transitivity:
○ Check if R[i,k] ≥ maxj min (R[i,j], R[j,k]) for all i, k.
Python Implementation
import numpy as np
import [Link] as plt
import seaborn as sns
def check_fuzzy_properties(R):
n = [Link][0]
# Check Reflexivity
is_reflexive = all(R[i, i] == 1 for i in range(n))
# Check Symmetry
is_symmetric = [Link](R, R.T)
# Check Transitivity
is_transitive = True
for i in range(n):
for k in range(n):
max_min = max(min(R[i, j], R[j, k]) for j in range(n))
if R[i, k] < max_min:
is_transitive = False
break
if not is_transitive:
break
# Print results
print(f"Reflexivity: {'Yes' if is_reflexive else 'No'}")
print(f"Symmetry: {'Yes' if is_symmetric else 'No'}")
print(f"Transitivity: {'Yes' if is_transitive else 'No'}")
return is_reflexive, is_symmetric, is_transitive
def visualize_fuzzy_relation(R, is_reflexive, is_symmetric, is_transitive):
[Link](figsize=(6, 5))
[Link](R, annot=True, cmap="coolwarm", linewidths=0.5, square=True, vmin=0,
vmax=1)
[Link](f"Fuzzy Relation Matrix\nReflexive: {is_reflexive}, Symmetric:
{is_symmetric}, Transitive: {is_transitive}")
[Link]("Elements")
[Link]("Elements")
[Link]()
# Define the fuzzy relation matrix R
R = [Link]([
[1.0, 0.6, 0.4],
[0.6, 1.0, 0.5],
[0.4, 0.5, 1.0]
])
# Check properties
is_reflexive, is_symmetric, is_transitive = check_fuzzy_properties(R)
# Visualize the matrix
visualize_fuzzy_relation(R, is_reflexive, is_symmetric, is_transitive)
Output
Explanation
Reflexive:
● Diagonal elements are all 1, so it satisfies reflexivity.
Symmetric:
● Since R[i,j] = R[j,i] for all i, j, it satisfies symmetry.
Not Transitive:
● For example, checking R(1,3):
R(1,3) = 0.4
R(1,3) = 0.4
maxj min (R(1,j), R(j,3)) = max( min (1,0.4), min (0.6,0.5), min (0.4,1)) =
max (0.4,0.5,0.4) = 0.5
Since 0.4 < 0.5, the matrix is not transitive.
Task 7
7. Let us consider a fuzzy set A with the universe of discourse A = {(x, μA(x)) :
μA(x) = Normal (0, 0.9)}. Find a fuzzy set B with the universe of discourse Y =
[-10, 10] using extension principle for which we have a mapping function as y =
f(x) = x2 − 3 if x > 0 and x if x ≤ 0.
Applying the Extension Principle
This problem involves applying the Extension Principle to determine the fuzzy
set B from fuzzy set A using the given transformation function:
y = f(x) = x2 − 3 if x > 0 and x if x ≤ 0
Steps to Solve
1. Define Fuzzy Set A:
○ Membership function μA(x) = Normal ( 0,0.9) → a Gaussian function.
○ The universe of discourse for A is all real numbers.
○ The Gaussian function: μA(x) = e(-x^(2))/(2(0.9)^(2))
2. Apply the Extension Principle:
○ The mapping function f(x) is applied to all elements of A.
○ The membership function of B is inherited from A based on: μB(y) =
supx:f(x)=y μA(x)
○ This means for each y, we determine the corresponding x values
that map to y and assign the maximum membership from A.
3. Plot Both Sets:
First, plot A as a Gaussian distribution.
○ Then, compute B based on the transformation and plot it.
Python Implementation
Here’s how we can compute B and visualize both fuzzy sets.
import numpy as np
import [Link] as plt
from [Link] import norm
# Define Gaussian Membership Function for A
def gaussian(x, mean=0, sigma=0.9):
return [Link](-((x - mean) ** 2) / (2 * sigma ** 2))
# Define the transformation function f(x)
def transformation(x):
return [Link](x > 0, x**2 - 3, x)
# Define the universe of discourse for A
X = [Link](-3, 3, 500) # From -3 to 3, covering significant probability mass
Y = transformation(X)
# Compute Memberships
mu_A = gaussian(X)
mu_B = np.zeros_like(Y)
# Compute fuzzy set B using extension principle
unique_Y = [Link](-10, 10, 500) # Universe of discourse for B
for i, y in enumerate(unique_Y):
corresponding_x = X[[Link](Y, y, atol=0.1)] # Find x values mapping to y
if corresponding_x.size > 0:
mu_B[i] = [Link](gaussian(corresponding_x)) # Assign max membership from A
# Plot A and B
[Link](figsize=(10, 5))
[Link](1, 2, 1)
[Link](X, mu_A, label="Fuzzy Set A (Gaussian)", color='b')
[Link]("x")
[Link]("Membership")
[Link]("Fuzzy Set A (Gaussian)")
[Link]()
[Link](1, 2, 2)
[Link](unique_Y, mu_B, label="Fuzzy Set B (Transformed)", color='r')
[Link]("y")
[Link]("Membership")
[Link]("Fuzzy Set B (Extension Principle)")
[Link]()
plt.tight_layout()
[Link]()
Explanation of Code
● Step 1: Define A using a Gaussian function centered at 0 with σ = 0.9.
● Step 2: Apply the mapping function f(x) to transform A into B.
● Step 3: For each y, find all x that map to it and assign the highest
membership.
● Step 4: Plot both fuzzy sets for visualization.
Output
1. Left Plot (Fuzzy Set A):
○ A Gaussian curve centered at 0.
2. Right Plot (Fuzzy Set B):
○ The transformed fuzzy set is based on the extension principle.