0% found this document useful (0 votes)
13 views21 pages

Fuzzy Set

The document describes implementing genetic algorithm operations on binary encoded numbers. It defines functions for binary encoding/decoding numbers, calculating fitness values, and performing crossover. It generates an initial population, calculates their fitness values, and stores in a dataframe. Uniform crossover is performed on the population to create offspring, which are then decoded. The offspring are evaluated and stored in a new dataframe. This process is repeated to create a second generation of offspring.

Uploaded by

Mohshin Khan
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)
13 views21 pages

Fuzzy Set

The document describes implementing genetic algorithm operations on binary encoded numbers. It defines functions for binary encoding/decoding numbers, calculating fitness values, and performing crossover. It generates an initial population, calculates their fitness values, and stores in a dataframe. Uniform crossover is performed on the population to create offspring, which are then decoded. The offspring are evaluated and stored in a new dataframe. This process is repeated to create a second generation of offspring.

Uploaded by

Mohshin Khan
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/ 21

fuzzy-set

December 16, 2023

[14]: #declaration of fuzzy set


a,b,c=[],[],[]
fuzzy_sets=[a,b,c]

[15]: #user input to fuzzy set


for i in range(3):
print("Insert for fuzzy set number : ",i+1)
for j in range(3):
print('Membership value of x{}'.format(j+1))
x=float(input())
fuzzy_sets[i].append(('x{}'.format(j+1),x))

Insert for fuzzy set number : 1


Membership value of x1
0.3
Membership value of x2
0.4
Membership value of x3
0.6
Insert for fuzzy set number : 2
Membership value of x1
0.3
Membership value of x2
0.7
Membership value of x3
0.9
Insert for fuzzy set number : 3
Membership value of x1
0.1
Membership value of x2
0.4
Membership value of x3
0.6

[16]: fuzzy_sets

1
[16]: [[('x1', 0.3), ('x2', 0.4), ('x3', 0.6)],
[('x1', 0.3), ('x2', 0.7), ('x3', 0.9)],
[('x1', 0.1), ('x2', 0.4), ('x3', 0.6)]]

[30]: #performing union operation


result1=[]
for j in range(3):
result1.append(('x{}'.
↪format(j+1),max(fuzzy_sets[0][j][1],fuzzy_sets[1][j][1],fuzzy_sets[2][j][1])))

[31]: result1

[31]: [('x1', 0.3), ('x2', 0.7), ('x3', 0.9)]

[32]: #performing intersection operation


result2=[]
for j in range(3):
result2.append(('x{}'.
↪format(j+1),min(fuzzy_sets[0][j][1],fuzzy_sets[1][j][1],fuzzy_sets[2][j][1])))

[33]: result2

[33]: [('x1', 0.1), ('x2', 0.4), ('x3', 0.6)]

[ ]:

[113]: #Implementing Triangular Membership Function


#let fuzzy set be
a=[(1,0),(4,1),(6,0)]
a.sort()
#importing inbuilt plotting function
import matplotlib.pyplot as plt

[114]: x=[]
u=[]
for i in a:
x.append(i[0])
u.append(i[1])

[115]: plt.plot(x,u)
plt.show()

2
[116]: def triangular(x,fuzzy):
if fuzzy[1][1]!=1 and fuzzy[0][1]!=0 and fuzzy[2][0]!=0:
return 'not triangular'
if x<fuzzy[0][0]:
return 0
elif x>fuzzy[2][0]:
return 0
elif x>=fuzzy[0][0] and x<=fuzzy[1][0]:
val=(x-fuzzy[0][0])/(fuzzy[1][0]-fuzzy[0][0])
return val
elif x>=fuzzy[1][0] and x<=fuzzy[2][0]:
val=(fuzzy[2][0]-x)/(fuzzy[2][0]-fuzzy[1][0])
return val

[121]: i=float(input('Enter number: '))


val=triangular(i,a)

