遗传算法Python实现

    xiaoxiao2023-11-05  151

    遗传算法Python实现

    瞎BB代码导入库以及参数设置目标函数生成C行R列的值在0-1的数组混沌函数二进制转十进制个体按值从大到小排序交叉变异适应度函数主函数

    瞎BB

    代码

    导入库以及参数设置

    import pandas as pd import numpy as np import matplotlib.pyplot as plt import math import random #range of variable bounds = np.array([-2,2]) #begin of variable boundsbegin = bounds[0] #end of variable boundsend = bounds[1] precision = 0.0001 #calc the BitLength BitLength = math.ceil(np.log2((boundsend - boundsbegin) / precision)) #init popsize = 100 Generationmax = 100 pmut = 0.09

    目标函数

    def targetfun(x): value = 200 * math.exp(-0.05 * x) * math.sin(x) return value

    生成C行R列的值在0-1的数组

    def random_random(C,R): rand=[] for i in range(C*R): rand.append(random.random()) rand=np.array(rand) return rand.reshape(C,R)

    混沌函数

    def chaos(size): chaos_cro = np.zeros(size) chaos_cro[0] = random.random() for j in range(1,size): chaos_cro[j] = 4 * chaos_cro[j - 1] * (1 - chaos_cro[j - 1]) return chaos_cro[-1]

    二进制转十进制

    def transform2to10(sample): BitLength = len(sample) x=sample[-1] for i in range(1,BitLength): x=x+sample[-i-1]*np.power(2,i) return x

    个体按值从大到小排序

    def rank(population): popsize = population.shape[0] BitLength = population.shape[1] fitvalue = np.zeros(popsize).reshape(popsize,1) for i in range(popsize): x = transform2to10(population[i]) #tansform to range of variable xx=boundsbegin + x * (boundsend - boundsbegin) / (np.power(boundsend,BitLength)-1) fitvalue[i,0]=targetfun(xx) #make fitvalue(j)<fitvalue(j+1) res = np.concatenate((population,fitvalue),axis = 1) res=pd.DataFrame(res) population = res.sort_values(by=BitLength) population = np.array(population) population = population[:,0:BitLength] return population

    交叉变异

    def cro_mut_improve(population,rate_mut): #seln:two individuals popsize = population.shape[0] BitLength = population.shape[1] population = rank(population) #crossover pop=popsize chaos_cro = np.zeros(BitLength) if popsize % 2 == 1: pop = popsize - 1 for i in range(0,pop,2): chaos_cro = chaos(BitLength) chao = math.floor(chaos_cro * BitLength) temp = population[i,chao] population[i,chao] = population[i+1,chao] population[i + 1,chao] = temp #mutation by = np.array([]) n = len(by) #generate random individuals to mutate while n == 0: by = random_random(1,popsize)<rate_mut for i in by[0]: if i: n+=1 num_mut = n for k in range(popsize): if by[0,k] == True: chaos_mut = np.zeros(BitLength) chaos_mut[0] = random.random() for t in range(1,BitLength): chaos_mut[t] = 4 * chaos_mut[t - 1] * (1 - chaos_mut[t - 1]) position = np.floor(BitLength * random_random(1,2)) position.astype(np.int16) population[k,int(position[0,0])] = np.round(chaos(BitLength)) population[k,int(position[0,1])] = np.round(chaos(BitLength)) return population

    适应度函数

    def fitness(population): #population=pd.DataFrame(population) popsize = population.shape[0] BitLength = population.shape[1] cumsump = np.zeros(popsize).reshape(1,popsize) fitvalue = np.zeros(popsize).reshape(1,popsize) for i in range(popsize): x = transform2to10(population[i]) #tansform to range of variable xx = boundsbegin + x * (boundsend - boundsbegin) / (np.power(boundsend,BitLength) - 1) fitvalue[0,i] = targetfun(xx) #ensure fitvalue>0 fitvalue = fitvalue+230 fsum = fitvalue.sum(1)[0] Pperpopulation = fitvalue / fsum cumsump[0] = Pperpopulation[0] for i in range(1,popsize): cumsump[0,i] = cumsump[0,i-1] + Pperpopulation[0,i] res = np.concatenate((fitvalue,cumsump),axis = 0) return res

    主函数

    ymax=np.zeros(Generationmax+1) ymean=np.zeros(Generationmax+1) xmax=np.zeros(Generationmax+1) #generate random population population = np.round(random_random(popsize,BitLength)) #calc fitness return fitvalue and sum of probability res=fitness(population) fitvalue = res[0] cumsump = res[1] #main code Generation=1 while Generation<Generationmax+1: population=cro_mut_improve(population,pmut) res=fitness(population) fitvalue = res[0] cumsump = res[1] fmax = np.max(fitvalue) for i in range(popsize): if fitvalue[i]==fmax: nmax = i break fmean = np.mean(fitvalue,axis = 0) ymax[Generation] = fmax ymean[Generation] = fmean x = transform2to10(population[nmax]) xx = boundsbegin + x * (boundsend-boundsbegin) / (pow(boundsend,BitLength)-1) xmax[Generation] = xx Generation += 1 #Generation=Generation-1; Bestpopulation = np.max(xmax) BestValue = targetfun(Bestpopulation) print(Bestpopulation) print(BestValue) x=[] y=[] for i in range(400): t=-2+0.01*i x.append(t) y.append(targetfun(t)) plt.scatter(x, y)
    最新回复(0)