Keras Sequential模型绘图报错:'Sequential'对象不可下标访问
解决1D CNN训练中的两个问题:下标访问报错与ModelCheckpoint无法保存最佳模型
问题1:'Sequential' object is not subscriptable 报错
你直接用model['accuracy']访问训练指标的方式是错误的——Keras的Sequential模型实例本身不支持下标访问,训练过程中的准确率、损失等数据都存在**model.fit()返回的History对象**里。
解决步骤:
- 训练时保存History对象:
history = model.fit(x_train, y_train, epochs=10, batch_size=32) - 从History对象的
history字典中提取指标数据:# 训练集准确率与损失 train_acc = history.history['accuracy'] train_loss = history.history['loss'] # 如果有验证集,对应键为val_accuracy、val_loss val_acc = history.history.get('val_accuracy') val_loss = history.history.get('val_loss') - 绘制曲线示例(用matplotlib):
import matplotlib.pyplot as plt # 绘制准确率曲线 plt.figure(figsize=(8, 4)) plt.plot(train_acc, label='Training Accuracy') if val_acc: plt.plot(val_acc, label='Validation Accuracy') plt.title('Model Accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend() plt.show() # 绘制损失曲线 plt.figure(figsize=(8, 4)) plt.plot(train_loss, label='Training Loss') if val_loss: plt.plot(val_loss, label='Validation Loss') plt.title('Model Loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend() plt.show()
问题2:未传入验证集导致ModelCheckpoint无法保存最佳模型
ModelCheckpoint默认需要验证集指标(如val_loss)来判断“最佳”模型,没有验证集就无法完成最佳模型的判定逻辑。
解决方法:
- 优先使用验证集:在
model.fit()中传入验证集数据,要么手动传入validation_data,要么用validation_split从训练集拆分:# 方式1:传入预准备的验证集 model.fit(x_train, y_train, validation_data=(x_val, y_val), callbacks=[checkpoint], epochs=10) # 方式2:从训练集中拆分15%作为验证集 model.fit(x_train, y_train, validation_split=0.15, callbacks=[checkpoint], epochs=10) - 无验证集时的替代方案(不推荐,易过拟合):修改ModelCheckpoint的监控指标为训练集损失/准确率,基于训练集数据保存“最佳”模型:
from tensorflow.keras.callbacks import ModelCheckpoint # 监控训练集损失,保存损失最小的模型 checkpoint = ModelCheckpoint('best_train_model.h5', monitor='loss', save_best_only=True, mode='min') model.fit(x_train, y_train, callbacks=[checkpoint], epochs=10)
内容的提问来源于stack exchange,提问作者Maryam Awari-Alimi
相关产品推荐
相关产品推荐

