【问题标题】:what if steps_per_epoch does not fit into numbers of samples?如果steps_per_epoch 不适合样本数量怎么办?
【发布时间】:2018-11-11 15:03:39
【问题描述】:

使用 Keras fit_generator,steps_per_epoch 应该等于可用样本总数除以 batch_size

但是,如果我选择的 batch_size 不适合样本 n 次,那么生成器或 fit_generator 将如何反应?它是否会产生样本,直到它不能再填充整个batch_size,或者它只是使用较小的batch_size 作为最后的产量?

我问的原因:我将我的数据分成不同大小(不同百分比)的训练/验证/测试,但会为训练集和验证集使用相同的批量大小,尤其是训练集和测试集。由于它们的大小不同,我无法保证批量大小适合样本总量。

【问题讨论】:

    标签: keras generator


    【解决方案1】:

    如果是您的生成器,yield

    是您创建了生成器,因此行为由您定义。

    如果steps_per_epoch 大于预期批次,fit 将看不到任何内容,它只会继续请求批次,直到达到步数。

    唯一的事情是:你必须确保你的生成器是无限的。

    例如,在开头使用while True:

    如果它是来自ImageDataGenerator 的生成器。

    如果生成器来自ImageDataGenerator,它实际上是keras.utils.Sequence,并且它具有长度属性:len(generatorInstance)

    然后你可以自己检查会发生什么:

    remainingSamples = total_samples % batch_size #confirm that this is gerater than 0
    wholeBatches = total_samples // batch_size
    totalBatches = wholeBatches + 1
    
    if len(generator) == wholeBatches:
        print("missing the last batch")    
    elif len(generator) == totalBatches:
        print("last batch included")
    else:
        print('weird behavior')
    

    并检查最后一批的大小:

    lastBatch = generator[len(generator)-1]
    
    if lastBatch.shape[0] == remainingSamples:
        print('last batch contains the remaining samples')
    else:
        print('last batch is different')
    

    【讨论】:

    • 你好丹尼尔。很高兴再次见到你,我在生成器中使用了经典的“while nlen(Data)。我只是想知道 fit_generator 函数在没有返回值的情况下做了什么。
    • 查看改进的答案。
    • 一个更完整的答案是:) 但是,为了涵盖total_samples batch_size的倍数的情况,我会写totalBatches = wholeBatches + (remainingSamples != 0)(或简单地@ 987654333@,并相应地更改以下条件...?
    • 确实,我只是在“检查”Sequence 生成器以查看它的作用(因为您没有创建它)。
    【解决方案2】:

    如果您将N 分配给fit_generator() 的参数steps_per_epoch,Keras 基本上会在考虑完成一个时期之前调用您的生成器N 次。由您的生成器生成 N 批次中的所有样本。

    请注意,由于对于大多数模型来说,每次迭代都有不同的批量大小是可以的,您可以修复 steps_per_epoch = ceil(dataset_size / batch_size) 并让您的生成器为最后的样本输出较小的批量。

    【讨论】:

      【解决方案3】:

      我遇到了同样的逻辑错误 通过定义steps_per_epochs解决了它

      BS = 32
      steps_per_epoch=len(trainX) // BS
      history = model.fit(train_batches,
                      epochs=initial_epochs,steps_per_epoch=steps_per_epoch,
                      validation_data=validation_batches)
      

      【讨论】:

        猜你喜欢
        • 2021-03-09
        • 2022-08-05
        • 2013-01-13
        • 1970-01-01
        • 2019-10-10
        • 2013-06-05
        • 2011-07-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多