【问题标题】:ImageDataGenerator() for CNN with input and output as an Image用于 CNN 的 ImageDataGenerator(),输入和输出为图像
【发布时间】:2020-11-01 16:04:00
【问题描述】:

我正在寻找这样的训练地图:

灰度图像 -> 彩色图像

但是由于明显的原因,不能将数据集作为 X 和 Y 全部加载到内存中。

我查看了 ImageDataGenerator() 库,但它没有给我一个明确的答案,让它在这里工作。

总结:

输入形状 = (2048, 2048, 1)

输出形状 = (2048, 2048, 2)

训练数据集 = 17,000 张图像

验证数据集 = 1,000 张图片

这是我正在尝试训练的模型的结构:

Model: "functional_1"
__________________________________________________________________________________________________
Layer (type)                    Output Shape         Param #     Connected to                     
==================================================================================================
input_1 (InputLayer)            [(None, 2048, 2048,  0                                            
__________________________________________________________________________________________________
conv2d (Conv2D)                 (None, 2048, 2048, 1 160         input_1[0][0]                    
__________________________________________________________________________________________________
leaky_re_lu (LeakyReLU)         (None, 2048, 2048, 1 0           conv2d[0][0]                     
__________________________________________________________________________________________________
conv2d_1 (Conv2D)               (None, 2048, 2048, 3 4640        leaky_re_lu[0][0]                
__________________________________________________________________________________________________
leaky_re_lu_1 (LeakyReLU)       (None, 2048, 2048, 3 0           conv2d_1[0][0]                   
__________________________________________________________________________________________________
batch_normalization (BatchNorma (None, 2048, 2048, 3 128         leaky_re_lu_1[0][0]              
__________________________________________________________________________________________________
max_pooling2d (MaxPooling2D)    (None, 1024, 1024, 3 0           batch_normalization[0][0]        
__________________________________________________________________________________________________
conv2d_2 (Conv2D)               (None, 1024, 1024, 6 18496       max_pooling2d[0][0]              
__________________________________________________________________________________________________
leaky_re_lu_2 (LeakyReLU)       (None, 1024, 1024, 6 0           conv2d_2[0][0]                   
__________________________________________________________________________________________________
batch_normalization_1 (BatchNor (None, 1024, 1024, 6 256         leaky_re_lu_2[0][0]              
__________________________________________________________________________________________________
max_pooling2d_1 (MaxPooling2D)  (None, 512, 512, 64) 0           batch_normalization_1[0][0]      
__________________________________________________________________________________________________
conv2d_3 (Conv2D)               (None, 512, 512, 128 73856       max_pooling2d_1[0][0]            
__________________________________________________________________________________________________
leaky_re_lu_3 (LeakyReLU)       (None, 512, 512, 128 0           conv2d_3[0][0]                   
__________________________________________________________________________________________________
batch_normalization_2 (BatchNor (None, 512, 512, 128 512         leaky_re_lu_3[0][0]              
__________________________________________________________________________________________________
conv2d_4 (Conv2D)               (None, 512, 512, 256 295168      batch_normalization_2[0][0]      
__________________________________________________________________________________________________
leaky_re_lu_4 (LeakyReLU)       (None, 512, 512, 256 0           conv2d_4[0][0]                   
__________________________________________________________________________________________________
batch_normalization_3 (BatchNor (None, 512, 512, 256 1024        leaky_re_lu_4[0][0]              
__________________________________________________________________________________________________
up_sampling2d (UpSampling2D)    (None, 1024, 1024, 2 0           batch_normalization_3[0][0]      
__________________________________________________________________________________________________
conv2d_5 (Conv2D)               (None, 1024, 1024, 1 295040      up_sampling2d[0][0]              
__________________________________________________________________________________________________
leaky_re_lu_5 (LeakyReLU)       (None, 1024, 1024, 1 0           conv2d_5[0][0]                   
__________________________________________________________________________________________________
batch_normalization_4 (BatchNor (None, 1024, 1024, 1 512         leaky_re_lu_5[0][0]              
__________________________________________________________________________________________________
up_sampling2d_1 (UpSampling2D)  (None, 2048, 2048, 1 0           batch_normalization_4[0][0]      
__________________________________________________________________________________________________
conv2d_6 (Conv2D)               (None, 2048, 2048, 6 73792       up_sampling2d_1[0][0]            
__________________________________________________________________________________________________
leaky_re_lu_6 (LeakyReLU)       (None, 2048, 2048, 6 0           conv2d_6[0][0]                   
__________________________________________________________________________________________________
concatenate (Concatenate)       (None, 2048, 2048, 6 0           leaky_re_lu_6[0][0]              
                                                                 input_1[0][0]                    
__________________________________________________________________________________________________
conv2d_7 (Conv2D)               (None, 2048, 2048, 6 37504       concatenate[0][0]                
__________________________________________________________________________________________________
leaky_re_lu_7 (LeakyReLU)       (None, 2048, 2048, 6 0           conv2d_7[0][0]                   
__________________________________________________________________________________________________
batch_normalization_5 (BatchNor (None, 2048, 2048, 6 256         leaky_re_lu_7[0][0]              
__________________________________________________________________________________________________
conv2d_8 (Conv2D)               (None, 2048, 2048, 3 18464       batch_normalization_5[0][0]      
__________________________________________________________________________________________________
leaky_re_lu_8 (LeakyReLU)       (None, 2048, 2048, 3 0           conv2d_8[0][0]                   
__________________________________________________________________________________________________
conv2d_9 (Conv2D)               (None, 2048, 2048, 2 578         leaky_re_lu_8[0][0]              
==================================================================================================
Total params: 820,386
Trainable params: 819,042
Non-trainable params: 1,344
__________________________________________________________________________________________________

【问题讨论】:

  • 您需要批量训练模型。例如,如果您想在 1 个 epoch 中使用 500 张图像,则可以每批 50 张图像和 10 个 epoch 代替。这样,您只需在内存中加载 50 张图像。您必须设置批次大小并将 shuffle 设置为 True,以便您的批次具有不同的图像。检查我的文档,如果不清楚,我稍后会尝试发布一些内容
  • 你能把你的问题缩小到几个你可以在这里分享的代码行吗?目前,对于您的问题有什么可能的解决方案完全不明显。

标签: python tensorflow image-processing keras conv-neural-network


【解决方案1】:

使用自定义训练循环将是最简单的。

def reconstruct(colored_inputs):
    with tf.GradientTape() as tape:
        grayscale_inputs = tf.image.rgb_to_grayscale(colored_inputs)

        out = autoencoder(grayscale_inputs)
        loss = loss_object(colored_inputs, out)

    gradients = tape.gradient(loss, autoencoder.trainable_variables)
    optimizer.apply_gradients(zip(gradients, autoencoder.trainable_variables))

    reconstruction_loss(loss)

在这里,我的数据迭代器循环遍历所有彩色图片,但在传递给模型之前将其转换为灰度。然后,将模型的 RGB 输出与原始 RGB 图像进行比较。您将不得不在flow_from_directory 中使用参数class_mode=None。我使用tf.image.rgb_to_grayscale进行灰度和RGB的转换。

完整示例:

import tensorflow as tf
physical_devices = tf.config.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)
import os

os.chdir(r'catsanddogs')

generator = tf.keras.preprocessing.image.ImageDataGenerator()
iterator = generator.flow_from_directory(
    target_size=(32, 32),
    directory='.',
    batch_size=4,
    class_mode=None)

encoder = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(32, 32, 1)),
    tf.keras.layers.Dense(32),
    tf.keras.layers.Dense(16)
])

decoder = tf.keras.Sequential([
    tf.keras.layers.Dense(32, input_shape=[16]),
    tf.keras.layers.Dense(32 * 32 * 3),
    tf.keras.layers.Reshape([32, 32, 3])
])


autoencoder = tf.keras.Sequential([encoder, decoder])

loss_object = tf.losses.BinaryCrossentropy()

reconstruction_loss = tf.metrics.Mean(name='reconstruction_loss')

optimizer = tf.optimizers.Adam()


def reconstruct(colored_inputs):
    with tf.GradientTape() as tape:
        grayscale_inputs = tf.image.rgb_to_grayscale(colored_inputs)

        out = autoencoder(grayscale_inputs)
        loss = loss_object(colored_inputs, out)

    gradients = tape.gradient(loss, autoencoder.trainable_variables)
    optimizer.apply_gradients(zip(gradients, autoencoder.trainable_variables))

    reconstruction_loss(loss)


if __name__ == '__main__':
    template = 'Epoch {:2} Reconstruction Loss {:.4f}'
    for epoch in range(50):
        reconstruction_loss.reset_states()
        for input_batches in iterator:
            reconstruct(input_batches)
        print(template.format(epoch + 1, reconstruction_loss.result()))

【讨论】:

    【解决方案2】:

    我将使用示例代码发表我的评论:

    您需要批量训练模型。例如,如果您想在 1 个 epoch 中使用 500 张图像,则可以每批 50 张图像和 10 个 epoch 代替。这样,您只需在内存中加载 50 张图像。您必须设置批次大小并将 shuffle 设置为 True,以便您的批次具有不同的图像。

    如果您的图片在目录中,则上面的评论会翻译成如下内容:

    from keras_preprocessing.image import ImageDataGenerator
    preprocessing_images = ImageDataGenerator()
    
    train_generator = preprocessing_images.flow_from_directory(
            train_path,
            target_size=target_size,
            batch_size=50,
            class_mode="categorical", # classes are provided in categorical format for a 2-unit output layer
            shuffle=True,
            color_mode="grayscale",
            seed=1234567890
        )
    

    您有一个生成器,可以生成 50 张图像的批次。我没有为您的具体问题指定参数,您需要更改 target_size 和所有这些东西。请注意,这是一个无限生成器,它将返回无限数量的包含 50 张图像的批次。您可以将其包装到 tf.data.Dataset 或指定每个时期的步骤。有几种方法。我希望它有所帮助。稍微处理一下,如果还有问题,我会详细说明答案(我现在很忙)

    【讨论】:

    • 我尝试了这种方法,但我的模型类似于自动编码器。此方法适用于分类问题。唯一的区别是我的模型是监督模型。
    • 数据是否分类无关紧要,但不确定您对自动编码器的看法。你能展示你当前对模型的输入吗?假设您的代码没有内存大小问题来查看它
    猜你喜欢
    • 2020-04-16
    • 2018-12-15
    • 2019-03-31
    • 2019-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    相关资源
    最近更新 更多