Search code examples
pythongenetic-algorithmpygad

TypeError: can't multiply sequence by non-int of type 'GA'


I am making a Genetic Algorithm(GA) in python with pygad, but I keep getting this error:

TypeError: can't multiply sequence by non-int of type 'GA'

here is my whole code:

import pygad
import numpy

print(pygad.__version__)

inputs = [0.4,1,0,7,8,1,2,3,4,5,6,7,8,9,0,12,23,34,45,5667,67,78,95678,456,23,234,456,9,0,9,54,213,]
desired_output = 32

def fitness_func(solution, solution_idx, ga_instance):
    output = numpy.sum(solution*inputs) # error here
    fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)

    return fitness

ga_instance = pygad.GA(num_generations=100,
                       sol_per_pop=10,
                       num_genes=len(inputs),
                       num_parents_mating=2,
                       fitness_func=fitness_func,
                       mutation_type="random",
                       mutation_probability=0.6)

ga_instance.run()

ga_instance.plot_fitness()

*the inputs are just a bunch of random numbers

I am using pygad 3.0.0 and python 3.11.3

I have tried to do this:

output = numpy.sum(int(solution)*inputs)

And also just replacing the solution parameter with the expected output(32) but when I do that the AI doesn't do anything.


Solution

  • Like Anony Mous said in the comments, here is the answer:

    "Ok what I think is happening is pygad.GA is passing either solution incorrectly. So check your fitness_func function, make sure it's parameters are correct."(Anony Mous)

    here is the working bit of code:

    import pygad
    import numpy
    
    print(pygad.__version__)
    
    inputs = [0.4,1,0,7,8,1,2,3,4,5,6,7,8,9,0,12,23,34,45,5667,67,78,95678,456,23,234,456,9,0,9,54,213,]
    desired_output = 32
    
    def fitness_func(ga_instance, solution, solution_idx): # error was here
        output = numpy.sum(solution*inputs)
        fitness = 1.0 / (numpy.abs(output - desired_output) + 0.000001)
    
        return fitness
    
    ga_instance = pygad.GA(num_generations=100,
                           sol_per_pop=10,
                           num_genes=len(inputs),
                           num_parents_mating=2,
                           fitness_func=fitness_func,
                           mutation_type="random",
                           mutation_probability=0.6)
    
    ga_instance.run()
    
    ga_instance.plot_fitness()
    

    Thanks so much!