Search code examples
pythonnumpyconv-neural-networkautoencoder

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


I have created a custom generator that yields a tuple of corrupted_image and original_image.

If I call this generator like this:

(corrupted_images_batch, orig_images_batch) = next(test_generator)

It returns the expected output i.e 64 images in both the batches. For training my model I need to iterate over the entire batch.

But if I try doing something like:

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

I get an error: ValueError: too many values to unpack (expected 2).


Solution

  • As demonstrated by (corrupted_images_batch, orig_images_batch) = next(test_generator), next(test_generator) is a 2-tuple, so you can't loop over it unpacking each element into a 2-tuple.

    What you're looking for is:

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

    This way you're looping over the generator, not just the next element generated.