如果适应度饱和,Pygad 会创建新种群

问题描述 投票:0回答:1

我正在使用 Pygad 来计算优化问题,但是该算法在所有代运行之前就达到了局部最小值(不是理想的解决方案)。我希望能够在每一代之后检查适应度是否已经饱和一定数量的代,如果是这样,则使用当前的“每次流行的溶胶”、“基因数量”和“基因空间”重新初始化新种群实例。这可以在 Pygad 中做到吗?任何帮助将不胜感激。

我尝试设置“On Generation”回调,但我似乎找不到调用新种群初始化并将其传回“population”属性的方法。

python genetic-algorithm genetic-programming pygad
1个回答
0
投票

这是应用您提到的内容的示例。如果适应度在 10 代内达到饱和,就会生成新的种群。

import pygad

def fitness_func(ga_instance, solution, solution_idx):
    return 5

def on_generation(ga_i):
    if ga_i.generations_completed > 10:
        # Check if the fitness is saturated
        if ga_i.best_solutions_fitness[-1] == ga_i.best_solutions_fitness[-10]:
            # reinitialize a new population using the 'sol per pop', 'gene number', and 'gene space'
            ga_i.initialize_population(low=ga_i.init_range_low,
                                       high=ga_i.init_range_high,
                                       allow_duplicate_genes=ga_i.allow_duplicate_genes,
                                       mutation_by_replacement=True,
                                       gene_type=ga_i.gene_type)
            # At this point, a new population is created and assigned to the 'population' parameter.


ga_instance = pygad.GA(num_generations=20,
                       sol_per_pop=5,
                       num_genes=2,
                       num_parents_mating=2,
                       fitness_func=fitness_func,
                       on_generation=on_generation)

ga_instance.run()
© www.soinside.com 2019 - 2024. All rights reserved.