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的Darts库实现时间序列预测

《Python的Darts库实现时间序列预测》Darts一个集统计、机器学习与深度学习模型于一体的Python时间序列预测库,本文主要介绍了Python的Darts库实现时间序列预测,感兴趣的可以了解... 目录目录一、什么是 Darts?二、安装与基本配置安装 Darts导入基础模块三、时间序列数据结构与

Python正则表达式匹配和替换的操作指南

《Python正则表达式匹配和替换的操作指南》正则表达式是处理文本的强大工具,Python通过re模块提供了完整的正则表达式功能,本文将通过代码示例详细介绍Python中的正则匹配和替换操作,需要的朋... 目录基础语法导入re模块基本元字符常用匹配方法1. re.match() - 从字符串开头匹配2.

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv

通过Docker容器部署Python环境的全流程

《通过Docker容器部署Python环境的全流程》在现代化开发流程中,Docker因其轻量化、环境隔离和跨平台一致性的特性,已成为部署Python应用的标准工具,本文将详细演示如何通过Docker容... 目录引言一、docker与python的协同优势二、核心步骤详解三、进阶配置技巧四、生产环境最佳实践

Python一次性将指定版本所有包上传PyPI镜像解决方案

《Python一次性将指定版本所有包上传PyPI镜像解决方案》本文主要介绍了一个安全、完整、可离线部署的解决方案,用于一次性准备指定Python版本的所有包,然后导出到内网环境,感兴趣的小伙伴可以跟随... 目录为什么需要这个方案完整解决方案1. 项目目录结构2. 创建智能下载脚本3. 创建包清单生成脚本4

Spring Security简介、使用与最佳实践

《SpringSecurity简介、使用与最佳实践》SpringSecurity是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架,本文给大家介绍SpringSec... 目录一、如何理解 Spring Security?—— 核心思想二、如何在 Java 项目中使用?——

springboot中使用okhttp3的小结

《springboot中使用okhttp3的小结》OkHttp3是一个JavaHTTP客户端,可以处理各种请求类型,比如GET、POST、PUT等,并且支持高效的HTTP连接池、请求和响应缓存、以及异... 在 Spring Boot 项目中使用 OkHttp3 进行 HTTP 请求是一个高效且流行的方式。

Python实现Excel批量样式修改器(附完整代码)

《Python实现Excel批量样式修改器(附完整代码)》这篇文章主要为大家详细介绍了如何使用Python实现一个Excel批量样式修改器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一... 目录前言功能特性核心功能界面特性系统要求安装说明使用指南基本操作流程高级功能技术实现核心技术栈关键函

python获取指定名字的程序的文件路径的两种方法

《python获取指定名字的程序的文件路径的两种方法》本文主要介绍了python获取指定名字的程序的文件路径的两种方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要... 最近在做项目,需要用到给定一个程序名字就可以自动获取到这个程序在Windows系统下的绝对路径,以下

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC