在深度学习中,我们经常需要用到一些技巧(比如将图片进行旋转,翻转等)来进行data augmentation, 来减少过拟合。 在本文中,我们将主要介绍如何用深度学习框架keras来自动的进行data augmentation。
现在让我们来看一个例子:
@requires_authorization
from keras.preprocessing.image import ImageDataGenerator
datagen = ImageDataGenerator(
rotation_range=40,
width_shift_range=0.2,
height_shift_range=0.2,
rescale=1./255,
shear_range=0.2,
zoom_range=0.2,
horizontal_flip=True,
fill_mode='nearest',
cval=0,
channel_shift_range=0,
horizontal_flip=False,
vertical_flip=False,
rescale=None)
下面我们使用这个工具来生成图片,并将它们保存在一个临时文件夹中
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
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/cat.jpg') # 这是一个PIL图像
x = img_to_array(img) # 把PIL图像转换成一个numpy数组,形状为(3, 150, 150)
x = x.reshape((1,) + x.shape) # 这是一个numpy数组,形状为 (1, 3, 150, 150)
# 下面是生产图片的代码
# 生产的所有图片保存在 `preview/` 目录下
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 > 50:
break # 否则生成器会退出循环
flow(self, X, y, batch_size=32, shuffle=True, seed=None, save_to_dir=None, save_prefix=”, save_format=’jpeg’):接收numpy数组和标签为参数,生成经过数据提升或标准化后的batch数据,并在一个无限循环中不断的返回batch数据.
源代码 [ code]
更多关于keras 图片生成器的部分详见 [ ImageDataGenerator ]