0% found this document useful (0 votes)
169 views29 pages

Fuzzy Logic Lab Final

Fuzzy set theory allows for partial membership in a set rather than crisp binary membership. A fuzzy set is represented by a membership function that assigns a value between 0 and 1 to each element, indicating the degree of membership. Common membership functions include linear, triangular, trapezoidal, and Gaussian functions. Fuzzy logic uses fuzzy set theory and linguistic rules to map inputs to outputs. It involves fuzzifying inputs, applying fuzzy rules, aggregating outputs, and defuzzifying to obtain a crisp output. Python libraries can be used to implement fuzzy systems and visualize membership functions.

Uploaded by

Manish LACHHETA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
169 views29 pages

Fuzzy Logic Lab Final

Fuzzy set theory allows for partial membership in a set rather than crisp binary membership. A fuzzy set is represented by a membership function that assigns a value between 0 and 1 to each element, indicating the degree of membership. Common membership functions include linear, triangular, trapezoidal, and Gaussian functions. Fuzzy logic uses fuzzy set theory and linguistic rules to map inputs to outputs. It involves fuzzifying inputs, applying fuzzy rules, aggregating outputs, and defuzzifying to obtain a crisp output. Python libraries can be used to implement fuzzy systems and visualize membership functions.

Uploaded by

Manish LACHHETA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Ques 1 Overview of Fuzzy Set

What is Fuzzy Set ?

Fuzzy refers to something that is unclear or vague . Hence,


Fuzzy Set is a Set where every key is associated with value,
which is between 0 to 1 based on the certainty .This value is
often called as degree of membership. Fuzzy Set is denoted
with a Tilde Sign on top of the normal Set notation.
Operations on Fuzzy Set with Code :

1. Union :
Consider 2 Fuzzy Sets denoted by A and B, then let’s
consider Y be the Union of them, then for every member of A
and B, Y will be:

degree_of_membership(Y)= max(degree_of_membership(A),
degree_of_membership(B))

EXAMPLE :

# Example to Demonstrate the


# Union of Two Fuzzy Sets
A = dict()
B = dict()
Y = dict()

A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}


B = {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5}

print('The First Fuzzy Set is :', A)


print('The Second Fuzzy Set is :', B)

for A_key, B_key in zip(A, B):


A_value = A[A_key]
B_value = B[B_key]

if A_value > B_value:


Y[A_key] = A_value
else:
Y[B_key] = B_value

print('Fuzzy Set Union is :', Y)

Output
The First Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
The Second Fuzzy Set is : {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}
Fuzzy Set Union is : {'a': 0.9, 'b': 0.9, 'c': 0.6, 'd': 0.6}

2. Intersection :
Consider 2 Fuzzy Sets denoted by A and B, then let’s
consider Y be the Intersection of them, then for every
member of A and B, Y will be:
degree_of_membership(Y)= min(degree_of_membership(A),
degree_of_membership(B))

EXAMPLE :

# Example to Demonstrate
# Intersection of Two Fuzzy Sets
A = dict()
B = dict()
Y = dict()

A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}


B = {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5}

print('The First Fuzzy Set is :', A)


print('The Second Fuzzy Set is :', B)

for A_key, B_key in zip(A, B):


A_value = A[A_key]
B_value = B[B_key]

if A_value < B_value:


Y[A_key] = A_value
else:
Y[B_key] = B_value
print('Fuzzy Set Intersection is :', Y)

Output
The First Fuzzy Set is : {'a': 0.2, 'b': 0.3, 'c': 0.6, 'd': 0.6}
The Second Fuzzy Set is : {'a': 0.9, 'b': 0.9, 'c': 0.4, 'd': 0.5}
Fuzzy Set Intersection is : {'a': 0.2, 'b': 0.3, 'c': 0.4, 'd': 0.5}

3. Difference : Consider 2 Fuzzy Sets denoted by A and B,


then let’s consider Y be the Intersection of them, then for
every member of A and B, Y will be:
degree_of_membership(Y)= min(degree_of_membership(A), 1-
degree_of_membership(B))

EXAMPLE :

# Example to Demonstrate the


# Difference Between Two Fuzzy Sets
A = dict()
B = dict()
Y = dict()

A = {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}


B = {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5}

print('The First Fuzzy Set is :', A)


print('The Second Fuzzy Set is :', B)

for A_key, B_key in zip(A, B):


A_value = A[A_key]
B_value = B[B_key]
B_value = 1 - B_value
if A_value < B_value:
Y[A_key] = A_value
else:
Y[B_key] = B_value

