python的deap库使用记录

2024-05-12 01:36
文章标签 python 使用 记录 deap

本文主要是介绍python的deap库使用记录,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  • 主要是在遗传符号回归的代码中添加了注释和根据一部分源码做了一点改动
import operator
import random
import numpy as np
import matplotlib.pyplot as plt
from deap import algorithms, base, creator, tools, gp
from operator import attrgetter##生成数据
def generate_data():X = np.random.uniform(-10, 10, 100).reshape(-1, 1)y = X**3 - 2*X**2 + 3*X - 5 + np.random.normal(0, 5, 100).reshape(-1, 1)return X, y##population:群体
##toolbox:工具箱
##cxpb:交配概率
##mutpb:变异概率
def varAnd(population, toolbox, cxpb, mutpb):offspring = [toolbox.clone(ind) for ind in population]# Apply crossover and mutation on the offspringfor i in range(1, len(offspring), 2):if random.random() < cxpb:offspring[i - 1], offspring[i] = toolbox.mate(offspring[i - 1],offspring[i])del offspring[i - 1].fitness.values, offspring[i].fitness.valuesfor i in range(len(offspring)):if random.random() < mutpb:offspring[i], = toolbox.mutate(offspring[i])del offspring[i].fitness.valuesreturn offspringdef if_then_else(input, output1, output2):return np.where(input, output1, output2)# 定义评价函数
def evalSymbReg(individual, points):func = toolbox.compile(expr=individual)           #编译表达式sqerrors = ((func(points) - y)**2).flatten()      #误差计算return np.sqrt(np.sum(sqerrors)),# 挑选好的若干个体
def selTournament(individuals, k, tournsize, fit_attr="fitness"):chosen = []for i in range(k):aspirants = [random.choice(individuals) for i in range(tournsize)]chosen.append(max(aspirants, key=attrgetter(fit_attr)))return chosendef eaSimple2(population, toolbox, cxpb, mutpb, ngen, stats=None,halloffame=None, verbose=__debug__):#用适应度评价群体,对还没有进行过评价的个体进行评价(主要是存在很多评价过的个体)invalid_ind = []   for ind in population:if not ind.fitness.valid:invalid_ind.append(ind)fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)for ind, fit in zip(invalid_ind, fitnesses):ind.fitness.values = fitif halloffame is not None:    #名人堂halloffame.update(population)#开始迭代过程for gen in range(1, ngen + 1):#1、选择下一代繁殖个体offspring = toolbox.select(population, len(population))#2、交叉变异offspring = toolbox.varAnd(offspring, toolbox, cxpb, mutpb)#3、对适应度无效的个体进行评价invalid_ind = []for ind in offspring:if not ind.fitness.valid:invalid_ind.append(ind)fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)for ind, fit in zip(invalid_ind, fitnesses):ind.fitness.values = fit#4、更新名人堂if halloffame is not None:halloffame.update(offspring)#5、用后代代替当前的群体population = offspring   #用这种方法可以使用原来的地址return population#################################################################################################
# 1、创建遗传符号回归语义集合
pset = gp.PrimitiveSet("MAIN", 1)
pset.addPrimitive(operator.add, 2)
pset.addPrimitive(operator.sub, 2)
pset.addPrimitive(operator.mul, 2)
pset.addPrimitive(operator.neg, 1)
pset.addPrimitive(np.square, 1)
pset.addPrimitive(np.sqrt, 1)
pset.addPrimitive(if_then_else, 3)
pset.addEphemeralConstant("rand101", lambda: random.uniform(-10, 10))# 2、顶级适应度和个体类
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", gp.PrimitiveTree, fitness=creator.FitnessMin)
# 4、定义工具函数,这里可以引入自定义函数
toolbox = base.Toolbox()
## 4.1 定义个体和种群
toolbox.register("expr", gp.genFull, pset=pset, min_=1, max_=2)                      #在两个子叶之间生成1-2深度表达式
toolbox.register("individual", tools.initIterate, creator.Individual, toolbox.expr)  #定义个体
toolbox.register("population", tools.initRepeat, list, toolbox.individual)            #生成群体
## 4.2 公式编码
toolbox.register("compile", gp.compile, pset=pset)                                    #表达式编译
## 4.3 评价和挑选
X, y = generate_data()
toolbox.register("evaluate", evalSymbReg, points=X)                                #用生成的这些数据进行评价 
toolbox.register("select", selTournament, tournsize=3)                           #个体筛选
## 4.4 交叉变异和下一代繁殖
toolbox.register("mate", gp.cxOnePoint)                                                   #交叉toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register("mutate", gp.mutUniform, expr=toolbox.expr_mut, pset=pset)               #变异
toolbox.register("select", selTournament, tournsize=3)   toolbox.register("varAnd", varAnd)   #繁殖########################################################################
# 1、定义种群和名人堂
pop = toolbox.population(n=300)        #种群
hof = tools.HallOfFame(10)              #名人堂
# 2、拟合公式
pop = eaSimple2(pop, toolbox, 0.5, 0.1, 40,halloffame=hof, verbose=True)
best_ind = hof[0]
print("拟合公式:",best_ind)
# 3、画出图像
func = toolbox.compile(expr=best_ind)
y_pred = func(X)
plt.figure()
plt.scatter(X, y, color='blue', label='Actual data')
plt.scatter(X, y_pred, color='red', label='Predicted data')
plt.legend()
plt.show()