Enter number: 3

[122]: print('Resultant value is: ',val)

Resultant value is: 0.6666666666666666

[123]: plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()

3
[ ]:

[124]: #Implementing Trapezoidal Membership Function


#let fuzzy set be
a=[(1,0),(4,1),(6,1),(7,0)]
a.sort()

[125]: x=[]
u=[]
for i in a:
x.append(i[0])
u.append(i[1])

[126]: plt.plot(x,u)
plt.show()

4
[127]: def trapezoidal(x,fuzzy):
if fuzzy[1][1]!=1 and fuzzy[0][1]!=0 and fuzzy[2][0]!=1 and fuzzy[3][0]!=0:
return 'not trapezoidal'
if x<fuzzy[0][0]:
return 0
elif x>fuzzy[3][0]:
return 0
elif x>=fuzzy[0][0] and x<=fuzzy[1][0]:
val=(x-fuzzy[0][0])/(fuzzy[1][0]-fuzzy[0][0])
return val
elif x>=fuzzy[2][0] and x<=fuzzy[3][0]:
val=(fuzzy[3][0]-x)/(fuzzy[3][0]-fuzzy[2][0])
return val
elif x>=fuzzy[1][0] and x<=fuzzy[2][0]:
return 1

[130]: i=float(input('Enter number: '))


val=trapezoidal(i,a)

Enter number: 6.4

[131]: print('Resultant value is: ',val)

Resultant value is: 0.5999999999999996

5
[132]: plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()

[147]: #Gaussian
c=int(input('Center Value: '))
s=int(input('Width Value: '))
m=int(input('Fuzzification Value: '))

Center Value: 5
Width Value: 2
Fuzzification Value: 2

[148]: import math

[150]: fuzzy_set=[]
for i in range(c*2+1):
m_value=math.exp(-(1/2)*(abs((i-c)/s))**m)
fuzzy_set.append((i,m_value))

[153]: x=[]
u=[]
for i in fuzzy_set:
x.append(i[0])
u.append(i[1])

6
[154]: plt.plot(x,u,color='black')
plt.show()

[ ]:

[155]: def gaussian(x,c,s,m):


m_value=math.exp(-(1/2)*(abs((x-c)/s))**m)
return m_value

[156]: i=float(input('Enter number: '))


val=gaussian(i,c,s,m)

Enter number: 3.4

[157]: print('Resultant value is: ',val)

Resultant value is: 0.7261490370736908

[158]: plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()

7
[134]: a=fuzzy_sets[0]
b=fuzzy_sets[1]
print(a,b)

[('x1', 0.3), ('x2', 0.4), ('x3', 0.6)] [('x1', 0.3), ('x2', 0.7), ('x3', 0.9)]

[138]: def fuzzy_operation(a,b):


result=[]
for j in range(3):
result.append(('x{}'.format(j+1),(a[j][1]*b[j][1])/(a[j][1]+b[j][1])))
return result

[139]: print(fuzzy_operation(a,b))

[('x1', 0.15), ('x2', 0.2545454545454545), ('x3', 0.36000000000000004)]

[ ]:

[ ]:

[ ]:

[ ]:

[ ]:

8
[ ]:

[ ]:

[ ]:

[ ]: 9

[400]: import pandas as pd


df=pd.DataFrame()

[401]: global size


size=5
def iteration(x,df):
def fitness_fun(x):
fitness_func=2*x**2+3*x+1
return fitness_func
def decimal_to_binary(x):
ch=bin(x).replace('0b','')
if len(ch)<size:
ch='0'+ch
return ch

