📜  ModelCheckpoint - Python (1)

📅  最后修改于: 2023-12-03 15:32:55.373000             🧑  作者: Mango

ModelCheckpoint - Python

The ModelCheckpoint function from the Python library Keras allows programmers to save the model during training. It is a callback function that is called after each epoch and can be used to save the model weights or the entire model.

Usage

The function can be instantiated as follows:

from keras.callbacks import ModelCheckpoint

checkpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', save_freq='epoch')
  • filepath: string, path to save the model.
  • monitor: quantity to monitor for saving the model.
  • verbose: verbosity mode, 0 or 1.
  • save_best_only: if True, the latest best model according to the quantity monitored will not be overwritten.
  • save_weights_only: if True, then only the model weights will be saved instead of the entire model.
  • mode: one of {auto, min, max}.
  • save_freq: 'epoch' or integer. When using 'epoch', the model is saved after each epoch. When using integer, the model is saved at the end of this many batches.

The ModelCheckpoint function can then be passed to the fit method of the Keras model as follows:

model.fit(X_train, y_train, epochs=10, batch_size=32, callbacks=[checkpoint])
Example

Here's an example usage of ModelCheckpoint:

from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import ModelCheckpoint
import numpy as np

# generate some random data
X_train = np.random.rand(1000, 10)
y_train = np.random.rand(1000, 1)

# create model
model = Sequential()
model.add(Dense(10, input_dim=10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

# compile model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# define callback for saving model during training
checkpoint = ModelCheckpoint('model.h5', monitor='val_accuracy', verbose=1, save_best_only=True, save_weights_only=False, mode='auto', save_freq='epoch')

# train model
model.fit(X_train, y_train, epochs=10, batch_size=32, callbacks=[checkpoint])

In this example, the model is trained on random data and saves the model at the end of each epoch, only saving the best model according to validation accuracy. The saved model can then be loaded and used for prediction later.

Conclusion

The ModelCheckpoint function is a useful tool for saving models during training and ensuring that the best performing model is saved. Programmers can use it to save time and resources during the model development process.