是否可以在 Keras 中将 image_dataset_from_directory() 与卷积自动编码器一起使用?

Is it possible to use image_dataset_from_directory() with convolutional autoencoders in Keras?

有一个类似的问题 here 询问如何将 image_dataset_from_directory() 与自动编码器一起使用。问题实际上没有答案,因为答案建议使用其他东西。

我的问题是,是否可以在 Keras 中使用 image_dataset_from_directory() 作为卷积自动编码器的输入?

这是绝对有可能的,你只需要事先调整你的模型输入:

import tensorflow as tf
import pathlib

dataset_url = "https://storage.googleapis.com/download.tensorflow.org/example_images/flower_photos.tgz"
data_dir = tf.keras.utils.get_file('flower_photos', origin=dataset_url, untar=True)
data_dir = pathlib.Path(data_dir)

batch_size = 32

train_ds = tf.keras.utils.image_dataset_from_directory(
  data_dir,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(28, 28),
  batch_size=batch_size)

normalization_layer = tf.keras.layers.Rescaling(1./255)

def change_inputs(images, labels):
  x = tf.image.resize(normalization_layer(images),[28, 28], method=tf.image.ResizeMethod.NEAREST_NEIGHBOR)
  return x, x

normalized_ds = train_ds.map(change_inputs)

input_img = tf.keras.Input(shape=(28, 28, 3))
x = tf.keras.layers.Flatten()(input_img)
x = tf.keras.layers.Dense(28 * 28 * 3, activation='relu')(x)
output = tf.keras.layers.Reshape(target_shape=(28, 28 ,3))(x)
autoencoder = tf.keras.Model(input_img, output)

autoencoder.compile(optimizer='adam', loss='mse')

history = autoencoder.fit(normalized_ds, epochs=2)
Found 3670 files belonging to 5 classes.
Using 2936 files for training.
Epoch 1/2
92/92 [==============================] - 4s 41ms/step - loss: 0.1538
Epoch 2/2
92/92 [==============================] - 4s 40ms/step - loss: 0.1300

请注意,我使用了一个完全连接的神经层作为编码器和解码器,但它们很容易被 CNN 网络取代。我还将图像缩小到更小的尺寸以便快速演示。