pythonpython-3.xmathematical-optimizationgenetic-algorithmpygad

Genetic Algorithm with PyGAD


I'm trying to make a genetic algorithm with PyGAD to find the best value that maximize this function: Z = (3*(x^2 - y)^2 + (100 - x)^2) + (y- x) , x and y between [-4, 4].

Could someone send me an example of something similar to this function? The example I found uses a function with inputs that have already been given: y = f(w1:w6) = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + 6wx6

I don't know how i can get the fitness value to each individual using the function with two variables


Solution

  • This is a PyGAD code that solves your problem.

    import pygad
    
    def fitness_func(solution, solution_idx):
        x = solution[0]
        y = solution[1]
        Z = -(100*(x**2 - y)**2 + (1 - x)**2)
        return Z
    
    last_fitness = 0
    def on_generation(ga_instance):
        global last_fitness
        print("Generation = {generation}".format(generation=ga_instance.generations_completed))
        print("Fitness    = {fitness}".format(fitness=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1]))
        print("Change     = {change}".format(change=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1] - last_fitness))
        last_fitness = ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1]
    
    ga_instance = pygad.GA(num_generations=1000,
                           num_parents_mating=5,
                           sol_per_pop=10,
                           num_genes=2,
                           gene_space={"low": -2, "high": 2},
                           mutation_by_replacement=True,
                           fitness_func=fitness_func,
                           on_generation=on_generation)
    
    ga_instance.run()
    
    ga_instance.plot_fitness()
    
    solution, solution_fitness, solution_idx = ga_instance.best_solution(ga_instance.last_generation_fitness)
    print("Solution", solution)
    print("Fitness value of the best solution = {solution_fitness}".format(solution_fitness=solution_fitness))
    

    Based on your description, here are the values of some parameters:

    You can change the other parameters used according to your preference. For example, you may get better fitness by increasing the number of generations (num_generations).

    Please make sure that PyGAD is installed and run the script.