使用 Kerasfit_generator
,steps_per_epoch 应等于可用样本总数除以batch_size
。
但是,如果我选择的batch_size
不适合样品n次,生成器或fit_generator
将如何反应?它是产生样品直到无法再填充整个batch_size
,还是只是使用较小的batch_size
来获得最后的产量?
我为什么问:我将数据划分为不同大小(不同%(的训练/验证/测试,但会对训练集和验证集使用相同的批量大小,尤其是对于训练集和测试集。由于它们的大小不同,我不能保证批量大小适合样品总量。
如果它是你的生成器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')
如果你将N
分配给参数fit_generator()
的参数steps_per_epoch
,Keras 基本上会在考虑完成一个 epoch 之前调用你的生成器N
次。由您的生成器来分N
批次生产所有样品。
请注意,由于对于大多数模型,每次迭代都有不同的批大小是可以的,因此您可以修复steps_per_epoch = ceil(dataset_size / batch_size)
,让生成器为最后一个样本输出较小的批次。
我遇到了同样的逻辑错误 通过定义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)