Keras的可视化功能可以帮助你更好地理解和分析模型的结构和训练过程。以下是一些常用的可视化方法:
模型结构可视化
使用 plot_model
函数可以生成模型结构的图像。以下是一个例子:
from keras.models import Sequential
from keras.layers import Dense
from keras.utils.vis_utils import plot_model
model = Sequential([
Dense(32, activation='relu', input_shape=(100,)),
Dense(16, activation='relu'),
Dense(1, activation='sigmoid')
])
plot_model(model, to_file='model.png')
模型结构
训练过程可视化
使用 matplotlib
可以将训练过程中的损失和准确率绘制出来。
import matplotlib.pyplot as plt
from keras.callbacks import EarlyStopping
early_stopping = EarlyStopping(monitor='val_loss', patience=3)
history = model.fit(x_train, y_train, validation_data=(x_val, y_val), epochs=10, callbacks=[early_stopping])
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Loss over epochs')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Validation'], loc='upper left')
plt.show()
损失与验证损失
更多可视化技巧和示例,请访问我们的 Keras可视化深入指南。