Search code examples
pythongenetic-algorithm

Why I am getting Errors when I run the code?


I want to calculate the fitness function for each chromosome in population, but I always get Errors when I run the code

population = np.random.randint(x1,y2, size=(100, 2))
def fitness_func(x1, y1):
x2  , y2  = x1 + 160 , y1 + 60
x = 0
Im = Image.open("D:\hagar\Genetic Algorithm\Project\Binary Image.png")
for i in range (x1,x2):
    for j in range (y1,y2):
        r, g, b = Im.getpixel((i,j))
        a = (r, g, b)
        x = x + int(r/255)+ int(g/255)+ int (b/255)
return x

I got the errors because of the following part:

for chromosome in population:
print(fitness_func(population[chromosome][0],population[chromosome][1]))

for the previous part the error message is

Traceback (most recent call last): File "d:\hagar\Genetic Algorithm\Project\GA Eye Detection.py", line 60, in print(fitness_func(population[chromosome][0],population[chromosome][1])) IndexError: index 143 is out of bounds for axis 0 with size 100

I also tried to write it as:

for chromosome in 10:
print(fitness_func(population[chromosome][0],population[chromosome][1]))

and for this part the error message is:

Traceback (most recent call last): File "d:\hagar\Genetic Algorithm\Project\GA Eye Detection.py", line 59, in for chromosome in 10: TypeError: 'int' object is not iterable

Could you help me please?


Solution

  • for your first error, you should write

    for chromosome in population:
        print(fitness_func(chromosome[0], chromosome[1]))
    

    as chromosome is an item in population not an index

    for your second error, you should do

    for chromosome in range(10):
        print(fitness_func(population[chromosome][0], population[chromosome][1]))