使用Keras随机增强图像

4

我正在尝试使用MNIST数据集来学习Keras库。在MNIST中,有60000张训练图像和10000张验证图像。

在这两个集合中,我想对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%的数据集进行增强? - Marcin Możejko
在训练和验证集上都要使用,但不想在所有数据集上应用它。希望保留约70%的数据集不变。 - Grimlock
你想要每个epoch都增强不同的30%图像,还是固定增强30%的图像? - Yu-Yang
只修改数据集的一小部分,大约30%左右。我可以接受“修复30%的图像”,但是“每个时期增强不同30%的图像”听起来更好! - Grimlock
1个回答

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

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

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))

感谢您添加评论!不知何故,当我训练模型时出现了这个异常:https://pastebin.com/raw/7KyEBv2u - Grimlock
@Marcin 我有什么遗漏吗?在 partial_flow 函数调用中,参数生成器怎么办? - Bharath M Shetty
哪个参数?你是指 fit 函数的参数吗? - Marcin Możejko
我是说这里 partial_flow(training_images, training_labels, 0.7, batch_size) 没有传递生成器,是吗?但是该函数需要一个 partial_flow(array, flags, generator, aug_percentage, batch_size) - Bharath M Shetty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接