【问题标题】:Gene AI package python - define a custom fitness function基因AI包python——定义自定义适应度函数
【发布时间】:2023-03-18 01:30:01
【问题描述】:

我正在使用 python 中的 Gene AI 包来测试遗传算法 (https://github.com/diogomatoschaves/geneal/blob/master/geneal/genetic_algorithms/genetic_algorithm_base.py)。

我想要自己的健身功能,所以我写了

def my_fitness(chromosome):   
    fitness = mean_absolute_percentage_error(chromosome, [0.5 0.5 0.5 0.5])
    return fitness

然后按照文档编写如下代码:

    from geneal.genetic_algorithms import ContinuousGenAlgSolver
    from geneal.applications.fitness_functions.continuous import fitness_functions_continuous
    
    solver = ContinuousGenAlgSolver(
    n_genes=4, 
    fitness_function=my_fitness(chromosome),
    pop_size=10,
    max_gen=200,
    mutation_rate=0.1,
    selection_rate=0.6,
    selection_strategy="roulette_wheel",
    problem_type=float, # Defines the possible values as float numbers
    variables_limits=(-10, 10) # Defines the limits of all variables between -10 and 10. 
                               # Alternatively one can pass an array of tuples defining the limits
                               # for each variable: [(-10, 10), (0, 5), (0, 5), (-20, 20)]
)

solver.solve()

不清楚如何使用我自己的健身功能。得到染色体未定义的错误(显然!)。 如何在这个包中使用我自己的健身功能。请出示。

【问题讨论】:

    标签: python genetic-algorithm


    【解决方案1】:

    一个适应度函数有两个要求:

    • 它必须传递一个且只有一个参数 - 染色体。如果它是二进制遗传算法求解器,则染色体是 1 和 0 的 numpy 数组,如果是连续遗传算法求解器,则染色体是 0 到 9 之间的数字数组。这个数组的大小由你初始化求解器的基因数量定义,数组上的每个位置对应一个不同的变量。

    • 它必须返回一个实数。

    此功能的内部运作由您决定。然后在初始化期间将其传递给对象,例如:

    from geneal.genetic_algorithms import ContinuousGenAlgSolver
    from geneal.applications.fitness_functions.continuous import fitness_functions_continuous
        
        solver = ContinuousGenAlgSolver(
        n_genes=4, 
        fitness_function=my_fitness,
        pop_size=10,
        max_gen=200,
        mutation_rate=0.1,
        selection_rate=0.6,
        selection_strategy="roulette_wheel",
        problem_type=float, # Defines the possible values as float numbers
        variables_limits=(-10, 10) # Defines the limits of all variables between -10 and 10. 
                                   # Alternatively one can pass an array of tuples defining the limits
                                   # for each variable: [(-10, 10), (0, 5), (0, 5), (-20, 20)]
    )
    

    我建议您查看包中提供的示例,以更好地了解如何定义自定义适应度函数:examples

    【讨论】:

      猜你喜欢
      • 2011-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2016-05-24
      • 2019-11-05
      • 2018-05-28
      • 1970-01-01
      相关资源
      最近更新 更多