print('Fuzzy Set Difference is :', Y)

Output
The First Fuzzy Set is : {"a": 0.2, "b": 0.3, "c": 0.6, "d": 0.6}
The Second Fuzzy Set is : {"a": 0.9, "b": 0.9, "c": 0.4, "d": 0.5}
Fuzzy Set Difference is : {"a": 0.1, "b": 0.1, "c": 0.6, "d": 0.5}

Class Fuzzy Sets

class FzSets:

def __init__(self):
self.A = dict()
self.B = dict()

self.complement_A = dict()
self.complement_B = dict()
self.union_AB = dict()
self.intersection_AB = dict()
self.differenceAB = dict()
self.differenceBA = dict()

self.change_union = False
self.change_intersection = False
self.change_complement = False

def __init__(self,A,nA,B,nB):
self.A = A
self.B = B
self.Aname = nA
self.Bname = nB
self.complement_A = dict()
self.complement_B = dict()
self.union_AB = dict()
self.intersection_AB = dict()
self.differenceAB = dict()
self.differenceBA = dict()

self.change_union = False
self.change_intersection = False
self.change_complement = False

def unionOp(self):
if self.change_union:
print('Result of UNION operation :',self.union_AB)
else:

#unionSet = set(self.A.keys()).union(self.B.keys())
sa = set(self.A.keys())
sb = set(self.B.keys())
intersectionSet = set(self.A.keys()).intersection(self.B.keys())

for i in intersectionSet:
self.union_AB[i] = max(self.A[i],self.B[i])
for i in sa-intersectionSet:
self.union_AB[i] = self.A[i]
for i in sb-intersectionSet:
self.union_AB[i] = self.B[i]

print('Result of UNION operation :',self.union_AB)

def intersectionOp(self):
if self.change_intersection:
print('Result of INTERSECTION operation :\n\t\t',self.intersection_AB)
else:

#unionSet = set(self.A.keys()).union(self.B.keys())
sa = set(self.A.keys())
sb = set(self.B.keys())
intersectionSet = set(self.A.keys()).intersection(self.B.keys())

for i in intersectionSet:
self.intersection_AB[i] = min(self.A[i],self.B[i])
for i in sa-intersectionSet:
self.intersection_AB[i] = 0.0
for i in sb-intersectionSet:
self.intersection_AB[i] = 0.0

print('Result of INTERSECTION operation :\n\t\t',self.intersection_AB)


self.change_intersection = True

def complementOp(self):
if self.change_complement:
print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_A)
print('Result of COMPLEMENT on ',self.Bname,' operation :',self.complement_B)
else:

for i in self.A:
self.complement_A[i] = 1 - A[i]
for i in self.B:
self.complement_B[i] = 1 - B[i]

print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_A)


print('Result of COMPLEMENT on ',self.Aname,' operation :',self.complement_B)

self.change_complement = True

def __oneMinustwo(self,L,R):
minus_d = dict()
Rcomp = dict()
for i in R:
Rcomp[i] = 1 - R[i]
sa = set(L.keys())
sb = set(R.keys())
intersectionSet = sa.intersection(sb) # min( A , complement(B) )
# l - r OR a - b
for i in intersectionSet:
minus_d[i] = min(L[i],Rcomp[i])
for i in sa-intersectionSet:
minus_d[i] = 0.0
for i in sb-intersectionSet:
minus_d[i] = 0.0

return minus_d

