新网创想网站建设,新征程启航

为企业提供网站建设、域名注册、服务器等服务

python遗传算法求函数极值的实现代码-创新互联

废话不多说,大家直接看代码吧!

成都网站建设哪家好,找创新互联建站!专注于网页设计、重庆网站建设、微信开发、微信小程序、集团企业网站建设等服务项目。核心团队均拥有互联网行业多年经验,服务众多知名企业客户;涵盖的客户类型包括:凿毛机等众多领域,积累了大量丰富的经验,同时也获得了客户的一致称赞!
"""遗传算法实现求函数极大值—Zjh"""
import numpy as np
import random
import matplotlib.pyplot as plt
class Ga():
 """求出二进制编码的长度"""
 def __init__(self):
  self.boundsbegin = -2
  self.boundsend = 3
  precision = 0.0001 # 运算精确度
  self.Bitlength = int(np.log2((self.boundsend - self.boundsbegin)/precision))+1#%染色体长度
  self.popsize = 50# 初始种群大小
  self.Generationmax = 12# 大进化代数
  self.pcrossover = 0.90# 交叉概率
  self.pmutation = 0.2# 变异概率
  self.population=np.random.randint(0,2,size=(self.popsize,self.Bitlength))
 
 """计算出适应度"""
 def fitness(self,population):
  Fitvalue=[]
  cumsump = []
  for i in population:
   x=self.transform2to10(i)#二进制对应的十进制
   xx=self.boundsbegin + x * (self.boundsend - self.boundsbegin) / (pow(2,self.Bitlength)-1)
   s=self.targetfun(xx)
   Fitvalue.append(s)
  fsum=sum(Fitvalue)
  everypopulation=[x/fsum for x in Fitvalue]
  cumsump.append(everypopulation[0])
  everypopulation.remove(everypopulation[0])
  for j in everypopulation:
   p=cumsump[-1]+j
   cumsump.append(p)
  return Fitvalue,cumsump
 """选择两个基因,准备交叉"""
 def select(self,cumsump):
  seln=[]
  for i in range(2):
   j = 1
   r=np.random.uniform(0,1)
   prand =[x-r for x in cumsump]
   while prand[j] < 0:
    j = j + 1
   seln.append(j)
  return seln
 """交叉"""
 def crossover(self, seln, pc):
  d=self.population[seln[1]].copy()
  f=self.population[seln[0]].copy()
  r=np.random.uniform()
  if r                
名称栏目:python遗传算法求函数极值的实现代码-创新互联
分享路径:http://www.wjwzjz.com/article/dgggci.html
在线咨询
服务热线
服务热线:028-86922220
TOP