How to fit an autoencoder using flow_from_directory

Viewed 497

I'm building out a basic autoencoder and using the keras documentation here as a guide: https://blog.keras.io/building-autoencoders-in-keras.html.

I'm getting stuck and switching it to be able to fit from a flow_from_directory object, here's the one I've set up:

data_gen = tf.keras.preprocessing.image.ImageDataGenerator()

train_generator = data_gen.flow_from_directory(
    directory= 'train_images',
    target_size=(28, 28),
    color_mode="rgb",
    batch_size=128,
    shuffle=True,
    seed=42,
    class_mode=None,
)

I'm trying to fit the model (which is more or less the same as the one in the keras documentation using this code:

autoencoder.fit(train_generator, train_generator,
                epochs=500,
                shuffle=True)

However, the problem is that passing it in like this gives me this error:

`ValueError: `y` argument is not supported 

I think maybe this is saying that I can't specify a y if my x comes from a flow_for_directory, which makes sense, but how can I specify labels to be the same the data-itself?

2 Answers

Putting the answer here in case it helps anyone else. As Frightera suggested in the comments, changing the class_mode to 'input' solved this problem:

data_gen = tf.keras.preprocessing.image.ImageDataGenerator()

train_generator = data_gen.flow_from_directory(
    directory= 'train_images',
    target_size=(28, 28),
    color_mode="rgb",
    batch_size=128,
    shuffle=True,
    seed=42,
    class_mode='input',
)

autoencoder.fit(train_generator,
                epochs=500,
                shuffle=True)

Try modifying your fit function:

autoencoder.fit(train_generator,
            epochs=500,
            shuffle=True)

You were using train_generator twice, when you are using ImageDataGenerator.flow_from_directory function it returns a DirectoryIterator yielding tuples of (x, y) where x is a numpy array containing batches of data and y is a numpy array of corresponding labels.

Please refer to the Keras docs: https://keras.io/api/preprocessing/image/#flowfromdirectory-method

Related