繁体   English   中英

生成器 function:要解包的值太多(预期为 2)

[英]Generator function: Too many values to unpack (expected 2)

我创建了一个自定义生成器,它产生一个corrupted_image的图像和original_image图像的元组:

def custom_image_generator(files, data_instances, batch_size = 64):

    iter = 0
    num_batches = data_instances / batch_size
    while True:

        iter = iter % num_batches

        batch_input = []
        proc_batch = []

        start = random.randint(0, data_instances - batch_size)
        for index in range(start, start + batch_size):
            original_image = Image.open(files[index])
            corrupted_image = draw_square_on_image(files[index])
            batch_input.append(original_image)
            proc_batch.append(corrupted_image)

        corrupted_images_batch = np.array(proc_batch)
        original_images_batch = np.array(batch_input)

        iter = iter + 1

        yield (corrupted_images_batch, original_images_batch)

如果我这样称呼这个生成器:

(corrupted_images_batch, orig_images_batch) = next(test_generator)

它返回预期的 output 即两个批次中的 64 个图像。 为了训练我的 model,我需要遍历整个批次。

但是,如果我尝试做类似的事情:

for (corrupted_images_batch, orig_images_batch) in next(test_generator):
    print(corrupted_images_batch)

我收到一个错误: ValueError: too many values to unpack (expected 2)

正如(corrupted_images_batch, orig_images_batch) = next(test_generator)所证明的那样, next(test_generator)是一个 2 元组,因此您不能循环将每个元素解压缩为 2 元组。

您正在寻找的是:

for (corrupted_images_batch, orig_images_batch) in test_generator:
    print(corrupted_images_batch)

这样你就可以循环生成器,而不仅仅是生成的下一个元素。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM