遗传算法

import numpy as np
import pandas as pd
import math


#将二进制转化为十进制 x∈[0,10]
def b2d(b):
t = 0
for j in range(len(b)):
t += b[j] * (math.pow(2, j))
t = t * 10 / 1023
return t
#随机编码
def geneEncoding(pop_size, chrom_length):
pop = [[]]
for i in range(pop_size):
temp = []
for j in range(chrom_length):
temp.append(np.random.randint(0, 2))
pop.append(temp)
return pop[1:]


# 用遗传算法求函数最大值:
# f(x)=10*sin(5x)+7*cos(4x) x∈[0,10]

 

import math
# 将种群的二进制基因转化为十进制(0,1023)
def decodechrom(pop):
temp = []
for i in range(len(pop)):
t = 0
for j in range(10):
t += pop[i][j] * (math.pow(2, j))
# print('t',t)
temp.append(t)
# print('temp',temp)
return temp


# 计算目标函数值
def calobjvalue(pop):
temp1 = [];
objvalue = [];
temp1 = decodechrom(pop)

for i in range(len(temp1)):
x = temp1[i] * 10 / 1023 #(0,1023)转化为 (0,10)
# print('x',x)
objvalue.append(10 * math.sin(5 * x) + 7 * math.cos(4 * x))
# print('objvalue',objvalue)
return objvalue #目标函数值objvalue[m] 与个体基因 pop[m] 对应

# 转化为适应值,目标函数值越大越好,负值淘汰
def calfitvalue(objvalue):
fitvalue = []
temp = 0.0
Cmin = 0
for i in range(len(objvalue)):
if(objvalue[i] + Cmin > 0):
temp = Cmin + objvalue[i]

else:
temp = 0.0
fitvalue.append(temp)

return fitvalue

# 找出适应函数值中最大值,和对应的个体
def best(pop, fitvalue):
px = len(pop)
bestindividual = []
bestfit = fitvalue[0]
for i in range(1,px):
if(fitvalue[i] > bestfit):
bestfit = fitvalue[i]
bestindividual = pop[i]

return [bestindividual, bestfit]

def sum(fitvalue):
total = 0
for i in range(len(fitvalue)):
total += fitvalue[i]
return total


#计算累计概率
def cumsum(fitvalue):
for i in range(len(fitvalue)):
t = 0
j = 0
while (j <= i):
t += fitvalue[j]
j = j + 1
fitvalue[i] = t


# 自然选择(轮盘赌算法)
def selection(pop, fitvalue):
newfitvalue = []#选中概率
totalfit = sum(fitvalue)
if totalfit:
for i in range(len(fitvalue)):
newfitvalue.append(fitvalue[i] / totalfit)
cumsum(newfitvalue)
ms = []
poplen = len(pop)

for i in range(poplen):
ms.append(np.random.random()) # random() 方法返回随机生成的一个实数,它在[0,1)范围内。
ms.sort()

fitin = 0
newin = 0
newpop = pop
while newin < poplen:
if (ms[newin] < newfitvalue[fitin]):#随机概率小于选中概率
newpop[newin] = pop[fitin]
newin = newin + 1
else:
fitin = fitin + 1
pop = newpop
return pop

 

#个体间交叉,实现基因交换
def crossover(pop, pc):#pc为杂交概率
poplen = len(pop)
for i in range(poplen - 1):#[0,1,2]
if(np.random.random() < pc):
cpoint = np.random.randint(0,len(pop[0]))

temp1 = []
temp2 = []
temp1.extend(pop[i][0 : cpoint])

temp1.extend(pop[i+1][cpoint : len(pop[i])])

temp2.extend(pop[i+1][0 : cpoint])

temp2.extend(pop[i][cpoint : len(pop[i])])

pop[i] = temp1
pop[i+1] = temp2

 

# 基因突变
def mutation(pop, pm): #pm突变概率
px = len(pop) #4
py = len(pop[0]) #10
for i in range(px):
r=np.random.random()
if ( r< pm):
mpoint = np.random.randint(0, py - 1)
# print('mpoint',mpoint)
if (pop[i][mpoint] == 1):
pop[i][mpoint] = 0
else:
pop[i][mpoint] = 1


popsize =4 # 种群的大小
chromlength = 10 # 基因片段的长度 ---10只股票
pc = 0.6 # 两个个体交叉的概率
pm = 0.001 # 基因突变的概率
results = [[]]
bestindividual = []
bestfit = 0
fitvalue = []
tempop = [[]]
pop=geneEncoding(4, 10)


for i in range(3): #繁殖100代
objvalue = calobjvalue(pop) #计算目标函数值,二进制转化为十进制,计算目标值
print('目标函数值:objvalue',objvalue)

fitvalue = calfitvalue(objvalue) #计算个体的适应值
print('个体的适应值:fitvalue',fitvalue)
#
[bestindividual, bestfit] = best(pop, fitvalue) #选出最好的个体和最好的函数值
print('最好的个体:bestindividual',bestindividual)
print('最好的函数值:bestfit',bestfit)
#
results.append([bestfit,b2d(bestindividual)]) #每次繁殖,将最好的结果记录下来
print('最好的结果:results',results)
#
selection(pop, fitvalue) #自然选择,淘汰掉一部分适应性低的个体
crossover(pop, pc) #交叉繁殖
mutation(pop, pc) #基因突变
print('newpop',pop)
results.sort()
print('>>>>',results)
print('<<<<',results[-1]) #打印函数最大值和对应的x

 

posted on 2018-09-15 20:36  happygril3  阅读(321)  评论(0)    收藏  举报

导航