#encoding
string=[]
initial_population=[]
fitness=[]
for i in range(len(x)):
string.append('x{}'.format(i+1))
initial_population.append(decimal_to_binary(x[i]))
fitness.append(fitness_fun(x[i]))
total_val_fitness=sum(fitness)
avg_val_fitness=total_val_fitness/len(x)
def probability_ExpectedCount(x,y):
return x/y
probability=[]
expected_count=[]
for i in fitness:
probability.append(probability_ExpectedCount(i,total_val_fitness))
expected_count.append(probability_ExpectedCount(i,avg_val_fitness))
df['String']=string
df['Initial_Population']=initial_population
df['x']=x
df['Fitness']=fitness
df['Probability']=probability
df['Expected_Count']=expected_count
df['Actual_Count']=round(df['Expected_Count'])

9
return df

[402]: #given
x=[9,11,13,15]
df=iteration(x,df)

[403]: df

[403]: String Initial_Population x Fitness Probability Expected_Count \


0 x1 01001 9 190 0.141791 0.567164
1 x2 01011 11 276 0.205970 0.823881
2 x3 01101 13 378 0.282090 1.128358
3 x4 01111 15 496 0.370149 1.480597

Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0

[513]: def binary_to_decimal(x):


return int(x,2)

[514]: import random

[515]: #Uniform Crossover


#x1,x4 x2,x3
def crossover(x,y):
x=list(x)
y=list(y)
for i in range(len(x)):
#tossing coin
if i%2==0:
pass
else:
t=x[i]
x[i]=y[i]
y[i]=t
x=''.join(x)
y=''.join(y)
return (x,y)
offsprings=[]
offsprings.
↪extend(crossover(df['Initial_Population'][2],df['Initial_Population'][3]))

offsprings.
↪extend(crossover(df['Initial_Population'][1],df['Initial_Population'][0]))

10
[516]: offsprings

[516]: ['01111', '01101', '01001', '01011']

[517]: off_x=[]
for i in offsprings:
off_x.append(binary_to_decimal(i))

[518]: off_x

[518]: [15, 13, 9, 11]

[519]: df1=pd.DataFrame()

[520]: df1=iteration(off_x,df1)

[521]: df1

[521]: String Initial_Population x Fitness Probability Expected_Count \


0 x1 01111 15 496 0.370149 1.480597
1 x2 01101 13 378 0.282090 1.128358
2 x3 01001 9 190 0.141791 0.567164
3 x4 01011 11 276 0.205970 0.823881

Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0

[522]: offsprings2=[]
offsprings2.
↪extend(crossover(df1['Initial_Population'][2],df1['Initial_Population'][3]))

offsprings2.
↪extend(crossover(df1['Initial_Population'][1],df1['Initial_Population'][0]))

off_x2=[]
for i in offsprings2:
off_x2.append(binary_to_decimal(i))

[523]: df2=pd.DataFrame()
df2=iteration(off_x2,df2)
df2

[523]: String Initial_Population x Fitness Probability Expected_Count \


0 x1 01011 11 276 0.205970 0.823881
1 x2 01001 9 190 0.141791 0.567164
2 x3 01111 15 496 0.370149 1.480597

11
3 x4 01101 13 378 0.282090 1.128358

Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0

[ ]:

[ ]:

[ ]: 15

[496]: def iteration(x):


def fitness_fun(x):

