【问题标题】:Data augmentation in Keras modelKeras 模型中的数据增强
【发布时间】:2022-08-05 11:35:22
【问题描述】:

我正在尝试将数据增强作为一个层添加到模型中,但出现以下错误。

TypeError: The added layer must be an instance of class Layer. Found: <tensorflow.python.keras.preprocessing.image.ImageDataGenerator object at 0x7f8c2dea0710>

data_augmentation = tf.keras.preprocessing.image.ImageDataGenerator(
   rotation_range=30, horizontal_flip=True)

model = Sequential()
model.add(data_augmentation)
model.add(Dense(1028,input_shape=(final_features.shape[1],)))
model.add(Dropout(0.7,input_shape=(final_features.shape[1],)))
model.add(Dense(n_classes, activation= \'softmax\', kernel_regularizer=\'l2\'))
model.compile(optimizer=adam,
              loss=\'categorical_crossentropy\',
              metrics=[\'accuracy\'])

history = model.fit(final_features, y,
            batch_size=batch_size,
            epochs=epochs,
            validation_split=0.2,
            callbacks=[lrr,EarlyStop]) 

我也尝试过这种方式:


    data_augmentation = Sequential(
      [
        preprocessing.RandomFlip(\"horizontal\"),
        preprocessing.RandomRotation(0.1),
        preprocessing.RandomZoom(0.1),
      ]
    )
    model = Sequential()
    model.add(data_augmentation)
    model.add(Dense(1028,input_shape=(final_features.shape[1],)))
    model.add(Dropout(0.7,input_shape=(final_features.shape[1],)))
    model.add(Dense(n_classes, activation= \'softmax\', kernel_regularizer=\'l2\'))
    model.compile(optimizer=adam,
                  loss=\'categorical_crossentropy\',
                  metrics=[\'accuracy\'])
    history = model.fit(final_features, y,
                batch_size=batch_size,
                epochs=epochs,
                validation_split=0.2,
                callbacks=[lrr,EarlyStop])

它给出了一个错误:


    ValueError: Input 0 of layer sequential_7 is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [128, 14272]

您能否建议我如何在 Keras 中使用增强功能?

    标签: keras data-augmentation


    【解决方案1】:

    在您的第一种情况下,您使用ImageDataGenerator 作为层,这不是:顾名思义,它只是一个将随机变换应用于图像的生成器(图像增强)喂给网络。因此,图像在 CPU 中增强,然后馈送到可以在 GPU 中运行的神经网络(如果有的话)。

    生成器通常也用于避免将大量数据集加载到内存中,因为它们只允许加载即将使用的批次。

    在第二种情况下,您正确地使用图像增强作为模型的层。这里的不同之处在于,增强是作为模型的一部分运行的,所以如果你有一个可用的 GPU,那么这些操作将在 GPU 中运行。

    第二种情况的问题在于模型本身(实际上模型在第一种方法中也是错误的,在执行到达模型之前,您只会在错误使用 ImageDataGenerator 时出现错误)。

    请注意,您使用图像作为输入,因此输入的形状应为(height, width, channels),但随后您将使用密集层启动模型,该层需要一个形状为(n_features,) 的数组。

    如果您的模型需要从密集层开始(奇怪,但在某些情况下可能还可以),那么您需要首先使用Flatten 层将形状为(h,w,c) 的图像转换为形状为(h*w*c,) 的向量。此更改肯定会解决您的第二种方法。

    也就是说,您不需要在每一层上指定输入形状:在第一层中执行就足够了。

    最后但并非最不重要的一点是:你确定这个模型是用图像提供的吗?根据您的fit 电话,您似乎正在使用以前提取的可能是向量的特征(这对您当前的模型架构有意义,但对使用图像增强没有意义)。

    请提供有关您的数据的更多详细信息以澄清这一点。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-02
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      相关资源
      最近更新 更多