为什么我在 运行 代码时出现错误?
Why I am getting 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
由于以下部分,我得到了错误:
for chromosome in population:
print(fitness_func(population[chromosome][0],population[chromosome][1]))
前一部分的错误信息是
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
我也试着写成:
for chromosome in 10:
print(fitness_func(population[chromosome][0],population[chromosome][1]))
这部分的错误信息是:
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
你能帮帮我吗?
对于你的第一个错误,你应该写
for chromosome in population:
print(fitness_func(chromosome[0], chromosome[1]))
因为 chromosome
是 population
中的一项而不是索引
对于你的第二个错误,你应该这样做
for chromosome in range(10):
print(fitness_func(population[chromosome][0], population[chromosome][1]))
我想计算种群中每条染色体的适应度函数,但是我 运行 代码
时总是出错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
由于以下部分,我得到了错误:
for chromosome in population:
print(fitness_func(population[chromosome][0],population[chromosome][1]))
前一部分的错误信息是
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
我也试着写成:
for chromosome in 10:
print(fitness_func(population[chromosome][0],population[chromosome][1]))
这部分的错误信息是:
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
你能帮帮我吗?
对于你的第一个错误,你应该写
for chromosome in population:
print(fitness_func(chromosome[0], chromosome[1]))
因为 chromosome
是 population
中的一项而不是索引
对于你的第二个错误,你应该这样做
for chromosome in range(10):
print(fitness_func(population[chromosome][0], population[chromosome][1]))