0% found this document useful (0 votes)
236 views15 pages

Prog

Uploaded by

aman kumar soni
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)
236 views15 pages

Prog

Uploaded by

aman kumar soni
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/ 15

import numpy

"""

The y=target is to maximize this equation ASAP:

y = w1x1+w2x2+w3x3+w4x4+w5x5+6wx6

where (x1,x2,x3,x4,x5,x6)=(4,-2,3.5,5,-11,-4.7)

What are the best values for the 6 weights w1 to w6?

We are going to use the genetic algorithm for the best possible values after a number of
generations.

"""

# Inputs of the equation.

equation_inputs = [4,-2,3.5,5,-11,-4.7]

# Number of the weights we are looking to optimize.

num_weights = len(equation_inputs)

"""

Genetic algorithm parameters:

Mating pool size

Population size

"""

sol_per_pop = 8

num_parents_mating = 4

# Defining the population size.

pop_size = (sol_per_pop,num_weights) # The population will have sol_per_pop chromosome where


each chromosome has num_weights genes.

#Creating the initial population.

new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)

print("new_population",new_population)
best_outputs = []

num_generations = 1000

for generation in range(num_generations):

# print("Generation : ", generation)

# Measuring the fitness of each chromosome in the population.

def cal_pop_fitness(equation_inputs, pop):

print("pop",pop)

# Calculating the fitness value of each solution in the current population.

# The fitness function calulates the sum of products between each input and its corresponding
weight.

fitness = numpy.sum(pop*equation_inputs, axis=1)

return fitness

print("Fitness")

print(fitness)

best_outputs.append(numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))

# The best result in the current iteration.

#print("Best result : ", numpy.max(numpy.sum(new_population*equation_inputs, axis=1)))

# Selecting the best parents in the population for mating.

def select_mating_pool(pop, fitness, num_parents):

# Selecting the best individuals in the current generation as parents for producing the offspring of
the next generation.

parents = numpy.empty((num_parents, pop.shape[1]))

for parent_num in range(num_parents):

max_fitness_idx = numpy.where(fitness == numpy.max(fitness))

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)

# Generating next generation using crossover.

def crossover(parents, offspring_size):

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]):

# Index of the first parent to mate.

parent1_idx = k%parents.shape[0]

# Index of the second parent to mate.

parent2_idx = (k+1)%parents.shape[0]

# The new offspring will have its first half of its genes taken from the first parent.

offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point]

# The new offspring will have its second half of its genes taken from the second parent.

offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:]

return offspring

print("Crossover")

print(offspring_crossover)

# Adding some variations to the offspring using mutation.

def mutation(offspring_crossover, num_mutations=1):

mutations_counter = numpy.uint8(offspring_crossover.shape[1] / num_mutations)

# Mutation changes a number of genes as defined by the num_mutations argument. The changes
are random.

for idx in range(offspring_crossover.shape[0]):


gene_idx = mutations_counter - 1

for mutation_num in range(num_mutations):

# The random value to be added to the gene.

random_value = numpy.random.uniform(-1.0, 1.0, 1)

offspring_crossover[idx, gene_idx] = offspring_crossover[idx, gene_idx] + random_value

gene_idx = gene_idx + mutations_counter

return offspring_crossover

print("Mutation")

print(offspring_mutation)

# Creating the new population based on the parents and offspring.

new_population[0:parents.shape[0], :] = parents

new_population[parents.shape[0]:, :] = offspring_mutation

# Getting the best solution after iterating finishing all generations.

#At first, the fitness is calculated for each solution in the final generation.

fitness = cal_pop_fitness(equation_inputs, new_population)

# Then return the index of that solution corresponding to the best fitness.

best_match_idx = numpy.where(fitness == numpy.max(fitness))

print("Best solution : ", new_population[best_match_idx, :])

print("Best solution fitness : ", fitness[best_match_idx])

import matplotlib.pyplot as plt

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))

print("New Population: ")

for i in new_population:

print(i)

print(type(new_population[0]))

from sklearn import datasets

dataset=datasets.load_breast_cancer()

from sklearn.svm import SVC

from sklearn.model_selection import train_test_split

x=dataset.data

y=dataset.target

xtrain,xtest,ytrain,ytest=train_test_split(x,y,test_size=0.30,random_state=0)

from sklearn.metrics import accuracy_score

fitness=np.empty(6)

for i in range(6):

print("features Selected: ")

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

import matplotlib.pyplot as plt

import skfuzzy as fuzz

#generate trapezoidal membership function on range(0,1)

x=np.arange(0,5.05,0.1)

mfx=fuzz.trapmf(x,[2,2.5,3,4.5])

#defuzzify this membership function five ways

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)

#Collect into for vertical lines

labels=['centroid','bisector','mean of maximum','first of maximum','last of maximum']

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')

for xv,y,label,color in zip(xvals,ymax,labels,colors):

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]))

for parent_num in range(num_parents):

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

def selection (num_parents,fitness,new_pop):

best_parents=[]

for i in range(num_parents):

best_index=numpy.argmax(fitness)#argmax=returning the value of best_index

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)):

print("Enter Degree of Membership for :",U[i])

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])

from sklearn import datasets

dataset=datasets.load_breast_cancer()

print(dataset.data.shape)

print(dataset.target.shape)

print(dataset.target_names)

from sklearn.svm import SVC

from sklearn.model_selection import train_test_split

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)

from sklearn.metrics import accuracy_score

acc=accuracy_score(predicted,ytest)

print(acc)

You might also like