从CSV加载图像和注释,并将fit_generator与多输出模型一起使用
问题内容:
在问题#10120之后,我正在使用Keras功能API构建具有多个(五个)输出和相同输入的模型,以便同时预测数据的不同属性(在我的情况下为图像)。数据集的所有元数据都存储在不同的CSV文件中(一个用于训练,一个用于验证,一个用于测试数据)。
我已经编写了解析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)
我的程序似乎在整个训练过程中消耗了多达20-25GB的RAM(在GPU上完成)。万一我添加了多个输出,我的程序由于内存泄漏而崩溃(我拥有的最大RAM为32GB)。
将已解析的注释与原始图像一起加载的正确方法是什么?
假设上述问题已解决, 那么将ImageDataGenerator用于以下多个输出的正确方法 是 什么 (也在此处讨论)
Keras:如何将fit_generator与不同类型的多个输出一起使用
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]