Keras model.fit 仅使用 batch_size 和仅使用 steps_per_epoch 之间的区别

Difference between Keras model.fit using only batch_size and using only steps_per_epoch

当我 运行 model.fit 同时使用 batch_sizesteps_per_epoch 参数时,我收到以下错误:

ValueError: If steps_per_epoch is set, the `batch_size` must be None.

所以,根据这个错误和下面的文档 from keras Model(functional API)

batch_size: Integer or None. Number of samples per gradient update. If unspecified, batch_size will default to 32.

steps_per_epoch: Integer or None. Total number of steps (batches of samples) before declaring one epoch finished and starting the next epoch. When training with input tensors such as TensorFlow data tensors, the default None is equal to the number of samples in your dataset divided by the batch size, or 1 if that cannot be determined.

我知道这两个参数在某种程度上是等价的。但是,在我的笔记本电脑上(使用带有 2GB VRAM 的 GeForce 940M 显卡并训练 cifar10 数据集)当我 运行 model.fit 将 epochs 参数设置为 256 时脚本 运行 很好而keras给出的反馈是这样的:

4608/50000 [=>............................] - ETA: 1:59 - loss: 0.8167 - acc: 0.7398

更新第一个数字总是添加 256 个单位。但是,当将 steps_per_epoch 作为 number_train//batch_size 传递时,我 运行 内存不足并且不能 运行 我的脚本,除非我将 batch_size 作为 1.

那么,model.fit 如何使用这些参数?当我只使用其中一个而不是另一个时有什么区别?

这是个好问题。我从源代码 ([1] and [2]) 中观察到的是:

  • 当您设置 batch_size 时,训练数据被分割成这个大小的批次(参见 L184)。
  • 当您设置 steps_per_epoch 时,如果训练输入不是框架原生张量(这是最常见的情况),则 整个 训练集被馈送一次性进入网络(参见 L152),这就是出现内存错误的原因。

因此,基于实现,我建议仅在通过框架原生张量(即第一维为批量大小的 TensorFlow 张量)馈送时使用参数 steps_per_epoch,这确实是要求。为此,model.fit 中的参数 xy 需要设置为 None.