You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从已保存模型输出训练/测试accuracy、val_accuracy及precision等指标与混淆矩阵?

从训练后的VGG16模型获取各类评估指标

加载已保存的模型

先加载你通过ModelCheckpoint保存的模型,假设模型文件名为best_model.h5,代码如下:

from tensorflow.keras.models import load_model

# 加载保存好的模型
my_vgg_model = load_model('best_model.h5')

获取训练集与测试集的accuracy

从训练历史中提取

训练时得到的hist对象存储了全程的指标数据,可直接提取:

# 提取训练集accuracy
train_acc = hist.history['accuracy'][0]
# 提取训练过程中验证集(即你的x_test、y_test)的val_accuracy
val_acc_from_history = hist.history['val_accuracy'][0]

print(f"训练集accuracy: {train_acc:.4f}")
print(f"训练时验证集val_accuracy: {val_acc_from_history:.4f}")

重新评估模型获取指标

如果已关闭训练脚本、丢失hist对象,可直接用模型重新评估数据集:

# 评估训练集
train_loss, train_acc = my_vgg_model.evaluate(x_train, y_train, verbose=0)
# 评估测试集(即训练时的validation_data)
test_loss, test_acc = my_vgg_model.evaluate(x_test, y_test, verbose=0)

print(f"训练集accuracy: {train_acc:.4f}")
print(f"测试集accuracy: {test_acc:.4f}")

计算precision、recall、F1-score及混淆矩阵

先获取模型对测试集的预测结果,再用sklearn.metrics模块计算指标:

import numpy as np
from sklearn.metrics import precision_score, recall_score, f1_score, confusion_matrix, classification_report

# 获取测试集的预测概率,转换为类别标签
y_pred_probs = my_vgg_model.predict(x_test, verbose=0)
y_pred = np.argmax(y_pred_probs, axis=1)
# 把独热编码的真实标签转为类别整数(如果你的标签不是独热编码,可跳过此步)
y_true = np.argmax(y_test, axis=1)

# 计算各项指标
precision = precision_score(y_true, y_pred, average='weighted')
recall = recall_score(y_true, y_pred, average='weighted')
f1 = f1_score(y_true, y_pred, average='weighted')

print(f"Precision: {precision:.4f}")
print(f"Recall: {recall:.4f}")
print(f"F1-score: {f1:.4f}")

# 打印混淆矩阵
print("\n混淆矩阵:")
print(confusion_matrix(y_true, y_pred))

# 打印包含单类指标的详细分类报告
print("\n分类报告:")
print(classification_report(y_true, y_pred))

内容的提问来源于stack exchange,提问作者Kiotaka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 02:07:12