关系识别分类任务的评估指标: precision、recall、f1-score. 理解混淆矩阵

理解TP/FP/FN

  • TP: 真实关系为A,预测关系也为A。
  • FP: 预测为关系A,但真实关系不为A
  • FN: 真实关系为A,但预测关系为其他关系。

代码

python 复制代码
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay

# 类别标签顺序
labels = ['instance of', 'has part']

# 真实关系标签与模型预测
y_true = ['instance of', 'instance of', 'instance of', 'instance of', 'has part', 'has part']
y_pred = ['instance of', 'instance of', 'has part', 'has part', 'has part', 'instance of']

# 计算混淆矩阵,显式指定标签顺序
cm = confusion_matrix(y_true, y_pred, labels=labels)

# 显示混淆矩阵
disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=labels)
disp.plot(cmap=plt.cm.Blues)

# 旋转x轴标签,优化显示
plt.xticks(rotation=45)
plt.yticks(rotation=0)
plt.tight_layout()

# 保存图像
plt.savefig('confusion_matrix.png')

# 每个类别的pre/recall/f1/support
precision, recall, f1, support = precision_recall_fscore_support(y_true, y_pred, labels=labels)

# 初始化字典存储 TP、FP、FN
results = {label: {'TP': 0, 'FP': 0, 'FN': 0} for label in labels}

# 通过 precision, recall 和 support 反推出每个类别的 TP、FP 和 FN
for i, label in enumerate(labels):
    TP = int(support[i] * recall[i])  # recall = TP / (TP + FN)
    FN = support[i] - TP             # FN = support - TP
    FP = int(TP / precision[i]) - TP if precision[i] > 0 else 0  # precision = TP / (TP + FP)

    results[label]['TP'] = TP
    results[label]['FP'] = FP
    results[label]['FN'] = FN

# 输出结果
for label in labels:
    print(f"类别: {label}")
    print(f"  TP: {results[label]['TP']}")
    print(f"  FP: {results[label]['FP']}")
    print(f"  FN: {results[label]['FN']}")

混淆矩阵

  • True Positive (TP):对角线上数值(预测正确)。
  • False Positive (FP):同一列中,非对角线上的数值(预测为某类但真实不是)。
  • False Negative (FN):同一行中,非对角线上的数值(真实为某类但预测不是)。

演示计算 instance of 类别的TP/FP/FN:

  • TP=2
  • FP=1
  • FN=2
相关推荐
gnawkhhkwang7 分钟前
Flask + YARA-Python*实现文件扫描功能
后端·python·flask
CODE_RabbitV7 分钟前
如何让 RAG 检索更高效?——大模型召回策略全解
人工智能·算法·机器学习
yj155815 分钟前
二手房翻新时怎样装修省钱?
python
max50060033 分钟前
复现论文《A Fiber Bragg Grating Sensor System for Train Axle Counting》
开发语言·python·深度学习·机器学习·matlab·transformer·机器翻译
无规则ai35 分钟前
数字图像处理(冈萨雷斯)第三版:第四章——频率域滤波(学前了解知识)——主要内容和重点
人工智能·算法·机器学习·计算机视觉
WSSWWWSSW42 分钟前
Python高级编程与实践:Python网络编程基础与实践
开发语言·网络·python
mortimer1 小时前
Python GUI 应用启动优化实战:从3分钟到“秒开”的深度历程
python·github·pyqt
竹子_231 小时前
贪心算法解析
python·算法·贪心算法
三道杠卷胡1 小时前
【AI News | 20250804】每日AI进展
人工智能·python·语言模型·github·aigc
小沈熬夜秃头中୧⍤⃝2 小时前
Python 基础语法(二):流程控制语句详解
开发语言·数据库·python