ModelCheckpoint 类keras.callbacks.ModelCheckpoint(
filepath,
monitor="val_loss",
verbose=0,
save_best_only=False,
save_weights_only=False,
mode="auto",
save_freq="epoch",
initial_value_threshold=None,
)
以一定频率保存 Keras 模型或模型权重的回调。
ModelCheckpoint 回调与使用 model.fit() 进行训练配合使用,以一定间隔保存模型或权重(在检查点文件中),以便以后可以加载模型或权重以从保存的状态继续训练。
此回调提供的一些选项包括:
示例
model.compile(loss=..., optimizer=...,
metrics=['accuracy'])
EPOCHS = 10
checkpoint_filepath = '/tmp/ckpt/checkpoint.model.keras'
model_checkpoint_callback = keras.callbacks.ModelCheckpoint(
filepath=checkpoint_filepath,
monitor='val_accuracy',
mode='max',
save_best_only=True)
# Model is saved at the end of every epoch, if it's the best seen so far.
model.fit(epochs=EPOCHS, callbacks=[model_checkpoint_callback])
# The model (that are considered the best) can be loaded as -
keras.models.load_model(checkpoint_filepath)
# Alternatively, one could checkpoint just the model weights as -
checkpoint_filepath = '/tmp/ckpt/checkpoint.weights.h5'
model_checkpoint_callback = keras.callbacks.ModelCheckpoint(
filepath=checkpoint_filepath,
save_weights_only=True,
monitor='val_accuracy',
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])
# The model weights (that are considered the best) can be loaded as -
model.load_weights(checkpoint_filepath)
参数
PathLike,用于保存模型文件的路径。filepath 可以包含命名格式选项,这些选项将填充 epoch 和 logs(在 on_epoch_end 中传递)中的键的值。当 save_weights_only=True 时,filepath 名称需要以 ".weights.h5" 结尾,或者在检查点保存整个模型(默认)时,应以 ".keras" 或 ".h5" 结尾。例如:如果 filepath 是 "{epoch:02d}-{val_loss:.2f}.keras" 或 "{epoch:02d}-{val_loss:.2f}.weights.h5",则模型检查点将以文件名中的 epoch 编号和验证损失保存。文件路径的目录不应被任何其他回调重用,以避免冲突。Model.compile 方法设置。注意:"val_" 以监控验证指标。"loss" 或 "val_loss" 来监控模型的总损失。"accuracy",则传递相同的字符串(带或不带 "val_" 前缀)。metrics.Metric 对象,monitor 应设置为 metric.namehistory = model.fit() 返回的 history.history 字典的内容save_best_only=True,则只在模型被认为是“最佳”时保存,并且根据监控的数量,最新的最佳模型将不会被覆盖。如果 filepath 不包含 {epoch} 等格式选项,则 filepath 将被每个新的更好的模型覆盖。"auto", "min", "max"} 之一。如果 save_best_only=True,则根据监控数量的最大化或最小化来决定是否覆盖当前保存文件。对于 val_acc,这应该是 "max";对于 val_loss,这应该是 "min" 等。在 "auto" 模式下,方向会自动从监控数量的名称中推断出来。True,则只保存模型的权重(model.save_weights(filepath)),否则保存完整模型(model.save(filepath))。"epoch" 或整数。当使用 "epoch" 时,回调在每个 epoch 后保存模型。当使用整数时,回调在此数量的批次结束时保存模型。如果 Model 使用 steps_per_execution=N 编译,则每 N 个批次检查一次保存条件。请注意,如果保存与 epoch 不对齐,则监控的指标可能可靠性较低(它可能只反映 1 个批次,因为指标在每个 epoch 都会重置)。默认为 "epoch"。save_best_value=True 时适用。仅当当前模型的性能优于此值时才覆盖已保存的模型权重。