Keras: fit_generator中如何构建一个generator?

版权声明:本文系作者原创,未经允许,禁止转载。 https://blog.csdn.net/qq_27261889/article/details/83698334

为何使用fit_generator?

在深度学习中,我们数据通常会很大,即使在使用GPU的情况下,我们如果一次性将所有数据(如图像)读入CPU的内存中,内存很有可能会奔溃。这在实际的项目中很有可能会出现。
如果我们使用fit_generator则可以解决这个问题:
1)fit_generator的参数中有一个是连续不断的产生数据的函数,被称为generator。
2)至于这个generator是怎么产生的,本文不想多说。本文只想告诉大家怎么来构建一个实际的generator。

实际的generator例子

import json
import os
import numpy as np
import cv2
from sklearn.utils import shuffle

def cv_imread(filePath):
    cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1)

    return cv_img

def load_train(train_path, width, height, batch_size):
    classes = np.zeros(61)
    root = os.getcwd()
    with open(train_path, 'r') as load_f:
        load_dict = json.load(load_f)
        start = 0
        end = batch_size
        num_epochs = 0
        while True:
            images = []
            labels = []
            number = np.random.random_integers(0, len(load_dict)-1, batch_size)
            for image in number:
                index = load_dict[image]["disease_class"]
                path = load_dict[image]['image_id']
                img_path = os.path.join(root, 'new_train', 'images', path)
                image_data = cv_imread(img_path)
                image_data = cv2.resize(image_data, (width, height), 0, 0, cv2.INTER_LINEAR)
                image_data = image_data.astype(np.float32)
                image_data = np.multiply(image_data, 1.0 / 255.0)
                images.append(image_data)
                label = np.zeros(len(classes))
                label[index] = 1
                labels.append(label)
            images = np.array(images)
            labels = np.array(labels)
            yield images, labels

def load_validate(validate_path, width, height):
    root = os.getcwd()
    with open(validate_path, 'r') as load_f:
        load_dict = json.load(load_f)

        # num_image = len(load_dict)
        # 只产生512个数据,避免内存过大
        while True:
            images = []
            labels = []
            classes = np.zeros(61)
            number = np.random.random_integers(0, len(load_dict) - 1, 512)

            for image in number:
                index = load_dict[image]["disease_class"]
                path = load_dict[image]['image_id']
                img_path = os.path.join(root, 'AgriculturalDisease_validationset', 'images', path)
                image_data = cv_imread(img_path)
                image_data = cv2.resize(image_data, (width, height), 0, 0, cv2.INTER_LINEAR)
                image_data = image_data.astype(np.float32)
                image_data = np.multiply(image_data, 1.0 / 255.0)

                images.append(image_data)
                label = np.zeros(len(classes))
                label[index] = 1
                labels.append(label)
            images = np.array(images)
            labels = np.array(labels)

            yield images, labels

以上是切实可行的程序。这里对上面的程序做一个说明:
1)注意到函数中使用yield返回数据
2)注意到函数使用while True 来进行循环,目前可以认为这是一个必要的部分,这个函数不停的在while中进行循环
3)由于是在while中进行循环,我们需要在while中进行设置初始化,而不要在while循环外进行初始化;我刚开始在load_validate函数中没有初始化 images = []和labels = [],导致程序出错。因为我在while循环中最后将这两个数据都变成了numpy的数据格式,当进行第二轮数据产生时,numpy的数据格式是没有append的函数的,所以会出错。
4)程序中具体的数据运算不需要太多了解,不过这里给出一个简单的说明,以助于理解:在train数据中,我试图从一个很大的图片数据库中随机选择batch_size个图片,然后进行resize变换。这是一张图片的过程。为了读取多张图片,我是先将每一个图片都读入一个列表中,这是为了使用列表的append这个追加数据的功能(我觉得这个功能其实挺好用的),最后,把要训练的一个batch数据转成numpy的array格式。
5)除了while True 和 yield,大家留意一下这里的循环和初始化,比较容易出错。

最后,这里也给出这个程序的一些参数设置

个人觉得这里的参数设置还是不太方便的,需要注意一下。
1)首先,对于train中的数据,batch是从主函数中读进来的。
下面是fit_generator调用设置

times = 3070
batch_size = 64
model.fit_generator(load_data.load_train(train_path, img_rows, img_cols, batch_size=batch_size),
                    steps_per_epoch=times,
                    verbose=1,
                    epochs=100,
                    validation_data=load_data.load_validate(validate_path, img_rows, img_cols),
                    validation_steps=1,
                    shuffle=True)

先说一下,我的数据数量:训练集共196434张图片,验证集共4095张图片。
我这里主要说一下训练集的设置,因为验证集我还没有仔细的思考。
由于我的GPU数量只是1,所以我只是讲batch_size设置为64,所以需要从196434/63=3070次才能将整个数据库平均取一次。而epochs设置为100,意味着我将这个轮回设置成了100,。

以上有不对的地方,或者可以改进的地方,请各位不吝指教。

猜你喜欢

转载自blog.csdn.net/qq_27261889/article/details/83698334