↪fitness_func=(int(x[0])+int(x[1]))-(int(x[2])+int(x[3]))+(int(x[4])+int(x[5]))-(int(x[6])+in

return fitness_func
#encoding
string=[]
fitness=[]
for i in range(len(x)):
string.append('x{}'.format(i+1))
fitness.append(fitness_fun(x[i]))
total_val_fitness=sum(fitness)
val1=zip(string,x,fitness)
val=list(val1)
val=sorted(val,key=lambda x:x[2])[::-1]
return val

[497]: x=['65413532','87126601','23921285','41852094']

[498]: val1=iteration(x)

[499]: val1

[499]: [('x2', '87126601', 23),


('x1', '65413532', 9),
('x3', '23921285', -16),
('x4', '41852094', -19)]

[500]: #cross-over with best fitted middle point


best1=val1[0][1]
best2=val1[1][1]

12
[501]: off_1=best1[:int(len(best1)/2)]+best2[int(len(best2)/2):]
off_2=best2[:int(len(best2)/2)]+best1[int(len(best1)/2):]

[502]: best3=val1[2][1]

[503]: #cross-over with 2nd and 3rdbest fitted from 2nd and 6th position
off_3=best2[:2]+best3[2:6]+best2[6:]
off_4=best3[:2]+best2[2:6]+best3[6:]

[504]: off_5,off_6=crossover(best1,best3)

[505]: offspring=[off_1,off_2,off_3,off_4,off_5,off_6]

[506]: new_gen=iteration(offspring)

[508]: new_gen

[508]: [('x2', '65416601', 17),


('x1', '87123532', 15),
('x5', '83126205', 11),
('x3', '65921232', -2),
('x6', '27921681', -4),
('x4', '23413585', -5)]

[ ]:

[ ]:

[ ]:

[861]: import pandas as pd


df=pd.DataFrame(columns=['a','b','c','d','e','f'])

[862]: def tsp_d(df,iteration_df):


distance=[]
print(df)
for i in iteration_df['paths']:
add=0
for j in range(len(i)-1):
add+=df.loc[i[j]][i[j+1]]
distance.append(add)
iteration_df['distance']=distance
print(iteration_df)
return iteration_df

[863]: def tsp(iteration_df):


total_fitness=sum(iteration_df['distance'])

13
iteration_df['relative_fitness']=total_fitness/iteration_df['distance']
total_relative_fitness=sum(iteration_df['relative_fitness'])
iteration_df['probability']=iteration_df['relative_fitness']/
↪total_relative_fitness

cdf=[]
s=0
for i in iteration_df['probability']:
s+=i
cdf.append(s)
iteration_df['cdf']=cdf

[864]: #city table


df['a']=[0,5,6,8,2,1]
df['b']=[5,0,6,3,2,3]
df['c']=[1,6,0,4,4,5]
df['d']=[4,6,8,0,2,1]
df['e']=[3,6,8,2,0,3]
df['f']=[2,5,6,7,2,0]

[865]: df.index=['a','b','c','d','e','f']

[866]: df=df.transpose()

[867]: df

[867]: a b c d e f
a 0 5 6 8 2 1
b 5 0 6 3 2 3
c 1 6 0 4 4 5
d 4 6 8 0 2 1
e 3 6 8 2 0 3
f 2 5 6 7 2 0

[868]: #a->a
import random as ran

[869]: paths=[]
for i in range(4):
path=['a']
roots=['b','c','d','e','f']
for j in range(5):
v=ran.choices(roots)
roots.remove(v[0])
path.append(v[0])
path.append('a')
paths.append(path)

14
[870]: paths

[870]: [['a', 'f', 'c', 'b', 'e', 'd', 'a'],


['a', 'f', 'b', 'e', 'c', 'd', 'a'],
['a', 'c', 'e', 'd', 'b', 'f', 'a'],
['a', 'b', 'c', 'e', 'd', 'f', 'a']]

[871]: df

[871]: a b c d e f
a 0 5 6 8 2 1
b 5 0 6 3 2 3
c 1 6 0 4 4 5
d 4 6 8 0 2 1
e 3 6 8 2 0 3
f 2 5 6 7 2 0

[872]: iteration_df=pd.DataFrame()

[873]: iteration_df['paths']=paths

[874]: iteration_df

[874]: paths
0 [a, f, c, b, e, d, a]
1 [a, f, b, e, c, d, a]
2 [a, c, e, d, b, f, a]
3 [a, b, c, e, d, f, a]

[875]: iteration_df=tsp_d(df,iteration_df)

a b c d e f
a 0 5 6 8 2 1
b 5 0 6 3 2 3
c 1 6 0 4 4 5
d 4 6 8 0 2 1
e 3 6 8 2 0 3
f 2 5 6 7 2 0
paths distance
0 [a, f, c, b, e, d, a] 21
1 [a, f, b, e, c, d, a] 24
2 [a, c, e, d, b, f, a] 23
3 [a, b, c, e, d, f, a] 20

[876]: iteration_df

15
[876]: paths distance
0 [a, f, c, b, e, d, a] 21
1 [a, f, b, e, c, d, a] 24
2 [a, c, e, d, b, f, a] 23
3 [a, b, c, e, d, f, a] 20

[877]: df1=iteration_df.copy()

[878]: tsp(iteration_df)

[879]: iteration_df

[879]: paths distance relative_fitness probability cdf


0 [a, f, c, b, e, d, a] 21 4.190476 0.260549 0.260549
1 [a, f, b, e, c, d, a] 24 3.666667 0.227981 0.488530
2 [a, c, e, d, b, f, a] 23 3.826087 0.237893 0.726423
3 [a, b, c, e, d, f, a] 20 4.400000 0.273577 1.000000

[ ]:

[ ]:

[ ]:

[880]: #parents
parents=[]
j=-1
while len(parents)<2:
random_number=ran.random()
for row,i in enumerate(iteration_df['cdf']):
if i>random_number:
if j!=row:
parents.append(iteration_df.iloc[row].paths)
if j==-1:
j=row
break

[881]: parents

[881]: [['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'b', 'c', 'e', 'd', 'f', 'a']]

[882]: def unique(x,y):


if x[:2]!=y[:2]:
t=y[0]
y[0]=x[0]
for i in range(1,len(y)):
if y[i]==y[0]:

16
y[i]=t
y[1]=x[1]
for i in range(2,len(y)):
if y[i]==y[1]:
y[i]=t
x=['a']+x+['a']
y=['a']+y+['a']
return [x,y]

[883]: parent_ready=unique(parents[0][1:-1],parents[1][1:-1])

[884]: parent_ready

[884]: [['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'f', 'b', 'e', 'd', 'b', 'a']]

[885]: parents

[885]: [['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'b', 'c', 'e', 'd', 'f', 'a']]

[886]: #swap
off1=[]
off1.append(parent_ready[0][:2]+parent_ready[1][2:])
off1.append(parent_ready[1][:2]+parent_ready[0][2:])

[887]: off1

[887]: [['a', 'f', 'b', 'e', 'd', 'b', 'a'], ['a', 'f', 'b', 'e', 'c', 'd', 'a']]

[888]: off_distance=[]
for i in off1:
add=0
for j in range(len(i)-1):
add+=df.loc[i[j]][i[j+1]]
off_distance.append(add)

[889]: off_distance

[889]: [21, 24]

[890]: for d in range(len(off_distance)):


for row,i in enumerate(iteration_df['distance']):
if off_distance[d]<i:
df1.iloc[row]=[off1[d],off_distance[d]]
break

E:\anaconda\lib\site-packages\numpy\core\fromnumeric.py:3156:
VisibleDeprecationWarning: Creating an ndarray from ragged nested sequences

17
(which is a list-or-tuple of lists-or-tuples-or ndarrays with different lengths
or shapes) is deprecated. If you meant to do this, you must specify
'dtype=object' when creating the ndarray.
return asarray(a).ndim

[891]: iteration_df

[891]: paths distance relative_fitness probability cdf


0 [a, f, c, b, e, d, a] 21 4.190476 0.260549 0.260549
1 [a, f, b, e, c, d, a] 24 3.666667 0.227981 0.488530
2 [a, c, e, d, b, f, a] 23 3.826087 0.237893 0.726423
3 [a, b, c, e, d, f, a] 20 4.400000 0.273577 1.000000

[892]: df1

[892]: paths distance


0 [a, f, c, b, e, d, a] 21
1 [a, f, b, e, d, b, a] 21
2 [a, c, e, d, b, f, a] 23
3 [a, b, c, e, d, f, a] 20

[893]: iteration_df=df1.copy()

[894]: tsp(iteration_df)

[895]: iteration_df

[895]: paths distance relative_fitness probability cdf


0 [a, f, c, b, e, d, a] 21 4.047619 0.252331 0.252331
1 [a, f, b, e, d, b, a] 21 4.047619 0.252331 0.504663
2 [a, c, e, d, b, f, a] 23 3.695652 0.230389 0.735052
3 [a, b, c, e, d, f, a] 20 4.250000 0.264948 1.000000

[ ]:

[ ]:

[ ]:

[897]: import random as ran

13
[ ]: 3 ta plane
5 ta crew a,b,c,d,e
a b c 000
c d e 100
a d e 011

18
a b c 100
d b c 011
d a e 100
b a e 011
b d c 100

[896]: a b c 1 1 1 0 0 3
c d e 0 0 2 1 1 4
a d e 1 0 0 2 2 5
a b c 2 1 1 0 0 4
d b c 0 0 2 1 1 4
d a e 1 0 0 2 2 5
b a e 2 1 1 0 0 4
b d c 0 0 2 1 1 4

[2210]: def fitness(crew,work_days_count):


for i in crew:
work_days_count[i]+=1
penalty = sum(max(0, work_days_count[crew] - MAX_WORK_DAYS) for crew in␣
↪work_days_count)

return 1 / (1 + penalty)

[2211]: def crossover(parent1, parent2):


crossover_point = random.randint(1, NUM_DAYS - 1)
child = parent1[:crossover_point] + parent2[crossover_point:]
if len(set(child))!=len(child):
for i in set(child):
dup=0
for j in child:
if i==j:
dup+=1
if dup==2:
x=list(work_count.values())
found=False
while not found:
for k in range(5):
if list(work_count.keys())[k] not in child and␣
↪work_count[list(work_count.keys())[k]]<=1:

child[child.index(j)]= list(work_count.
↪keys())[k]

found=True

return child

[2222]: def crew_fun(crew,work_count,generation):


for _ in range(generation):
fit_score=[]

19
for i in combi:
work_days_count=work_count.copy()
fit_score.append(fitness(i,work_days_count))
parents = [combi[i] for i in range(len(fit_score)) if ran.random() <␣
↪fit_score[i]]

try:
parent1, parent2 = random.sample(parents, 2)
child = crossover(parent1, parent2)
min1=min(fit_score)
combi.remove(combi[fit_score.index(min1)])
combi.insert(fit_score.index(min1),child)
fit_score.remove(min1)

except:
pass
fit_score=[]
for i in combi:
work_days_count=work_count.copy()
fit_score.append(fitness(i,work_days_count))
best_solution = combi[fit_score.index(max(fit_score))]
combi.remove(best_solution)
new_combi=[]
complete=[]
al=['a','b','c','d','e']
for i in best_solution:
work_count[i]+=1
for i in al:
if i not in best_solution:
work_count[i]=0
for i in work_count:
if work_count[i]>=2:
complete.append(i)
for i in al:
if i not in complete:
new_combi.append(i)
if len(new_combi)>3:
new_combi=new_combi[:3]
combi.append(new_combi)
return best_solution

[2227]: global work_count


work_count={'a':0,'b':0,'c':0,'d':0,'e':0}
POPULATION_SIZE = 8

[2234]: combi=[]
for _ in range(8):

20
crew=['a','b','c','d','e']
c=[]
for _ in range(3):
s=ran.choice(crew)
crew.remove(s[0])
c.append(s[0])
combi.append(c)

[2235]: generation=20
print(crew_fun(combi,work_count,generation))

['a', 'b', 'e']

[2236]: work_count

[2236]: {'a': 2, 'b': 1, 'c': 0, 'd': 0, 'e': 1}

[ ]:

21

You might also like