目录
python DEAP框架
![DEAP 图标](https://deap.readthedocs.io/en/master/_images/deap_long.png)
Core核心模块:
- base: 基本结构。包含Toolbox(存储自定的EA运行所需的对象和操作), Fitness(个体的适应度的基类)等。
- creator: 允许通过动态添加属性或函数来创建符合问题需求的类,常用来创建个体。
- tools: 包含多种选择(selection)操作函数,遗传算子操作函数(多种crossover, mutation)等。
还会用到的模块:
- algorithms (包含常用进化算法),
- gp (提供了DEAP框架上实行genetic programming的类与方法,如创建GP树的类)
![DEAP结构示意图](https://img-blog.csdnimg.cn/20190815112708901.png)
Genetic Programming基本过程回顾
- Initialization of Population
初始化族群:设定 primitive set——设定包含所用函数、操作的函数集(function set),设定包含变量、常量和无参函数的终止集(terminal set)。给定参数,随机生成初始族群。
* 族群生成方法:grow, full, ramped half and half 等 - Fitness Evaluation
适应度评估:根据具体问题设计适应度函数(fitness function),评估各个个体的适应度。 - Selection
选择父系:(绝大部分情况)根据适应度,随机选出相对优秀的个体。
* 选择方法:锦标赛选择法、轮盘赌选择法等 - Genetic Operation
遗传操作:父体通过交叉、变异、复制生成下一代个体。
* 遗传算子:subtree crossover, one-point crossover, subtree mutation, reproduction - Termination or Iteration
判断终止或继续迭代
DEAP 举例讲解
DEAP官方文档给出的一个简单GP例子 (符号回归问题): Symbolic Regression Problem: Introduction to GP
在这里令我们的期望曲线为
( x 4 + x 3 + x 2 + x ) (x^4+x^3+x^2+x) (x4+x3+x2+x)
并在[-1, 1]区间设置20个等分点来评估适应度(fitness),来寻找一个GP生成的最拟合的表达式。
以下是对它的讲解,代码部分的comment当中也加入了对代码过程和操作的解读。
0. 导入模块
import math
import random
import operator # python内部操作符,包含对象比较、逻辑比较、算术运算和序列操作
import numpy
# deap的常用五个模块齐了
from deap import base # core
from deap import creator # core
from deap import tools # core
from deap import gp
from deap import algorithms
1. Primitive Set的创建
* 注:Primitive set 为function set和terminal set的并集。primitives不是指functions + terminals,primitives仅仅指functions
def protectedDiv(left, right): # 保护性除法,防崩
try:
return left / right
except ZeroDivisionError: