使用Keras Functional模型迁移学习绘制精度曲线时遇AttributeError问题
解决AttributeError: 'Functional' object has no attribute 'epoch'问题
错误原因
你传给plot_performance_acc函数的参数是模型对象(Functional类型),但这个函数需要的是模型训练后返回的History对象。model.fit()方法会返回一个History实例,它包含.history和.epoch属性;而模型本身(比如你用函数式API创建的EfficientNet模型)没有这些属性,因此触发报错。
解决方案
1. 修正函数调用逻辑
训练模型时,务必保存model.fit()返回的History对象,再将其传入绘图函数:
# 初始化并训练模型,保存训练历史 model_06 = get_model() model_06.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.1), loss='binary_crossentropy', metrics=['accuracy']) history_06 = model_06.fit(train_data, epochs=..., validation_data=val_data) # 同理处理其他不同学习率的模型 model_07 = get_model() model_07.compile(optimizer=tf.keras.optimizers.Adam(learning_rate=0.01), ...) history_07 = model_07.fit(...) history_08 = ... history_09 = ... history_10 = ... # 调用绘图函数时传入History对象而非模型 plot_performance_acc(history_06, history_07, history_08, history_09, history_10)
2. 优化绘图函数(可选)
可以重构函数,让它支持可变数量的输入,减少重复代码:
def plot_performance_acc(histories, labels): plt.rcParams['figure.figsize'] = (20, 10) # 绘制训练精度曲线 plt.subplot(1, 2, 1) for hist, label in zip(histories, labels): epochs = range(len(hist.history['accuracy'])) plt.plot(epochs, hist.history['accuracy'], label=label) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.title('Training accuracy with Adam optimizer') plt.legend(loc='lower right') # 绘制验证精度曲线 plt.subplot(1, 2, 2) for hist, label in zip(histories, labels): epochs = range(len(hist.history['val_accuracy'])) plt.plot(epochs, hist.history['val_accuracy'], label=label) plt.xlabel('Epochs') plt.ylabel('Accuracy') plt.title('Validation accuracy with Adam optimizer') plt.legend(loc='lower right') plt.tight_layout(2) fig1 = plt.gcf() plt.show() plt.draw() fig1.savefig('acc.png', dpi=50) # 调用示例 histories = [history_06, history_07, history_08, history_09, history_10] labels = ['Learning Rate: 0.1', 'Learning Rate: 0.01', 'Learning Rate: 0.001', 'Learning Rate: 0.0001', 'Learning Rate: 0.00001'] plot_performance_acc(histories, labels)
补充提醒
无论自定义CNN还是迁移学习模型,训练后都要区分模型对象和训练历史对象:模型用于预测、保存等操作,训练历史才是绘图需要的数据源。
内容的提问来源于stack exchange,提问作者5hi
相关产品推荐
相关产品推荐

