boxmoe_header_banner_img

Hello! 欢迎来到悠悠畅享网!

文章导读

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


avatar
站长 2025年8月9日 10

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

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

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

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

以下是一个示例代码:

import numpy as np from 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)  # 初始化 HallOfFame hof = 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'))

代码解释:

  1. HallOfFame: tools.HallOfFame(consts.HALL_OF_FAME_SIZE) 用于存储最优的个体。 consts.HALL_OF_FAME_SIZE 定义了存储的个体数量。 通常设置为1,只保留最佳个体。
  2. history.register(‘hof’, get_best_from_hof, hof=hof): 关键在于这一行。 我们定义了一个 get_best_from_hof 函数,它接受 hof 对象作为参数,并返回 hof 中的第一个个体(即最佳个体)。 我们将这个函数注册到 history 统计信息中,并将 hof 对象传递给它。 这样,每一代都会从 HallOfFame 中获取最佳个体并记录下来。
  3. 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,可以更高效地获取每一代种群中的最佳个体。这种方法避免了在统计信息中进行复杂的过滤操作,提高了代码的执行效率。同时,它也使得代码更加简洁易懂,方便后续的分析和可视化。



评论(已关闭)

评论已关闭