测试集指标统计
统计准确率和召回率。为了计算准确率和召回率,需要以下信息:
- 真阳性(True Positive, TP):正确预测为正类的样本数。
- 假阳性(False Positive, FP):错误预测为正类的样本数。
- 假阴性(False Negative, FN):错误预测为负类的样本数。
- 真阴性(True Negative, TN):正确预测为负类的样本数。
计算准确率:
准确率 = (真阳性 + 真阴性) / 总样本数。
计算召回率:
召回率 = 真阳性 / (真阳性 + 假阴性)。
计算精确率:
精确率 = 真阳性 / (真阳性 + 假阳性)。精确率 (Precision):预测为正的样本中真实正的比例(TP/(TP+FP))
召回率 (Recall):真实正的样本中被正确预测的比例(TP/(TP+FN))
F1-Score:精确率和召回率的调和平均
Support:每个类别的实际样本数
混淆数:每个类别的FP+FN总和
假设数据集只有两类:正类(positive)和负类(negative)。可以根据这些信息来计算准确率和召回率。
代码如下
结果图片格式:positive_0001_cls_positive.jpg >> 图片真实标签_0001_cls_模型预测结果.jpg
import os
import glob
# 图片路径
img_p = r"/Train-main\projects\eat\workdir\results20250227".replace("\\", "/")
# 获取所有图片
img_list = glob.glob(f"{img_p}/**/*.jpg", recursive=True) + glob.glob(f"{img_p}/**/*.png", recursive=True)
# 初始化计数器
true_positive = 0
false_positive = 0
false_negative = 0
true_negative = 0
# 遍历所有图片 positive_0001_cls_positive.jpg >> 图片真实标签_0001_cls_模型预测结果.jpg
for i in img_list:
img_str = os.path.basename(i)
img_lab = img_str.split("_")[0]
pred_lab = img_str.split("_")[3].split(".")[0]
if img_lab == "positive":
if pred_lab == "positive":
true_positive += 1
else:
false_negative += 1
else: # img_lab == "negative"
if pred_lab == "positive":
false_positive += 1
else:
true_negative += 1
# 计算总样本数
img_all = len(img_list)
# 计算准确率
accuracy = (true_positive + true_negative) / img_all
# 计算召回率(针对正类)
recall = true_positive / (true_positive + false_negative) if (true_positive + false_negative) > 0 else 0
# 计算精确率(针对正类)
precision = true_positive / (true_positive + false_positive) if (true_positive + false_positive) > 0 else 0
# 输出结果
print(f"Total images: {img_all}")
print(f"True Positive: {true_positive}")
print(f"False Positive: {false_positive}")
print(f"False Negative: {false_negative}")
print(f"True Negative: {true_negative}")
print(f"Accuracy: {accuracy:.4f}")
print(f"Recall: {recall:.4f}")
print(f"Precision: {precision:.4f}")
详细解释
-
初始化计数器:
true_positive
:真阳性计数器。false_positive
:假阳性计数器。false_negative
:假阴性计数器。true_negative
:真阴性计数器。
-
遍历所有图片:
- 从图片文件名中提取真实标签
img_lab
和预测标签pred_lab
。 - 根据真实标签和预测标签更新计数器。
- 从图片文件名中提取真实标签
-
计算总样本数:
img_all
是所有图片的数量。
-
计算准确率:
- 准确率 = (真阳性 + 真阴性) / 总样本数。
-
计算召回率:
- 召回率 = 真阳性 / (真阳性 + 假阴性)。
-
计算精确率:
- 精确率 = 真阳性 / (真阳性 + 假阳性)。
-
输出结果:
- 打印总样本数、真阳性、假阳性、假阴性、真阴性、准确率、召回率和精确率。