SantoshGupta7
SantoshGupta7

Reputation: 6197

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

I would like to save my model every x number of steps when running model.fit.

I am looking at the documentation https://www.tensorflow.org/api_docs/python/tf/keras/Model#fit

And there doesn't seem to be an option for this. But saving checkpoints during training is such a common use case, it's a bit hard to imagine there isn't some way to do this. So I am wondering if I overlooked something.

Upvotes: 0

Views: 1475

Answers (1)

sdcbr
sdcbr

Reputation: 7129

This can be done using the 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])

You can modify the behaviour of the callback using the monitor, mode and save_best_only parameters, which govern the metric to track and whether the checkpoints are overwritten to retain the best model only.

Upvotes: 1

Related Questions