def AminusB(self):
self.differenceAB = self.__oneMinustwo(self.A,self.B)
print('Result of DIFFERENCE ',self.Aname,' | ',self.Bname,' operation
:\n\t\t',self.differenceAB)

def BminusA(self):
self.differenceBA = self.__oneMinustwo(self.B,self.A)
print('Result of DIFFERENCE ',self.Bname,' | ',self.Aname,' operation
:\n\t\t',self.differenceBA)

def change_Setz(self,A,B):
self.A = A
self.B = B

print('\nSet ',self.Aname,' :',self.A)


print('Set ',self.Bname,' :',self.B,end='')

self.change_union = True
self.change_intersection = True
self.change_complement = True
print('\t\t\t Cache Reset')

def displaySets(self):
print('\nSet ',self.Aname,' :',self.A)
print('Set ',self.Bname,' :' ,self.B)
Ques 2. Implementation of Membership
functions
Membership functions
Membership functions for fuzzy logic, encoded and plotted in python.

The following membership functions showed are:

• Pending function
• Lineal function
• Triangle function
• Trapezoidal function
• Generalized bell function
• Gaussian function

membershipFunctions.py
import numpy as np
import skfuzzy as fuzz

def getAxisValues(axis,stepSize):
return np.arange(axis['xmin'], axis['xmax'], stepSize)
pass

def linearFuncBon(points, xrange):


values = []
for x in xrange:
if x<points['a']:
values.append(0)
elif (x>=points['a'] and x<points['b']):
values.append((x-points['a'])/(points['b'] - points['a']))
elif x>=points['b']:
values.append(1)
return values
pass

def triangleFuncBon(points, xrange):


values = []
for x in xrange:
if x <= points['a']:
values.append(0)
elif (x >= points['a'] and x <= points['b']):
values.append((x-points['a'])/(points['b'] - points['a']))
elif x >= points['b'] and x <= points['c']:
values.append((points['c']-x)/(points['c'] - points['b']))
elif x >= points['c']:
values.append(0)
return values
pass

def trapezoidalFuncBon(points, xrange):


values = []
for x in xrange:
if x <= points['a']:
values.append(0)
elif (x >= points['a'] and x <= points['b']):
values.append((x-points['a'])/(points['b'] - points['a']))
elif x >= points['b'] and x <= points['c']:
values.append(1)
elif (x >= points['c'] and x <= points['d']):
values.append((points['d']-x)/(points['d'] - points['c']))
elif x >= points['d']:
values.append(0)
return values
pass

def generalizedBellFuncBon(generalizedBellData, xrange):


return fuzz.gbellmf(xrange,
generalizedBellData['width'],generalizedBellData['slope'],generalizedBellData['center'])
pass

def gaussianFuncBon(gaussianData, xrange):


return fuzz.gaussmf(xrange, gaussianData['mean'], gaussianData['sigma'])

Ques 3
Fuzzy Logic Implementation
with Python

Fuzzy logic originated with the theory of fuzzy sets introduced by


mathematician Lotfi Zadeh in 1965. Fuzzy logic arises by assigning
degrees of truth to propositions. The standard set of accuracy values
(degrees) is in the range of [0,1] real units. Here 0 represents
"completely false", 1
represents "totally true" and other values refer to partial truth
(intermediate truth).
There are two types of fuzzy inference systems:

• Mamdani systems
• Sugeno
systems
Fuzzy rule-based systems evaluate linguistic if-then rules using
fuzzification, inference and composition. They often produce fuzzy
results that need to be converted to crisp output. Fuzzy results are
made clear by defuzzification. Also there are some defuzzification
methods;

• Center of Sums(COS)

• Center of Gravity (COG)

• Centroid of Area (COA)

• Bisector of Area (BOA)

• Weighted Average

• Maxima

Our system consists of 24 rule bases and has a MISO (Multi Input
Single Output) system structure consisting of 6 inputs - single outputs.
Input values of the person; age, blood pressure, cholesterol, blood
sugar, LDL and HDL values. The output value consists of the “risk”
Mamdani Inference Engine and the centroid of
area defuzzification method. We coded this project with Python and
used numpy, skfuzzy, matplotlib.

First of all we need define inputs and output variable ranges with
numpy.
Rule Base
We read global heart health articles for try to choose true rules. By the
way please not forget, these rules are just our choises.

Here is our rule base;

And rule base numpy defines;


Dataset
We use just age, trestbps, chol, fbs, ldl and hdl values from this dataset
for our FIS.
Inputs Membership Functions
We should prepare membership functions with linguistic
qualifiers(Low, middle, high etc.) ranges. We use skfuzzy.membership
trapmf function for this step.
Here is membership functions and diagrams;
Output Membership Function
Fuzzification
We use skfuzzy library interpolation function for every linguistic
qualifiers fuzzification.

Mamdani Inference Engine


To compute the output of Mamdani FIS given the inputs, one must go
through six steps:

1. determining a set of fuzzy rules

2. fuzzifying the inputs using the input membership functions,

3. combining the fuzzified inputs according to the fuzzy rules to


establish a rule strength,

4. finding the consequence of the rule by combining the rule


strength and the output membership function,

5. combining the consequences to get an output distribution,


6. defuzzifying the output distribution (this step is only if a crisp
output (class) is needed).

If we back our project, we coded the mamdani inference engine using


rules as follows.

Defuzzification (CoA)
Time to make crisp and sense something. We choose centroid of area
method for defuzzification.

Outputs of Model
The risk of heart disease is calculated by applying the necessary
procedures to the information received from the user. I tried our model
with these data and It calculated Coroner Heart Diagnosis value is
4.386973. So in this example, this people has no risk for Coroner Heart
Disease.
Here is output diagrams;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy