使用 Keras model.fit,您如何设置它以保存每 x 个步骤?

With Keras model.fit, how do you set it up to save every x number of steps?

我想在 运行 model.fit 时每隔 x 步保存我的模型。

我正在查看文档 https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit

似乎没有这个选项。但是在训练期间保存检查点是一个非常常见的用例,很难想象没有什么方法可以做到这一点。所以我想知道我是否忽略了什么。

这可以使用 ModelCheckpoint callback:

EPOCHS = 10
checkpoint_filepath = '/tmp/checkpoint'
model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(
    filepath=checkpoint_filepath,
    save_weights_only=True,
    monitor='val_acc',
    mode='max',
    save_best_only=True)

# Model weights are saved at the end of every epoch, if it's the best seen
# so far.
model.fit(epochs=EPOCHS, callbacks=[model_checkpoint_callback])

您可以使用 monitormodesave_best_only 参数修改回调的行为,这些参数控制要跟踪的指标以及检查点是否被覆盖以保留最佳状态仅限模型。