【问题标题】:Numpy array index out of range with Genetic AlgorithmNumpy数组索引超出遗传算法范围
【发布时间】:2014-08-04 16:03:25
【问题描述】:

我编写了一个脚本来根据源生成图像,并使用遗传算法使用随机椭圆。运行后一直收到这个错误(每次种子的长度都不一样,这只是一个例子):

输出:

[[ 42 166  88  21]
 [ 25 201 321 227]
 [ 21  78 153  53]
 [  5  74 231  20]
 [  3  96 394  15]
 [ 20 239  28 244]
 [ 33   6  94  27]
 [  4 253 193 113]
 [ 10 139 323  16]
 [ 31   9  97 117]
 [ 23 273 181 214]
 [ 24 286 361 231]
 [ 33   2 187  47]
 [ 35  98 133 177]
 [ 10 307 136  76]
 [ 35 132 269 161]
 [ 25 147  11   2]
 [ 36 141 338 100]
 [ 23 163 430  37]
 [ 17 285 216  53]
 [ 18   2 181 119]
 [ 43 199 117 253]] 22

Traceback (most recent call last):
  File "E:/genetic image/genetic_image.py", line 106, in <module>
    generate()
  File "E:/genetic image/genetic_image.py", line 93, in generate
    params, test_image = seed_test(seeds[:random.randint(0, reproduce)])
  File "E:/genetic image/genetic_image.py", line 41, in seed_test
    r = int(seeds[i, 0] + random.random() - 0.5)
IndexError: index (22) out of range (0<=index<22) in dimension 0

这是脚本:

import random
import copy
import numpy
from PIL import Image, ImageDraw

optimal = Image.open("charles-darwin_large.jpg")
optimal = optimal.convert("RGB")
size = width, height = optimal.size
population = 2
generations = 5000
elements = int(1e3)
reproduce = height / 10
max_radius = height / 10
diff_max = height / 10

def random_test():
    test_elements = []
    test_image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(test_image)

    for i in range(elements):
        r = int(max_radius * random.random())
        x, y = random.randint(0, width), random.randint(0, height)
        color_value = random.randint(0, 255)
        color = (color_value, color_value, color_value)

        test_elements.append([r, x, y, color_value])

        draw.ellipse((x - r, y - r, x + r, y + r), fill = color)

    return test_elements, test_image

def seed_test(seeds):
    test_elements = []
    test_image = Image.new("RGB", (width, height), "white")
    draw = ImageDraw.Draw(test_image)

    print seeds, len(seeds)

    for i in range(elements):
        r = int(seeds[i, 0] + random.random() - 0.5)
        x, y = seeds[i, 1] + random.randint(-5, 5), seeds[i, 2] + random.randint(-5, 5)
        color_value = seeds[i, 3] + random.randint(-5, 5)
        color = (color_value, color_value, color_value)

        test_elements.append([r, x, y, color_value])

        draw.ellipse((x - r, y - r, x + r, y + r), fill = color)

    return test_elements, test_image

def grayscale(image):
    return image.convert("LA")

def fitness(source, generated):
    fitness = 0
    for i in range(height - 1):
        for j in range(width - 1):

            r1, g1, b1 = source.getpixel((j, i))
            r2, g2, b2 = generated.getpixel((j, i))

            deltaRed = r1 - r2
            deltaGreen = g1 - g2
            deltaBlue = b1 - b2

            pixelFitness = deltaRed ** 2 + deltaGreen ** 2 + deltaBlue ** 2

            fitness += pixelFitness

    return fitness

def generate():
    samples = []
    scores = [0] * reproduce

    for i in range(population):
        params, test_image = random_test()
        fitness_score = fitness(optimal, test_image)

        if fitness_score > scores[-1]:
            scores[-1] = fitness_score
            scores = sorted(scores)

            samples.append(params)

    for generation in range(generations):
        seeds = numpy.array(copy.deepcopy(samples))[0]
        samples = []
        scores = [0] * reproduce

        for i in range(population):
            params, test_image = seed_test(seeds[:random.randint(0, reproduce)])
            fitness_score = fitness(optimal, test_image)

            if fitness_score > scores[-1]:
                scores[-1] = fitness_score
                scores = sorted(scores)

                samples.append(params)

        for each in samples:
            print each

if __name__ == "__main__":
    generate()

源图可以在here找到。

错误是什么意思?

【问题讨论】:

  • 快速提问从for i in range(height - 1): for j in range(width - 1): 中删除-1 部分会发生什么?
  • 如果您正在谈论将它们从适应度函数中删除,则没有任何反应,错误仍然存​​在。
  • 对不起,我没有阅读堆栈跟踪,所以我正在查看您的循环,看看是否有任何问题,我将专注于 generateseed_test 代码,打印长度和内容的参数,看看它们是否看起来有效

标签: python numpy genetic-algorithm


【解决方案1】:

您有 1000 个 elements (1e3) 和 22 个 seeds(索引 0 - 21),因此当您尝试在以下循环中获取项目 seeds[22, 0] 时,索引超出范围:

for i in range(elements):
    r = int(seeds[i, 0] ...

我怀疑你需要做的是:

for i in range(len(seeds)):
    ...

【讨论】:

  • 谢谢先生。这个脚本是对我找到的另一个脚本的改编,我仍在努力解决其中的问题。
【解决方案2】:

在您的代码中,您将全局 elements 设置为 100,为什么不将其设置为 len(elements)?目前,如果种子估值器少于 100 个,那么算法 id 保证会按照您描述的方式失败。

当前解决方案尝试的一个问题是,各种函数之间的大部分“耦合”都是通过全局变量进行的。在 Python 中,我们喜欢说“隐式优于显式”,最好的软件工程实践是将数据显式传递给使用它的那些函数。

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多