Python实现遗传算法(二进制编码)求函数最优值方式


Posted in Python onFebruary 11, 2020

目标函数

Python实现遗传算法(二进制编码)求函数最优值方式

编码方式

本程序采用的是二进制编码精确到小数点后五位,经过计算可知对于 Python实现遗传算法(二进制编码)求函数最优值方式 其编码长度为18,对于 Python实现遗传算法(二进制编码)求函数最优值方式 其编码长度为15,因此每个基于的长度为33。

参数设置

Python实现遗传算法(二进制编码)求函数最优值方式

算法步骤

设计的程序主要分为以下步骤:1、参数设置;2、种群初始化;3、用轮盘赌方法选择其中一半较好的个体作为父代;4、交叉和变异;5、更新最优解;6、对最有个体进行自学习操作;7结果输出。其算法流程图为:

Python实现遗传算法(二进制编码)求函数最优值方式

算法结果

由程序输出可知其最终优化结果为38.85029, Python实现遗传算法(二进制编码)求函数最优值方式

输出基因编码为[1 1 0 0 1 0 1 1 1 1 1 1 1 0 1 1 1 1 0 1 0 1 1 0 1 0 0 1 0 1 1 1 1]。

代码

import numpy as np
import random
import math
import copy

class Ind():
 def __init__(self):
  self.fitness = 0
  self.x = np.zeros(33)
  self.place = 0
  self.x1 = 0
  self.x2 = 0

def Cal_fit(x, upper, lower): #计算适应度值函数
 Temp1 = 0
 for i in range(18):
  Temp1 += x[i] * math.pow(2, i)
 Temp2 = 0
 for i in range(18, 33, 1):
  Temp2 += math.pow(2, i - 18) * x[i]
 x1 = lower[0] + Temp1 * (upper[0] - lower[0])/(math.pow(2, 18) - 1)
 x2 = lower[1] + Temp2 * (upper[1] - lower[1])/(math.pow(2, 15) - 1)
 if x1 > upper[0]:
  x1 = random.uniform(lower[0], upper[0])
 if x2 > upper[1]:
  x2 = random.uniform(lower[1], upper[1])
 return 21.5 + x1 * math.sin(4 * math.pi * (x1)) + x2 * math.sin(20 * math.pi * x2)
def Init(G, upper, lower, Pop): #初始化函数
 for i in range(Pop):
  for j in range(33):
   G[i].x[j] = random.randint(0, 1)
  G[i].fitness = Cal_fit(G[i].x, upper, lower)
  G[i].place = i
def Find_Best(G, Pop):
 Temp = copy.deepcopy(G[0])
 for i in range(1, Pop, 1):
  if G[i].fitness > Temp.fitness:
   Temp = copy.deepcopy(G[i])
 return Temp

def Selection(G, Gparent, Pop, Ppool): #选择函数
 fit_sum = np.zeros(Pop)
 fit_sum[0] = G[0].fitness
 for i in range(1, Pop, 1):
  fit_sum[i] = G[i].fitness + fit_sum[i - 1]
 fit_sum = fit_sum/fit_sum.max()
 for i in range(Ppool):
  rate = random.random()
  Gparent[i] = copy.deepcopy(G[np.where(fit_sum > rate)[0][0]])

