【问题标题】:Is it possible to use image_dataset_from_directory() with convolutional autoencoders in Keras?是否可以在 Keras 中将 image_dataset_from_directory() 与卷积自动编码器一起使用?
【发布时间】:2021-12-17 02:09:30
【问题描述】:

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

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

【问题讨论】:

    标签: python tensorflow keras deep-learning tensorflow-datasets


    【解决方案1】:

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

    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 网络取代。为了快速演示,我还将图像缩小到更小的尺寸。

    【讨论】:

    • 所以如果我理解正确的话,必要的更改是return x, x,换句话说,我应该使标签与输入相同,x == y?
    • 是的,你理解正确。
    • 非常感谢,这让我困扰了几天。几年来我在这个领域并不是很活跃,现在我正在努力追赶,有很多新的东西和抽象,尤其是 Keras(当我使用 NN 时它才 2 岁,甚至那时我用的是纯TF)。
    • 当然可以,但我不知道该怎么做。如果可以,请成为我的客人。
    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 2020-06-11
    • 2017-01-04
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 2018-09-08
    相关资源
    最近更新 更多