我如何在整个数据集上应用数据扩充

How do i apply Data Augmentation on entire data-set

enter image description here

大家好,我是机器学习的新手,正在尝试学习它。我尝试在我的数据集上进行数据扩充。我从 keras 网站获得了这段代码,但这段代码一次只选择一张图片。我希望此代码从数据集中一张一张地挑选图像并对其应用增强技术。我对要更改的内容感到困惑。如果有人帮助我,我将不胜感激。

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

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 > 20:

        break  # otherwise the generator would loop indefinitely

我假设您的 data/train/cats/ 文件夹中有数据集。现在,根据上面的代码,它读取单个图像,对该单个图像运行扩充,并生成 20 个不同的图像。

现在,要扩展该过程,您可以简单地使用 osglob 模块从目录中获取文件列表。然后遍历你的代码块。例如:

import glob

list_of_files = glob.glob('data/train/cats/*.jpg')
for file in list_of_files:
  img = load_img(file)  # this is a PIL image
  x = img_to_array(img)  # this is a Numpy array with shape (3, 150, 150)
  .
  .
  .

您可以更多地利用 datagen.flow 而不是遍历整个代码块,即您可以传递整个数据集,而不是将单个图像作为 x 传递。例如,如果 n 是图像总数,假设所有图像大小相同,您的 x 形状将看起来像 (n,3,150,150)

此外,您可以改变此 n 值。即不选择总数据集长度。在那种情况下,假设 n 值为 20,在第一次迭代中,您将首先读取 20 个图像并像 (20,3,150,150) 一样传递 x。然后在第二次迭代中,您阅读下一个 20 等等。

例如,

import glob
import numpy as np

x = []
list_of_files = glob.glob('data/train/cats/*.jpg')
for file in list_of_files:
  img = load_img(file)  # this is a PIL image
  x.append(img_to_array(img))
x = np.array(x) # feed this x to your datagen.flow

# print(x.shape)
# (n, 3, 150, 150)

# (Note: n is the length of list_of_files, i.e. total dataset length)