这篇关于python的deap库使用记录的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/981235

相关文章

Python数据验证神器Pydantic库的使用和实践中的避坑指南

《Python数据验证神器Pydantic库的使用和实践中的避坑指南》Pydantic是一个用于数据验证和设置的库,可以显著简化API接口开发,文章通过一个实际案例,展示了Pydantic如何在生产环... 目录1️⃣ 崩溃时刻:当你的API接口又双叒崩了!2️⃣ 神兵天降:3行代码解决验证难题3️⃣ 深度

Linux内核定时器使用及说明

《Linux内核定时器使用及说明》文章详细介绍了Linux内核定时器的特性、核心数据结构、时间相关转换函数以及操作API,通过示例展示了如何编写和使用定时器,包括按键消抖的应用... 目录1.linux内核定时器特征2.Linux内核定时器核心数据结构3.Linux内核时间相关转换函数4.Linux内核定时

Python+FFmpeg实现视频自动化处理的完整指南

《Python+FFmpeg实现视频自动化处理的完整指南》本文总结了一套在Python中使用subprocess.run调用FFmpeg进行视频自动化处理的解决方案,涵盖了跨平台硬件加速、中间素材处理... 目录一、 跨平台硬件加速:统一接口设计1. 核心映射逻辑2. python 实现代码二、 中间素材处

python中的flask_sqlalchemy的使用及示例详解

《python中的flask_sqlalchemy的使用及示例详解》文章主要介绍了在使用SQLAlchemy创建模型实例时,通过元类动态创建实例的方式,并说明了如何在实例化时执行__init__方法,... 目录@orm.reconstructorSQLAlchemy的回滚关联其他模型数据库基本操作将数据添

Spring配置扩展之JavaConfig的使用小结

《Spring配置扩展之JavaConfig的使用小结》JavaConfig是Spring框架中基于纯Java代码的配置方式,用于替代传统的XML配置,通过注解(如@Bean)定义Spring容器的组... 目录JavaConfig 的概念什么是JavaConfig?为什么使用 JavaConfig?Jav

Python实现快速扫描目标主机的开放端口和服务

《Python实现快速扫描目标主机的开放端口和服务》这篇文章主要为大家详细介绍了如何使用Python编写一个功能强大的端口扫描器脚本,实现快速扫描目标主机的开放端口和服务,感兴趣的小伙伴可以了解下... 目录功能介绍场景应用1. 网络安全审计2. 系统管理维护3. 网络故障排查4. 合规性检查报错处理1.

Python轻松实现Word到Markdown的转换

《Python轻松实现Word到Markdown的转换》在文档管理、内容发布等场景中,将Word转换为Markdown格式是常见需求,本文将介绍如何使用FreeSpire.DocforPython实现... 目录一、工具简介二、核心转换实现1. 基础单文件转换2. 批量转换Word文件三、工具特性分析优点局

Python中4大日志记录库比较的终极PK

《Python中4大日志记录库比较的终极PK》日志记录框架是一种工具,可帮助您标准化应用程序中的日志记录过程,:本文主要介绍Python中4大日志记录库比较的相关资料,文中通过代码介绍的非常详细,... 目录一、logging库1、优点2、缺点二、LogAid库三、Loguru库四、Structlogphp

Java使用Spire.Doc for Java实现Word自动化插入图片

《Java使用Spire.DocforJava实现Word自动化插入图片》在日常工作中,Word文档是不可或缺的工具,而图片作为信息传达的重要载体,其在文档中的插入与布局显得尤为关键,下面我们就来... 目录1. Spire.Doc for Java库介绍与安装2. 使用特定的环绕方式插入图片3. 在指定位

Springboot3 ResponseEntity 完全使用案例

《Springboot3ResponseEntity完全使用案例》ResponseEntity是SpringBoot中控制HTTP响应的核心工具——它能让你精准定义响应状态码、响应头、响应体,相比... 目录Spring Boot 3 ResponseEntity 完全使用教程前置准备1. 项目基础依赖(M