def Cross_and_Mutation(Gparent, Gchild, Pc, Pm, upper, lower, Pop, Ppool): #交叉和变异
 for i in range(Ppool):
  place = random.sample([_ for _ in range(Ppool)], 2)
  parent1 = copy.deepcopy(Gparent[place[0]])
  parent2 = copy.deepcopy(Gparent[place[1]])
  parent3 = copy.deepcopy(parent2)
  if random.random() < Pc:
   num = random.sample([_ for _ in range(1, 32, 1)], 2)
   num.sort()
   if random.random() < 0.5:
    for j in range(num[0], num[1], 1):
     parent2.x[j] = parent1.x[j]
   else:
    for j in range(0, num[0], 1):
     parent2.x[j] = parent1.x[j]
    for j in range(num[1], 33, 1):
     parent2.x[j] = parent1.x[j]
   num = random.sample([_ for _ in range(1, 32, 1)], 2)
   num.sort()
   num.sort()
   if random.random() < 0.5:
    for j in range(num[0], num[1], 1):
     parent1.x[j] = parent3.x[j]
   else:
    for j in range(0, num[0], 1):
     parent1.x[j] = parent3.x[j]
    for j in range(num[1], 33, 1):
     parent1.x[j] = parent3.x[j]
  for j in range(33):
   if random.random() < Pm:
    parent1.x[j] = (parent1.x[j] + 1) % 2
   if random.random() < Pm:
    parent2.x[j] = (parent2.x[j] + 1) % 2

  parent1.fitness = Cal_fit(parent1.x, upper, lower)
  parent2.fitness = Cal_fit(parent2.x, upper, lower)
  Gchild[2 * i] = copy.deepcopy(parent1)
  Gchild[2 * i + 1] = copy.deepcopy(parent2)

def Choose_next(G, Gchild, Gsum, Pop): #选择下一代函数
 for i in range(Pop):
  Gsum[i] = copy.deepcopy(G[i])
  Gsum[2 * i + 1] = copy.deepcopy(Gchild[i])
 Gsum = sorted(Gsum, key = lambda x: x.fitness, reverse = True)
 for i in range(Pop):
  G[i] = copy.deepcopy(Gsum[i])
  G[i].place = i

def Decode(x):   #解码函数
 Temp1 = 0
 for i in range(18):
  Temp1 += x[i] * math.pow(2, i)
 Temp2 = 0
 for i in range(18, 33, 1):
  Temp2 += math.pow(2, i - 18) * x[i]
 x1 = lower[0] + Temp1 * (upper[0] - lower[0]) / (math.pow(2, 18) - 1)
 x2 = lower[1] + Temp2 * (upper[1] - lower[1]) / (math.pow(2, 15) - 1)
 if x1 > upper[0]:
  x1 = random.uniform(lower[0], upper[0])
 if x2 > upper[1]:
  x2 = random.uniform(lower[1], upper[1])
 return x1, x2

def Self_Learn(Best, upper, lower, sPm, sLearn): #自学习操作
 num = 0
 Temp = copy.deepcopy(Best)
 while True:
  num += 1
  for j in range(33):
   if random.random() < sPm:
    Temp.x[j] = (Temp.x[j] + 1)%2
  Temp.fitness = Cal_fit(Temp.x, upper, lower)
  if Temp.fitness > Best.fitness:
   Best = copy.deepcopy(Temp)
   num = 0
  if num > sLearn:
   break
 return Best

if __name__ == '__main__':
 upper = [12.1, 5.8]
 lower = [-3, 4.1]
 Pop = 100
 Ppool = 50
 G_max = 300
 Pc = 0.8
 Pm = 0.1
 sPm = 0.05
 sLearn = 20
 G = np.array([Ind() for _ in range(Pop)])
 Gparent = np.array([Ind() for _ in range(Ppool)])
 Gchild = np.array([Ind() for _ in range(Pop)])
 Gsum = np.array([Ind() for _ in range(Pop * 2)])
 Init(G, upper, lower, Pop)  #初始化
 Best = Find_Best(G, Pop)
 for k in range(G_max):
  Selection(G, Gparent, Pop, Ppool)  #使用轮盘赌方法选择其中50%为父代
  Cross_and_Mutation(Gparent, Gchild, Pc, Pm, upper, lower, Pop, Ppool) #交叉和变异生成子代
  Choose_next(G, Gchild, Gsum, Pop)  #选择出父代和子代中较优秀的个体
  Cbest = Find_Best(G, Pop)
  if Best.fitness < Cbest.fitness:
   Best = copy.deepcopy(Cbest)  #跟新最优解
  else:
   G[Cbest.place] = copy.deepcopy(Best)
  Best = Self_Learn(Best, upper, lower, sPm, sLearn)
  print(Best.fitness)
 x1, x2 = Decode(Best.x)
 print(Best.x)
 print([x1, x2])

以上这篇Python实现遗传算法(二进制编码)求函数最优值方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python实现简单HTML表格解析的方法
Jun 15 Python
Python Requests 基础入门
Apr 07 Python
python爬虫之BeautifulSoup 使用select方法详解
Oct 23 Python
Python实现感知器模型、两层神经网络
Dec 19 Python
Python实现去除列表中重复元素的方法小结【4种方法】
Apr 27 Python
python使用__slots__让你的代码更加节省内存
Sep 05 Python
一篇文章弄懂Python中所有数组数据类型
Jun 23 Python
pytorch自定义初始化权重的方法
Aug 17 Python
Python 在函数上添加包装器
Jul 28 Python
PyCharm2020.1.2社区版安装,配置及使用教程详解(Windows)
Aug 07 Python
Python pysnmp使用方法及代码实例
Aug 24 Python
python 制作简单的音乐播放器
Nov 25 Python
python加密解密库cryptography使用openSSL生成的密匙加密解密
Feb 11 #Python
如何通过python实现全排列
Feb 11 #Python
Python3加密解密库Crypto的RSA加解密和签名/验签实现方法实例
Feb 11 #Python
python 遗传算法求函数极值的实现代码
Feb 11 #Python
在django中使用apscheduler 执行计划任务的实现方法
Feb 11 #Python
django在保存图像的同时压缩图像示例代码详解
Feb 11 #Python
Python中包的用法及安装
Feb 11 #Python
You might like
php strcmp使用说明
2010/04/22 PHP
Apache 配置详解(最好的APACHE配置教程)
2010/07/04 PHP
php解析mht文件转换成html的实例
2017/03/13 PHP
PHP7中I/O模型内核剖析详解
2019/04/14 PHP
laravel数据库查询结果自动转数组修改实例
2021/02/27 PHP
jquery插件制作简单示例说明
2012/02/03 Javascript
JavaScript下的时间格式处理函数Date.prototype.format
2016/01/27 Javascript
Javascript中Date类型和Math类型详解
2016/02/27 Javascript
深入浅析Extjs中store分组功能的使用方法
2016/04/20 Javascript
jQuery实现侧浮窗与中浮窗切换效果的方法
2016/09/05 Javascript
微信小程序scroll-view实现字幕滚动
2018/07/14 Javascript
微信小程序swiper实现滑动放大缩小效果
2018/11/15 Javascript
微信小程序抽奖组件的使用步骤
2021/01/11 Javascript
[04:11]DOTA2亚洲邀请赛小组赛第一日 TOP10精彩集锦
2015/01/30 DOTA
[01:13:46]iG vs Winstrike 2018国际邀请赛小组赛BO2 第一场 8.16
2018/08/17 DOTA
Python中查看文件名和文件路径
2017/03/31 Python
Python标准库sched模块使用指南
2017/07/06 Python
Python 实现淘宝秒杀的示例代码
2018/01/02 Python
浅析Python装饰器以及装饰器模式
2018/05/28 Python
Tesserocr库的正确安装方式
2018/10/19 Python
Python爬虫使用浏览器cookies:browsercookie过程解析
2019/10/22 Python
Python爬虫谷歌Chrome F12抓包过程原理解析
2020/06/04 Python
python 密码学示例——凯撒密码的实现
2020/09/21 Python
python3实现名片管理系统(控制台版)
2020/11/29 Python
CSS3弹性伸缩布局之box布局
2016/07/12 HTML / CSS
HTML5样式控制示例代码
2013/11/27 HTML / CSS
春秋航空官方网站:Spring Airlines
2017/09/27 全球购物
Manuka Doctor英国官网:真正的麦卢卡蜂蜜和护肤品
2018/10/26 全球购物
Feelunique德国官方网站:欧洲最大的在线美容零售商
2019/07/20 全球购物
大学生职业生涯设计书
2014/01/02 职场文书
会计职业生涯规划范文
2014/01/04 职场文书
学习十八大坚定理想信念心得体会
2014/03/11 职场文书
《春到梅花山》教学反思
2014/04/16 职场文书
三好学生演讲稿范文
2014/04/26 职场文书
帮一个朋友写的求职信
2014/08/09 职场文书
医药公司开票员岗位职责
2015/04/15 职场文书