别再死磕数学公式了!用Python的DEAP库5分钟上手遗传算法(附实战代码)
用Python的DEAP库5分钟实现遗传算法零基础实战指南遗传算法作为模拟自然进化过程的智能优化方法在机器学习、工程设计和游戏AI等领域有着广泛应用。但传统教材往往陷入复杂的数学推导让初学者望而生畏。本文将带你用Python的DEAP库快速构建第一个遗传算法模型无需深入理论就能解决实际问题。1. 环境准备与DEAP库安装在开始之前我们需要配置好Python环境并安装必要的库。DEAP(Distributed Evolutionary Algorithms in Python)是专门为进化计算设计的强大框架支持遗传算法、遗传编程等多种进化计算技术。pip install deap numpy matplotlib安装完成后可以通过以下命令验证是否安装成功import deap print(deap.__version__)提示建议使用Python 3.7或更高版本某些旧版本可能会出现兼容性问题。如果遇到安装问题可以尝试先升级pip工具。2. 定义优化问题让我们从一个经典问题开始寻找函数f(x) x²在区间[0,31]上的最大值。虽然这个问题很简单但它能清晰展示遗传算法的核心机制。首先我们需要定义个体编码方式。对于这个整数优化问题我们可以使用二进制编码from deap import base, creator, tools import random # 定义适应度函数 creator.create(FitnessMax, base.Fitness, weights(1.0,)) creator.create(Individual, list, fitnesscreator.FitnessMax) toolbox base.Toolbox() # 定义基因属性0或1 toolbox.register(attr_bool, random.randint, 0, 1) # 定义个体包含5个基因因为2^532 toolbox.register(individual, tools.initRepeat, creator.Individual, toolbox.attr_bool, 5) # 定义种群由多个个体组成 toolbox.register(population, tools.initRepeat, list, toolbox.individual)3. 构建遗传算法核心组件遗传算法的三大核心操作是选择、交叉和变异。DEAP库提供了多种实现方式我们可以根据问题特点灵活选择。3.1 评估函数首先定义如何评估个体的适应度def evalOneMax(individual): # 将二进制转换为十进制 x int(.join(map(str, individual)), 2) return x * x, # 注意返回的是元组 toolbox.register(evaluate, evalOneMax)3.2 遗传操作配置接下来配置遗传算法的操作算子# 选择算子锦标赛选择 toolbox.register(select, tools.selTournament, tournsize3) # 交叉算子单点交叉 toolbox.register(mate, tools.cxOnePoint) # 变异算子位翻转变异 toolbox.register(mutate, tools.mutFlipBit, indpb0.05)这些参数可以根据实际问题进行调整参数说明推荐值tournsize锦标赛选择的大小3-5indpb每个基因变异的概率0.01-0.1cxpb交叉概率0.5-0.9mutpb变异概率0.1-0.34. 运行遗传算法现在我们可以将各个组件组合起来运行完整的遗传算法流程def main(): pop toolbox.population(n50) # 50个个体的种群 CXPB, MUTPB, NGEN 0.5, 0.2, 40 # 参数设置 # 评估初始种群 fitnesses list(map(toolbox.evaluate, pop)) for ind, fit in zip(pop, fitnesses): ind.fitness.values fit for g in range(NGEN): # 选择下一代 offspring toolbox.select(pop, len(pop)) # 克隆选中的个体 offspring list(map(toolbox.clone, offspring)) # 对后代进行交叉和变异 for child1, child2 in zip(offspring[::2], offspring[1::2]): if random.random() CXPB: toolbox.mate(child1, child2) del child1.fitness.values del child2.fitness.values for mutant in offspring: if random.random() MUTPB: toolbox.mutate(mutant) del mutant.fitness.values # 评估新个体 invalid_ind [ind for ind in offspring if not ind.fitness.valid] fitnesses map(toolbox.evaluate, invalid_ind) for ind, fit in zip(invalid_ind, fitnesses): ind.fitness.values fit # 替换种群 pop[:] offspring return pop best_ind tools.selBest(main(), 1)[0] print(最佳个体:, best_ind, 对应x值:, int(.join(map(str, best_ind)), 2))5. 进阶应用旅行商问题掌握了基本原理后我们可以尝试更复杂的问题。旅行商问题(TSP)是经典的组合优化问题遗传算法能有效寻找近似最优解。5.1 问题定义假设有5个城市需要找到访问所有城市一次并返回起点的最短路径。首先定义城市坐标import numpy as np cities { 0: (0, 0), 1: (1, 5), 2: (2, 3), 3: (5, 2), 4: (6, 6) }5.2 适应度函数定义路径长度的计算函数def distance(city1, city2): return np.sqrt((city1[0]-city2[0])**2 (city1[1]-city2[1])**2) def evalTSP(individual): dist 0 for i in range(len(individual)): dist distance(cities[individual[i-1]], cities[individual[i]]) return dist,5.3 特殊遗传操作对于排列编码问题需要使用特定的交叉和变异操作toolbox.register(evaluate, evalTSP) toolbox.register(mate, tools.cxOrdered) # 顺序交叉 toolbox.register(mutate, tools.mutShuffleIndexes, indpb0.05) # 位置变异在实际项目中我发现调整变异概率对结果影响很大。对于TSP问题适当提高变异概率(0.1-0.3)有助于跳出局部最优解。