📅  最后修改于: 2023-12-03 15:32:55.373000             🧑  作者: Mango
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.
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')
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])
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.
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.