关系识别分类任务的评估指标: 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
相关推荐
BerryS3N2 分钟前
深度解析:从零构建生产级大模型 RAG(检索增强生成)系统全栈指南
开发语言·python·ai
weixin_BYSJ198710 分钟前
「课设设计」springboot校园超市助购系统26449 (附源码)
java·javascript·spring boot·python·django·flask·php
今儿敲了吗18 分钟前
Python——函数基础
开发语言·笔记·python
半条_虫31 分钟前
豆包-网页逆向接口, 免token调用AI
python·ai·shell
kels88991 小时前
单连接动态增减订阅:股票行情API后端降负载实战方案
开发语言·笔记·python·信息可视化·金融
爱吃程序猿的喵1 小时前
LingBot-Map 复现与原理剖析:基于 Geometric Context Transformer 的流式 3D 重建
人工智能·python·深度学习·计算机视觉·3d·transformer
梦想不只是梦与想1 小时前
Python 中的 match-case(模式匹配)
python·match-case
郝同学今天有进步吗1 小时前
构建 LangGraph Code Review Agent(四):文件过滤与 AnalysisPackage 分包
git·python·ai·code review
a1117761 小时前
基于PyTorch的动物图像识别系统 开源
人工智能·pytorch·python
qetfw1 小时前
MWU:Vue 3 + FastAPI 的 MaaFramework 跨平台 WebUI 源码
前端·vue.js·python·fastapi·开源项目·效率工具