📅  最后修改于: 2023-12-03 15:02:30.376000             🧑  作者: Mango
Keras is a popular deep learning library that provides several utilities to work with and train deep neural networks. One of these utilities is the History callback, which can be used to collect and visualize the training and validation metrics during the training of a Keras model.
To use the History callback, you simply need to include it as a callback when fitting your Keras model:
from keras.callbacks import History
history = History()
model.fit(x_train, y_train, epochs=10, validation_data=(x_val, y_val), callbacks=[history])
After the model has finished training, the history
object will contain the training and validation metrics for each epoch. These metrics can be accessed using the history.history
attribute, which is a dictionary containing the metric names as keys and a list of values for each epoch as values.
history_dict = history.history
print(history_dict.keys()) # ['loss', 'acc', 'val_loss', 'val_acc']
train_loss = history_dict['loss']
val_loss = history_dict['val_loss']
train_acc = history_dict['acc']
val_acc = history_dict['val_acc']
The easiest way to visualize the training and validation metrics collected by the History callback is to use the matplotlib
library:
import matplotlib.pyplot as plt
epochs = range(1, len(train_loss) + 1)
plt.plot(epochs, train_loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
The History callback is a simple yet powerful tool to keep track of and visualize the training and validation metrics of a Keras model. By using this callback and the matplotlib
library, you can quickly identify and diagnose potential issues in your model and make informed decisions on how to improve its performance.