Skip to main content
 首页 » 编程设计

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

2024年12月31日11jackei

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

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] 和 [2])中观察到的是:

  • 当您设置 batch_size 时,训练数据被分割成这个大小的批处理(参见 L184 )。
  • 当您设置 steps_per_epoch 时,如果训练输入不是框架原生张量(这是最常见的情况),整个训练集将被送入网络在一个批处理中(见 L152 ),这就是你得到内存错误的原因。

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