keras.callbacks.ModelCheckpoint
时间: 2024-01-13 11:51:48 浏览: 100
The `ModelCheckpoint` callback in Keras is used to save the model after every epoch or a certain number of epochs during training. This callback is useful when training deep learning models that can take several hours or days to complete. By saving the model at regular intervals, we can resume training from where we left off in case of an unexpected interruption or failure.
The `ModelCheckpoint` callback takes several arguments, including:
- `filepath`: the path to save the model file.
- `monitor`: the metric to monitor for saving the best model.
- `save_best_only`: whether to save only the best model based on the monitored metric.
- `save_weights_only`: whether to save only the model weights instead of the entire model architecture.
- `mode`: whether to maximize or minimize the monitored metric.
- `verbose`: the verbosity mode.
Here's an example of using the `ModelCheckpoint` callback to save the best model based on validation loss:
```python
from tensorflow.keras.callbacks import ModelCheckpoint
checkpoint = ModelCheckpoint(filepath='best_model.h5',
monitor='val_loss',
save_best_only=True,
mode='min',
verbose=1)
model.fit(X_train, y_train,
batch_size=32,
epochs=10,
validation_data=(X_val, y_val),
callbacks=[checkpoint])
```
In this example, the `ModelCheckpoint` callback will save the best model based on validation loss in the file `best_model.h5`. The `verbose` argument is set to 1, which means that the callback will print a message when a new best model is saved.
阅读全文