python - 从 CSV 加载图像和注释,并将 fit_generator 与多输出模型结合使用

标签 python keras

已关注 issue #10120 ,我使用 Keras 功能 API 构建具有多个(五个)输出和相同输入的模型,以便同时预测数据的不同属性(在我的例子中是图像)。数据集的所有元数据都存储在不同的 CSV 文件中(一个用于训练,一个用于验证,一个用于测试数据)。

aaa.png

我已经编写了代码来解析 CSV 并将所有不同的注释保存到不同的 numpy 数组(x_train.npy、emotions.npy 等)中,稍后我将加载这些数组以训练我的 CNN。

<小时/>

我想提出的问题如下:

首先,保存解析的注释以便随后加载它们的最有效方法是什么?

从 CSV 文件中即时读取注释比将其保存到 numpy(或任何其他格式)更好吗?

当我加载保存的 numpy 数组时(以下示例仅包含图像和单个元数据)

 (x_train, y_train),(x_val, y_val)

那我就做

train_generator = datagen.flow(x_train, y_train, batch_size=32)

最后,

history = model.fit_generator(train_generator,
                        epochs=nb_of_epochs,
                        steps_per_epoch= steps_per_epoch,
                        validation_data=val_generator,
                        validation_steps=validation_steps,
                        callbacks=callbacks_list)

我的程序在整个训练过程(在 GPU 上完成)期间似乎消耗了高达 20-25GB 的 RAM。如果我添加多个输出,我的程序就会因为内存泄漏而崩溃(我的最大 RAM 是 32GB)。

将解析的注释与原始图像一起加载的正确方法是什么?

假设上述问题已解决,使用 ImageDataGenerator 进行多个输出的正确方法是什么,如下所示(也在此处讨论)

Keras: How to use fit_generator with multiple outputs of different type

Xi[0], [Yi1[1], Yi2[1],Yi3[1], Yi4[1],Yi5[1]]

最佳答案

def multi_output_generator(hdf5_file, nb_data, batch_size):
    """ Generates batches of tensor image data in form of ==> x, [y1, y2, y3, y4, y5] for use in a multi-output Keras model.

        # Arguments
            hdf5_file: the hdf5 file which contains the images and the annotations.
            nb_data: total number of samples saved in the array.
            batch_size: size of the batch to generate tensor image data for.

        # Returns
            A five-output generator.
    """

    batches_list = list(range(int(ceil(float(nb_data) / batch_size))))

    while True:

        # loop over batches
        for n, i in enumerate(batches_list):
            i_s = i * batch_size  # index of the first image in this batch
            i_e = min([(i + 1) * batch_size, nb_data])  # index of the last image in this batch

            x = hdf5_file["x_train"][i_s:i_e, ...]

            # read labels
            y1 = hdf5_file["y1"][i_s:i_e]
            y2 = hdf5_file["y2"][i_s:i_e]
            y3 = hdf5_file["y3"][i_s:i_e]
            y4 = hdf5_file["y4"][i_s:i_e]
            y5 = hdf5_file["y5"][i_s:i_e]

        yield x, [y1, y2, y3, y4 ,y5]

关于python - 从 CSV 加载图像和注释,并将 fit_generator 与多输出模型结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50333532/

相关文章:

Python 请求 - 403 禁止 - 尽管设置了 `User-Agent` header

python - 为什么在 python 中导入 .so 文件时出现小端错误

python - ValueError : No gradients provided for any variable while doing regression for integer values,,其中包括使用 keras 的底片

python - 以下哪一个是余弦衰减(神经网络的学习率重新加权)的正确实现?

python - 为什么keras损失函数将维度降低一维?

python - 什么时候使用变量类? (BooleanVar, DoubleVar, IntVar, StringVar)

python - 如何安装旧的 mingw 版本来安装 python 包(leven)

deep-learning - keras 输入层(Nnoe,200,3),为什么没有?输入有3维,但得到了形状为(200, 3)的数组

python - 训练前运行tensorflow模型,否则它不会训练?

python - while 循环 "continue"在尝试内不起作用,除了,最后