python实现遗传算法求解函数极值问题
import random
import numpy as np
class chromosome:
def __init__(self,chrom,decode,fitness):
self.chrom = chrom
self.decode = decode
self.fitness = fitness
def decode(chom):
chom.reverse()
x = 0
for i in range(len(chom)):
x = x + chom[i]*(pow(2,i))
x1 = x * (10/pow(2,10)-1)
return x1
def fitness(x):
return x + 10 * np.sin(5 * x) + 7 * np.cos(4 * x)
import random
def initPopulation(N):
pop = []
for i in range(N):
L=[random.randint(0,1) for i in range(10)]
this_decode = decode(L)
this_fitness = fitness(this_decode)
pop.append(chromosome(L,this_decode,this_fitness))
return pop
def crossover(pop):
odd = pop[0::2]
even = pop[1::2]
new_pop = []
a, b = np.random.choice(len(pop[0].chrom), 2)
for i in range(len(odd)):
a1 = odd[i].chrom
a2 = even[i].chrom
if a<b:
a1_1 = a1[0:a] + a2[a:b-1] + a1[b-1:]
a2_1 = a2[0:a] + a1[a:b-1] + a2[b-1:]
elif a>b:
a1_1 = a1[0:b] + a2[b:a-1] + a1[a-1:]
a2_1 = a2[0:b] + a1[b:a-1] + a2[a-1:]
elif a == b:
a1_1 = a1
a2_1 = a2
this_decode1 = decode(a1_1)
this_fitness1 = fitness(this_decode1)
new_pop.append(chromosome(a1_1,this_decode1,this_fitness1))
this_decode2 = decode(a2_1)
this_fitness2 = fitness(this_decode2)
new_pop.append(chromosome(a2_1,this_decode2,this_fitness2))
return new_pop
def mutation(pop):
new_pop = []
a = np.random.choice(len(pop[0].chrom), 1)
for i in range(len(pop)):
a1 = pop[i].chrom
if a1[a[0]] == 1:
a1[a[0]] = a1[a[0]]-1
else:
a1[a[0]] = a1[a[0]]+1
this_decode = decode(a1)
this_fitness = fitness(this_decode)
new_pop.append(chromosome(a1,this_decode,this_fitness))
return new_pop
'''
def Asort(POP):
for i in range(len(POP)):
for j in range(len(POP)-1):
if POP[i].fitness>POP[j].fitness:
POP[i],POP[j] = POP[j],POP[i]
return POP
'''
def Asort(POP):
for i in range(len(POP)):
for j in range(len(POP)-1):
if POP[i].fitness<POP[j].fitness:
POP[i],POP[j] = POP[j],POP[i]
return POP
def implement():
N = 20
iter_N = 100
POP = initPopulation(N)
POP_all = []
Pc = 0.8
Pm = 0.1
for i in range(iter_N):
POP_all = POP_all+POP
if np.random.random() < Pc:
POP = crossover(POP)
if np.random.random() < Pm:
POP = mutation(POP)
POP_all = POP_all + POP
POP_end = Asort(POP_all)
POP = POP_end[0:N]
POP_all = []
return POP
result = implement()
result
for i in range(len(result)):
print(result[i].decode)
print(result[i].fitness)
import matplotlib.pyplot as plt
def func(x):
return x + 10 * np.sin(5 * x) + 7 * np.cos(4 * x)
x = np.linspace(-10, 10, 10000)
y = func(x)
scatter_x = np.array([ind.decode for ind in result])
scatter_y = np.array([ind.fitness for ind in result])
plt.plot(x, y)
plt.scatter(scatter_x, scatter_y, c='r')
plt.show()
最后结果: