python 遗传算法求函数极值的实现代码
作者:zzzzjh 发布时间:2023-08-29 11:36:11
标签: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<pc:
print('yes')
c=np.random.randint(1,self.Bitlength-1)
print(c)
a=self.population[seln[1]][c:]
b=self.population[seln[0]][c:]
d[c:]=b
f[c:]=a
print(d)
print(f)
g=d
h=f
else:
g=self.population[seln[1]]
h=self.population[seln[0]]
return g,h
"""变异操作"""
def mutation(self,scnew,pmutation):
r=np.random.uniform(0, 1)
if r < pmutation:
v=np.random.randint(0,self.Bitlength)
scnew[v]=abs(scnew[v]-1)
else:
scnew=scnew
return scnew
"""二进制转换为十进制"""
def transform2to10(self,population):
#x=population[-1] #最后一位的值
x=0
#n=len(population)
n=self.Bitlength
p=population.copy()
p=p.tolist()
p.reverse()
for j in range(n):
x=x+p[j]*pow(2,j)
return x #返回十进制的数
"""目标函数"""
def targetfun(self,x):
#y = x∗(np.sin(10∗(np.pi)∗x))+ 2
y=x*(np.sin(10*np.pi*x))+2
return y
if __name__ == '__main__':
Generationmax=12
gg=Ga()
scnew=[]
ymax=[]
#print(gg.population)
Fitvalue, cumsump=gg.fitness(gg.population)
Generation = 1
while Generation < Generationmax +1:
Fitvalue, cumsump = gg.fitness(gg.population)
for j in range(0,gg.popsize,2):
seln = gg.select( cumsump) #返回选中的2个个体的序号
scro = gg.crossover(seln, gg.pcrossover) #返回两条染色体
s1=gg.mutation(scro[0],gg.pmutation)
s2=gg.mutation(scro[1],gg.pmutation)
scnew.append(s1)
scnew.append(s2)
gg.population = scnew
Fitvalue, cumsump = gg.fitness(gg.population)
fmax=max(Fitvalue)
d=Fitvalue.index(fmax)
ymax.append(fmax)
x = gg.transform2to10(gg.population[d])
xx = gg.boundsbegin + x * (gg.boundsend - gg.boundsbegin) / (pow(2, gg.Bitlength) - 1)
Generation = Generation + 1
Bestpopulation = xx
Targetmax = gg.targetfun(xx)
print(xx)
print(Targetmax)
x=np.linspace(-2,3,30)
y=x*(np.sin(10*np.pi*x))+2
plt.scatter(2.65,4.65,c='red')
plt.xlim(0,5)
plt.ylim(0,6)
plt.plot(x,y)
plt.annotate('local max', xy=(2.7,4.8), xytext=(3.6, 5.2),arrowprops=dict(facecolor='black', shrink=0.05))
plt.show()
一个函数求极值的仿真的作业,参考了别人的matlab代码,用python复现了一遍,加深印象!
来源:https://blog.csdn.net/zzzzjh/article/details/80633573


猜你喜欢
- View in Browser功能不生效问题安装玩view in browser插件后,在文档中点击邮件的view in browser 不
- 源码解读Bootstrap按钮按钮组按钮组和下拉菜单组件一样,需要依赖于bootstrap.js。使用“btn-group”的容器,把多个按
- filter的语法:filter(函数名字,可迭代的变量)其实filter就是一个“过滤器”:把【可迭代的变量】中的值,挨个地传给函数进行处
- 为了画个图,被numpy这个模块的安装真的折腾疯了!!!一直装不上,花了几个小时,看了网上的很多教程、方法发现总结得不是很全,这里总结一下,
- 先说需求: 1、django 自带了admin后管,如果我们需要使用,只需把我们定义的models注册即可;2、但如果只是简单注册,那显示的
- 1.引子:函数也是对象木有括号的函数那就不是在调用。def hi(name="yasoob"):return "
- 前言Python是面向对象的程序设计(Object Oriented Programming)。面向对象的程序设计的一条基本原则是:计算机程
- 本文实例为大家分享了python绘制散点图和折线图的具体代码,供大家参考,具体内容如下#散点图,一般和相关分析、回归分析结合使用import
- PDO::quotePDO::quote — 为SQL语句中的字符串添加引号。(PHP 5 >= 5.1.0, PECL pdo &g
- 先附上官方文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pan
- 1 计算属性实现模糊查询vue 中通过计算属性实现模糊查询,创建 html 文件,代码直接放入即可。这里自己导入 vue,我是导入本地已经下
- 一、安装MySQL下载MySQL的社区版的压缩包:https://dev.mysql.com/get/Downloads/MySQL-8.0
- 概览最近开始在学习mysql相关知识,自己根据学到的知识点,根据自己的理解整理分享出来,本篇文章会分析下一个sql语句在mysql中的执行流
- 注:IE8以前的版本均不支持该特性为了向文档中插入生成内容,可以使用:before与:after伪元素。如,我想在所有链接的后面加上&quo
- 借助map实现golang中没有set数据结构,一般是通过map实现,因为map的key值是不能重复的示例type empty struct
- 目录1. threding模块创建线程对象2. threding模块创建多线程3. 多线程的参数传递4. 线程产生的资源竞争1. thred
- 前言记录CS2000设备使用串口连接以及相关控制。CS2000是一台分光辐射亮度计,也就是可以测量光源的亮度。详细的规格网址参考CS2000
- 要将xian80地理坐标系转换成投影坐标系:xian1980 = """GEOGCS["GCS_Xi
- yolov5训练命令python .\train.py --data my.yaml --workers 8 --batch-size 32
- 代码如下: var params = new Enumerator(Request.QueryString); while (!params