使用 DEAP 获取每一代最佳个体

使用 deap 获取每一代最佳个体

本文旨在介绍如何在使用 DEAP (Distributed Evolutionary Algorithms in Python) 库进行遗传算法编程时,高效地获取每一代种群中的最佳个体。通过结合 HallOfFame 类和 MultiStatistics 类,我们可以轻松地追踪并记录每一代的最优解,从而进行后续的分析或可视化。本文提供了一种简洁明了的方法,避免了复杂的过滤操作,提高了代码效率。

在使用 DEAP 进行遗传算法开发时,经常需要追踪每一代种群中的最佳个体,以便分析算法的收敛情况或者进行可视化展示。一种常见的方法是使用 tools.Statistics 和 tools.MultiStatistics 类来记录种群的统计信息。然而,如果直接在 Statistics 类中注册一个复杂的函数来查找最佳个体,可能会导致性能问题,尤其是在种群规模较大时。

更高效的方法是利用 DEAP 提供的 HallOfFame 类。HallOfFame 类可以自动记录种群中适应度最高的若干个个体。我们可以在每一代结束后,从 HallOfFame 中获取最佳个体,并将其添加到 MultiStatistics 中。

以下是一个示例代码:

import numpy as npfrom deap import base, creator, tools, algorithms# 假设已经定义了适应度函数 tspDistance 和常量 consts# 例如:# def tspDistance(individual):#     # 计算个体的适应度#     return np.sum(individual)# consts.HALL_OF_FAME_SIZE = 1# consts.P_CROSSOVER = 0.9# consts.P_MUTATION = 0.1# consts.MAX_GENERATIONS = 10# 创建个体和种群creator.create("FitnessMin", base.Fitness, weights=(-1.0,))creator.create("Individual", list, fitness=creator.FitnessMin)toolbox = base.Toolbox()# 假设已经定义了 toolbox.register("attribute", ...) 和 toolbox.register("individual", ...)# 以及 toolbox.register("population", ...)# 例如:# toolbox.register("attribute", np.random.rand)# toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attribute, n=10)# toolbox.register("population", tools.initRepeat, list, toolbox.individual)# toolbox.register("mate", tools.cxTwoPoint)# toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=1, indpb=0.1)# toolbox.register("select", tools.selTournament, tournsize=3)# toolbox.register("evaluate", tspDistance)# 初始化 HallOfFamehof = tools.HallOfFame(consts.HALL_OF_FAME_SIZE)# 配置统计信息stats = tools.Statistics(lambda ind: ind.fitness.values)stats.register('min', np.min)stats.register('mean', np.mean)# 定义一个函数,从 HallOfFame 中获取最佳个体def get_best_from_hof(hof):    return hof[0] if hof else None  # 确保 hof 不为空# 注册历史记录,使用 HallOfFame 中的最佳个体history = tools.Statistics(lambda ind: ind)history.register('hof', get_best_from_hof, hof=hof) # 传递 hof 对象# 创建 MultiStatistics 对象mstats = tools.MultiStatistics(fitness=stats, history=history)# 初始化种群population = toolbox.population(n=100)# 运行遗传算法population, logbook = algorithms.eaSimple(population, toolbox,                                              cxpb=consts.P_CROSSOVER, mutpb=consts.P_MUTATION,                                              ngen=consts.MAX_GENERATIONS, stats=mstats,                                              halloffame=hof, verbose=True)# 现在可以通过 logbook 访问每一代的最佳个体# 例如:# print(logbook.chapters['history'].select('hof'))

代码解释:

HallOfFame: tools.HallOfFame(consts.HALL_OF_FAME_SIZE) 用于存储最优的个体。 consts.HALL_OF_FAME_SIZE 定义了存储的个体数量。 通常设置为1,只保留最佳个体。history.register(‘hof’, get_best_from_hof, hof=hof): 关键在于这一行。 我们定义了一个 get_best_from_hof 函数,它接受 hof 对象作为参数,并返回 hof 中的第一个个体(即最佳个体)。 我们将这个函数注册到 history 统计信息中,并将 hof 对象传递给它。 这样,每一代都会从 HallOfFame 中获取最佳个体并记录下来。algorithms.eaSimple: 在 eaSimple 函数中,halloffame=hof 确保每一代更新 HallOfFame,stats=mstats 确保每一代记录统计信息,包括从 HallOfFame 中获取的最佳个体。

注意事项:

确保 consts.HALL_OF_FAME_SIZE 设置为适当的值。如果只需要记录每一代的最佳个体,设置为 1 即可。tspDistance 函数需要正确计算个体的适应度值。如果 HallOfFame 为空,hof[0] 会抛出异常。所以在 get_best_from_hof 函数中添加了 if hof else None 的判断。

总结:

通过结合 HallOfFame 和 MultiStatistics,可以更高效地获取每一代种群中的最佳个体。这种方法避免了在统计信息中进行复杂的过滤操作,提高了代码的执行效率。同时,它也使得代码更加简洁易懂,方便后续的分析和可视化。

以上就是使用 DEAP 获取每一代最佳个体的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1366848.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月14日 06:55:37
下一篇 2025年12月14日 06:55:50

相关推荐

发表回复

登录后才能评论
关注微信