我试图建立一个模型,它的输入和输出(掩码)都有图像。由于数据集的大小和我有限的内存,我尝试使用Keras文档中介绍的生成器方法:
# Provide the same seed and keyword arguments to the fit and flow methods
seed = 1
image_generator = image_datagen.flow_from_directory(
'data/images',
class_mode=None,
seed=seed)
mask_generator = mask_datagen.flow_from_directory(
'data/masks',
class_mode=None,
seed=seed)
# combine generators into one which yields image and masks
train_generator = zip(image_generator, mask_generator)
model.fit_generator(
train_generator,
samples_per_epoch=2000,
nb_epoch=50)
一切似乎都工作,除了当代码到达这一行:
train_generator = zip(image_generator, mask_generator)
似乎压缩两个列表的过程显式地使它们生成内容,系统开始消耗大量RAM,直到内存耗尽。
使用generator的目的是避免RAM耗尽,而这段代码恰恰相反。
有办法解决这个问题吗?
您可以使用itertools.izip()
返回迭代器而不是列表。
itertools.izip(*iterables)
Make an iterator that aggregates elements from each of the iterables. Like zip() except that it returns an iterator instead of a list. Used for lock-step iteration over several iterables at a time.