Fuzzy Set
Fuzzy Set
a,b,c=[],[],[]
fuzzy_sets=[a,b,c]
fuzzy_sets
result1
result2
x=[]
u=[]
for i in a:
x.append(i[0])
u.append(i[1])
plt.plot(x,u)
plt.show()
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
Enter number: 3
plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()
x=[]
u=[]
for i in a:
x.append(i[0])
u.append(i[1])
plt.plot(x,u)
plt.show()
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
i=float(input('Enter number: '))
val=trapezoidal(i,a)
plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()
#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
import math
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))
x=[]
u=[]
for i in fuzzy_set:
x.append(i[0])
u.append(i[1])
plt.plot(x,u,color='black')
plt.show()
def gaussian(x,c,s,m):
m_value=math.exp(-(1/2)*(abs((x-c)/s))**m)
return m_value
plt.plot(x,u,color='black')
plt.scatter(i,val,color='red')
plt.show()
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)]
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
print(fuzzy_operation(a,b))
import pandas as pd
df=pd.DataFrame()
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'])
return df
#given
x=[9,11,13,15]
df=iteration(x,df)
df
Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0
def binary_to_decimal(x):
return int(x,2)
import random
#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]))
offsprings
off_x
df1=pd.DataFrame()
df1=iteration(off_x,df1)
df1
Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0
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))
df2=pd.DataFrame()
df2=iteration(off_x2,df2)
df2
Actual_Count
0 1.0
1 1.0
2 1.0
3 1.0
15
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])+int(x[7]))
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
x=['65413532','87126601','23921285','41852094']
val1=iteration(x)
val1
off_1=best1[:int(len(best1)/2)]+best2[int(len(best2)/2):]
off_2=best2[:int(len(best2)/2)]+best1[int(len(best1)/2):]
best3=val1[2][1]
#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:]
off_5,off_6=crossover(best1,best3)
offspring=[off_1,off_2,off_3,off_4,off_5,off_6]
new_gen=iteration(offspring)
new_gen
import pandas as pd
df=pd.DataFrame(columns=['a','b','c','d','e','f'])
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
def tsp(iteration_df):
total_fitness=sum(iteration_df['distance'])
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_rel
ative_fitness
cdf=[]
s=0
for i in iteration_df['probability']:
s+=i
cdf.append(s)
iteration_df['cdf']=cdf
#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]
df.index=['a','b','c','d','e','f']
df=df.transpose()
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
#a->a
import random as ran
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)
paths
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
iteration_df=pd.DataFrame()
iteration_df['paths']=paths
iteration_df
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]
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
iteration_df
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
df1=iteration_df.copy()
tsp(iteration_df)
iteration_df
#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
parents
[['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'b', 'c', 'e', 'd', 'f',
'a']]
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]:
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]
parent_ready=unique(parents[0][1:-1],parents[1][1:-1])
parent_ready
[['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'f', 'b', 'e', 'd', 'b',
'a']]
parents
[['a', 'f', 'b', 'e', 'c', 'd', 'a'], ['a', 'b', 'c', 'e', 'd', 'f',
'a']]
#swap
off1=[]
off1.append(parent_ready[0][:2]+parent_ready[1][2:])
off1.append(parent_ready[1][:2]+parent_ready[0][2:])
off1
[['a', 'f', 'b', 'e', 'd', 'b', 'a'], ['a', 'f', 'b', 'e', 'c', 'd',
'a']]
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)
off_distance
[21, 24]
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 (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
iteration_df
df1
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
iteration_df=df1.copy()
tsp(iteration_df)
iteration_df
13
3 ta plane
5 ta crew a,b,c,d,e
a b c 000
c d e 100
a d e 011
a b c 100
d b c 011
d a e 100
b a e 011
b d c 100
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
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)
return child
def crew_fun(crew,work_count,generation):
for _ in range(generation):
fit_score=[]
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
global work_count
work_count={'a':0,'b':0,'c':0,'d':0,'e':0}
POPULATION_SIZE = 8
combi=[]
for _ in range(8):
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)
generation=20
print(crew_fun(combi,work_count,generation))
['a', 'b', 'e']
work_count