【问题标题】:Randomly augmenting images using Keras使用 Keras 随机增强图像
【发布时间】:2018-02-24 15:53:07
【问题描述】:

我正在尝试使用 MNIST 数据集来学习 Keras 库。在 MNIST 中,有 60k 个训练图像和 10k 个验证图像。

在这两个集合中,我想对 30% 的图像进行增强。

datagen = ImageDataGenerator(horizontal_flip=True, vertical_flip=True)
datagen.fit(training_images)
datagen.fit(validation_images)

这不会增加图像,我不确定如何使用model.fit_generator 方法。我目前的model.fit如下:

model.fit(training_images, training_labels, validation_data=(validation_images, validation_labels), epochs=10, batch_size=200, verbose=2)

如何在此数据集中的某些图像上应用增强?

【问题讨论】:

  • 您想对两个数据集应用增强还是仅对其中的 30% 应用增强?
  • 在两者上(训练、验证),但不想将其应用于所有这些。希望保持约 70% 的数据集不变。
  • 您想要为每个 epoch 增加不同的 30% 的图像,还是固定 30% 的图像?
  • 30% 只是为了暗示我想要修改数据集的一小部分。我同意“固定 30% 的图像”,但“每个时期增加 30% 的不同图像”听起来更好!

标签: python image-processing neural-network keras mnist


【解决方案1】:

我会尝试通过以下方式定义我自己的生成器:

from sklearn.model_selection import train_test_split
from six import next

def partial_flow(array, flags, generator, aug_percentage, batch_size):
    # Splitting data into arrays which will be augmented and which won't
    not_aug_array, not_aug_flags, aug_array, aug_flags = train_test_split(
        array,
        test_size=aug_percentage)
    # Preparation of generators which will be used for augmentation.
    aug_split_size = int(batch_size * split_size)
    # We will use generator without any augmentation to yield not augmented data
    not_augmented_gen = ImageDataGenerator()
    aug_gen = generator.flow(
        x=aug_array,
        y=aug_flags,
        batch_size=aug_split_size)
    not_aug_gen = not_augmented_gen.flow(
        x=not_aug_array,
        y=not_aug_flags,
        batch_size=batch_size - aug_split_size)
    # Yiedling data
    while True:
        # Getting augmented data
        aug_x, aug_y = next(aug_gen)
        # Getting not augmented data
        not_aug_x, not_aug_y = next(not_aug_gen)
        # Concatenation
        current_x = numpy.concatenate([aug_x, not_aug_x], axis=0)
        current_y = numpy.concatenate([aug_y, not_aug_y], axis=0)
        yield current_x, current_y

现在您可以通过以下方式进行训练:

 batch_size = 200
 model.fit_generator(partial_flow(training_images, training_labels, 0.7, batch_size),
                     steps_per_epoch=int(training_images.shape[0] / batch_size),
                     epochs=10,
                     validation_data=partial_flow(validation_images, validation_labels, 0.7, batch_size),
                     validation_steps=int(validation_images.shape[0] / batch_size))

【讨论】:

  • 感谢您添加 cmets!出于某种原因,我在训练模型时遇到了这个异常:pastebin.com/raw/7KyEBv2u
  • @Marcin 我错过了什么吗? partial_flow 函数调用中的参数生成器呢?
  • 哪个参数?你的意思是fit函数的参数?
  • 我的意思是这里partial_flow(training_images, training_labels, 0.7, batch_size) 没有生成器通过na?但该功能需要一个partial_flow(array, flags, generator, aug_percentage, batch_size)
猜你喜欢
  • 2023-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-25
  • 1970-01-01
  • 1970-01-01
  • 2022-08-21
  • 1970-01-01
相关资源
最近更新 更多