Prog
Prog
"""
y = w1x1+w2x2+w3x3+w4x4+w5x5+6wx6
where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7)
We are going to use the genetic algorithm for the best possible values after a number of
generations.
"""
equation_inputs = [4,-2,3.5,5,-11,-4.7]
num_weights = len(equation_inputs)
"""
Population size
"""
sol_per_pop = 8
num_parents_mating = 4
print("new_population",new_population)
best_outputs = []
num_generations = 1000
print("pop",pop)
# The fitness function calulates the sum of products between each input and its corresponding
weight.
return fitness
print("Fitness")
print(fitness)
best_outputs.append(numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))
# Selecting the best individuals in the current generation as parents for producing the offspring of
the next generation.
max_fitness_idx = max_fitness_idx[0][0]
parents[parent_num, :] = pop[max_fitness_idx, :]
fitness[max_fitness_idx] = -99999999999
return parents
print("Parents")
print(parents)
offspring = numpy.empty(offspring_size)
# The point at which crossover takes place between two parents. Usually, it is at the center.
crossover_point = numpy.uint8(offspring_size[1]/2)
for k in range(offspring_size[0]):
parent1_idx = k%parents.shape[0]
parent2_idx = (k+1)%parents.shape[0]
# The new offspring will have its first half of its genes taken from the first parent.
# The new offspring will have its second half of its genes taken from the second parent.
return offspring
print("Crossover")
print(offspring_crossover)
# Mutation changes a number of genes as defined by the num_mutations argument. The changes
are random.
return offspring_crossover
print("Mutation")
print(offspring_mutation)
new_population[0:parents.shape[0], :] = parents
new_population[parents.shape[0]:, :] = offspring_mutation
#At first, the fitness is calculated for each solution in the final generation.
# Then return the index of that solution corresponding to the best fitness.
plt.plot(best_outputs)
plt.xlabel("Iteration")
plt.ylabel("Fitness")
plt.show()
import numpy as np
import random
sol_per_pop=6
num_features=20
total_pop=(sol_per_pop,num_features)
new_population=[]
for i in range(sol_per_pop):
new_population.append(random.sample(range(0,29),num_features))
for i in new_population:
print(i)
print(type(new_population[0]))
dataset=datasets.load_breast_cancer()
x=dataset.data
y=dataset.target
xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.30,random_state=0)
fitness=np.empty(6)
for i in range(6):
print(set(new_population[i]))
sample=xtrain[:,new_population[i]]
svc=SVC(kernel='rbf',C=0.1)
svc.fit(sample,ytrain)
predicted=svc.predict(xtest[:,new_population[i]])
fitness[i]=accuracy_score(predicted,ytest)
print(fitness)
num_parents=4
best_parents=[]
for i in range(4):
index=np.argmax(fitness)
best_parents.append(new_population[index])
fitness[index]=0
print("\n",best_parents)
cross_points=num_features//2
offspring_size=4
offspring=np.empty([4,10])
for i in range(4):
offspring[i,0:cross_point]=best_parents[i,0:cross_point]
if(i+1==4):
offspring[i,cross_point:]=best_parents[0,cross_points]
else:
offspring[i,cross_point:]=best_parents[i+1,cross_point]
import numpy as np
x=np.random.uniform(low=0,high=10,size=(50,2))
print (x)
import pandas as pd
x= pd.DataFrame(x)
x.to_csv('train.csv')
import numpy as np
x=np.arange(0,5.05,0.1)
mfx=fuzz.trapmf(x,[2,2.5,3,4.5])
defuzz_centroid=fuzz.defuzz(x,mfx,'centroid')
defuzz_bisector=fuzz.defuzz(x,mfx,'bisector')
defuzz_mom=fuzz.defuzz(x,mfx,'mom')
defuzz_fom=fuzz.defuzz(x,mfx,'som')
defuzz_lom=fuzz.defuzz(x,mfx,'lom')
print(defuzz_centroid)
print(defuzz_bisector)
print(defuzz_mom)
print(defuzz_fom)
print(defuzz_lom)
xvals=[defuzz_centroid,defuzz_bisector,defuzz_mom,defuzz_fom,defuzz_lom]
colors=['r','b','g','c','m']
ymax=[fuzz.interp_membership(x,mfx,i)for i in xvals]
print(ymax)
plt.figure(figsize=(8,5))
plt.plot(x,mfx,'k')
plt.vlines(xv,0,y,label=label,color=color)
plt.ylabel('Fuzzy Membership')
plt.xlabel('Universe variable(arb)')
plt.ylim(-0.1,1.1)
plt.legend(loc=2)
plt.show()
import numpy
import ann_NG
def create_pop(ps,pl):
pop=np.random.uniform(low=-5,high=5,size=(ps,pl))
return pop
def cal_fitness(pop,x,y):
fitness=[]
for i in range(pop.shape[0]):
error=ann_NG.ann_output(x,y,pop[i])
mse=ann_NG.mse_error(error)
fitness.append(1/mse)
return fitness
def sel_parent(pop,fitness,num_parents):
parents=np.empty((num_parents,pop.shape[1]))
ma_fitness_idx=np.argmax(fitness)
parents[parents_num,:]=pop[max_fitness_idx,:]
fitness[max_fitness_idx]=-99999999999
return parents
#cross-over
def crossover_parents(best_parents,offspring_size):
crossover_point=offspring_size[1]//2
offspring=numpy.empty(offspring_size)
for i in range(offspring_size[0]):
offspring[i,0:crossover_point]=best_parents[i,0:crossover_point]
if(i+1==offspring_size[0]):
offspring[i,crossover_point:]=best_parents[0,crossover_point]
else:
offspring[i,crossover_point]=best_parents[i+1,crossover_point]
return (np.array(offspring))
offspring=crossover(best_parents,offspring_size)
print("after crossover")
print(offspring)
import numpy as np
def thresh(x):
if x>=0:
return 1
else:
return 0
def create_ANN(x,y):
il=x.shape[l]+1
ol=1
hl=0
iw=np.random.uniform(low=-5,high=5,size=(il,))
hw=0
return iw
def ann_output(x,y,iw):
error=[]
for i in range(x.shape[0]):
n=iw[0]+np.dot(iw[1:],x[])
import numpy as np
import ann_NG
import ga_NG
x=[[0,0],[0,1][1,0],[1,1]]
y=[0,1,1,1]
weights=ann_NG.create_ANN(X,Y)
pop_size=8
pop_length=len(weights)
for i in range(1000):
pop=ga_NG.create_pop(pop_size,pop_length)
print("Population",pop)
fitness=ga_NG.cal_fitness(pop,x,y)
print("Fitness:",fitness)
if np.any(np.isinf(fitness)):
break
parent=ga_NG.sel_parent(pop,fitness,num_parents=4)
child=ga_NG.crossover_parents(parents,offspring_size=(4,3))
child_mut=ga_NG.mutation_child(child,num_mutations=3)
pop[0:parents.shape[0],:]=parents
pop[parents.shape[0],:=child_mut]
import numpy
eq_inputs=[4,-2,3.5,5,-11,4.7]
pop_size=8
total_pop=(pop_size,len(eq_inputs))
new_pop=numpy.random.uniform(low=-4.0,high=4.0,size=total_pop)
print("New Population:",new_pop)
def cal_fitness(eq_inputs,new_pop):
fitness=numpy.sum(eq_inputs*new_pop,axis=1)
return(fitness)
fitness=cal_fitness(eq_inputs,new_pop)
print("Fitness values",fitness)
import numpy
#initial population
eq_inputs=[4,-2,3.5,5,-11,4.7]
pop_size=8
total_pop=(pop_size,len(eq_inputs))
new_pop=numpy.random.uniform(low=-4.0,high=4.0,size=total_pop)
print("New Population:",new_pop)
#fitness
def cal_fitness(eq_inputs,new_pop):
fitness=numpy.sum(eq_inputs*new_pop,axis=1)
return(fitness)
fitness=cal_fitness(eq_inputs,new_pop)
print("Fitness values",fitness)
#selection
num_parents=4
best_parents=[]
for i in range(num_parents):
best_parents.append(new_pop[best_index])
fitness[best_index]=-999999
return(best_parents)
best_parents=selection(num_parents,fitness,new_pop)
print("Selcted Parents:",best_parents)
#cross over
offspring_size=(4,len(eq_inputs))
def crossover(best_parents,offspring_size):
cross_point=len(eq_inputs)//2
offspring=numpy.empty(offspring_size)
for i in range(offspring_size[0]):
offspring[i,0:cross_point]=best_parents[i,0:cross_point]
if(i+1==offspring_size[0]):
offspring[i,cross_point:]=best_parents[0,cross_point]
else:
offspring[i,cross_point]=best_parents[i+1,cross_point]
return (np.array(offspring))
offspring=crossover(best_parents,offspring_size)
print("after crossover")
print(offspring)
#mutation
num_mutations=2
def mutation(offspring,num_mutations):
for i in range(num_mutations):
pop_sel=numpy.random.randint(0,offspring.shape[0])
gene_sel=np.random.randint(0,offspring.shape[1])
value=np.random.uniform(low=-4.0,high=4.0,size=(1,1))
offspring[pop_sel,gene_sel]=value
print(pop.sle,gene_sel,value)
return(offspring)
mut_offspring=mutation(offspring_crossover,num_mutations)
print("After Mutation:",mut_offspring)
U=[3,4,5,6,7]
set_A=[]
set_B=[]
for i in range(len(U)):
set_A.append(float(input()))
set_C=[]
for i in range(len(U)):
if set_A[i]<set_B[i]:
set_C.append(set_A[i])
else:
set_C.append(ser_B[i])
dataset=datasets.load_breast_cancer()
print(dataset.data.shape)
print(dataset.target.shape)
print(dataset.target_names)
x=dataset.data
y=dataset.target
xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.30,random_state=0)
print(xtrain.shape)
print(xtest.shape)
print(ytrain.shape)
print(ytest.shape)
svc=SVC(kernel='rbf',C=0.1)
svc.fit(xtrain,ytrain)
predicted=svc.predict(xtest)
acc=accuracy_score(predicted,ytest)
print(acc)