【问题标题】:Infinite Loop with ImageDataGenerator带有 ImageDataGenerator 的无限循环
【发布时间】:2020-10-31 07:12:24
【问题描述】:

我正在处理一个更大的数据集,因此,我必须将数据批量加载到我的 RAM 中,以便在不耗尽资源的情况下更快地运行。我正在使用带有.flow的图像数据生成器@

使用 for 循环会导致无限循环,在循环重新开始之前不断生成相同批量大小的图像。准备器代码如下所示:

train_dataset=tf.keras.preprocessing.image.ImageDataGenerator(featurewise_center=False, samplewise_center=False,
    featurewise_std_normalization=False, samplewise_std_normalization=False,
    zca_whitening=False, rotation_range=0, width_shift_range=0.0,
    height_shift_range=0.0, brightness_range=None, shear_range=0.0, zoom_range=0.0,
    channel_shift_range=0.0, cval=0.0, horizontal_flip=False,
    vertical_flip=False, preprocessing_function=None,
    data_format=None, validation_split=0.0, dtype=None)
train_dataset.fit(X)

后面是一个尝试循环,如下所示:

for images, y_batch in train_dataset.flow(X, y, batch_size=batch_size):
          print(np.shape(images))

代码只是不断返回维度数组:

(batch_size,img_size,img_size,3) (我需要这些图像将数据带入我的 RAM 以执行 back prop)。请注意,我没有使用像 model.fit 这样的东西,需要通过我的正确代码运行这些数组。

不太清楚如何添加停止条件

【问题讨论】:

  • 抱歉,这里有什么问题?这就是生成器在 Keras 中的工作方式。

标签: tensorflow for-loop machine-learning keras infinite-loop


【解决方案1】:

这就是重点;永远继续迭代。 Keras 的 model.fit_gerentaor() 或 tf.keras 的 model.fit() 根据 epochs 和 steps_per_epoch 参数处理终止训练循环。

如果您想手动使用ImageDataGenerator() 训练模型,您可以大致执行以下操作:

epochs = 10
steps_per_epoch = len(x) // batch_size + 1  # we usually consider 1 epoch to be
                                            # the point where the model has seen
                                            # all the training samples at least once

generator = train_dataset.flow(X, y, batch_size=batch_size)

for e in range(epochs):
    for i, (images, y_batch) in enumerate(generator):
       model.train_on_batch(images, y_batch)  # train model for a single iteration
       if i >= steps_per_epoch:  # manually detect the end of the epoch
           break  
    generator.on_epoch_end()  # this shuffles the data at the end of each epoch

【讨论】:

  • ``` if i >= steps_per_epoch: ``
  • @Mr.JohnnyDoe 有错字,我已修正。
猜你喜欢
  • 2021-04-29
  • 1970-01-01
  • 2021-08-28
  • 2020-10-16
  • 2017-10-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多