Keras 数据扩充参数

Keras Data Augmentation Parameters

我阅读了一些关于 Keras 数据增强的材料,但对我来说仍然有点模糊。在数据增强步骤中是否有任何参数来控制从每个输入图像创建的图像数量?在 this example 中,我看不到任何控制从每个图像创建的图像数量的参数。

例如,在下面的代码中,我可以有一个参数 (num_imgs) 来控制从每个输入图像创建并存储在名为 preview 的文件夹中的图像数量;但是在实时数据增强中没有任何参数用于此目的。

from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
num_imgs = 20
datagen = ImageDataGenerator(
        rotation_range=40,
        width_shift_range=0.2,
        height_shift_range=0.2,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True,
        fill_mode='nearest')

img = load_img('data/train/cats/cat.0.jpg')  # this is a PIL image
x = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
x = x.reshape((1,) + x.shape)  # this is a Numpy array with shape (1, 3, 150, 150)

# the .flow() command below generates batches of randomly transformed images
# and saves the results to the `preview/` directory
i = 0
for batch in datagen.flow(x, batch_size=1,
                          save_to_dir='preview', save_prefix='cat', save_format='jpeg'):
    i += 1
    if i > num_imgs:
        break  # otherwise the generator would loop indefinitely

基本上是这样的,它只为每个输入图像生成一张图像,所有输入图像都生成一次后,它会重新开始。

在你的例子中,因为总共只有一张输入图像,它会重复生成该图像的不同版本,直到有二十张。

你可以在这里查看源代码https://github.com/fchollet/keras/blob/master/keras/preprocessing/image.py

数据扩充的工作原理如下:在每个学习时期,在指定范围内随机选择参数的变换应用于训练集中的所有原始图像。在一个时期完成后,即在将学习算法暴露于整个训练数据集之后,下一个学习时期开始,并通过对原始训练数据应用指定的转换再次扩充训练数据。

这样一来,每张图像被增强的次数就等于学习时期的数量。召回表格 the example that you linked:

# Fit the model on the batches generated by datagen.flow().
model.fit_generator(datagen.flow(X_train, Y_train,
                    batch_size=batch_size),
                    samples_per_epoch=X_train.shape[0],
                    nb_epoch=nb_epoch,
                    validation_data=(X_test, Y_test))

这里 datagen 对象会将训练集暴露给 model nb_epoch 次,因此每个图像都会被扩充 nb_epoch 次。通过这种方式,学习算法几乎永远不会看到两个完全相同的训练示例,因为在每个 epoch 训练示例都是随机变换的。