How to utilize callback functions in Keras?
In Keras, callbacks can be used by passing a list of callback functions during model training. Callback functions are functions called at specific points during the training process, and can be used to perform tasks such as saving the model, dynamically adjusting the learning rate, and visualizing the training process.
Here is a simple example showing how to use callbacks in Keras.
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import ModelCheckpoint
# 创建一个简单的Sequential模型
model = Sequential()
model.add(Dense(64, activation='relu', input_dim=100))
model.add(Dense(64, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
# 编译模型
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
# 定义一个回调函数,用来保存模型的权重
checkpoint = ModelCheckpoint(filepath='weights.{epoch:02d}-{val_loss:.2f}.hdf5',
monitor='val_loss', save_best_only=True)
# 模型训练,并传入回调函数的列表
model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val), callbacks=[checkpoint])
In the example above, we defined a ModelCheckpoint callback function to save the model’s weights. During model training, we pass this callback function into the callbacks parameter so that the model weights will be saved at the end of each epoch if there is an improvement in the validation loss.
In addition to the ModelCheckpoint callback function, Keras also offers many other built-in callbacks such as EarlyStopping, TensorBoard, etc., which can be selected based on specific needs.