关系识别分类任务的评估指标: 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
相关推荐
Doubbbbbbble云2 分钟前
图算法中的剪枝技术与启发式优化分析4
算法·机器学习·剪枝
minji...3 分钟前
LangGraph-AI智能体开发框架 - LangGraph 入门案例1 : 智能快递配送系统
人工智能·python·ai·langchain·大语言模型·agent·langgraph
Είναι η κοπέλα7 分钟前
PyTorch 安装与验证
人工智能·pytorch·python
“AI国潮设计-小江”11 分钟前
Python实战 | SDXL批量生成“潮汕英歌舞”国潮甜品IP,附核心Prompt与商用授权思路
开发语言·人工智能·python·prompt·aigc
盘古开天166617 分钟前
PPO算法原理详解(上):从策略梯度到近端策略优化的演进之路
人工智能·算法·机器学习·强化学习·ppo
2601_9628857224 分钟前
如何用 Python 分析股票的日历效应?(星期效应与月份效应,附数据挖掘陷阱)
开发语言·python·数据挖掘
czq_268671948726 分钟前
Python打卡第30天
python·机器学习
FYKJ_201033 分钟前
SSM校园互助与闲置交易平台62145-计算机课程设计、毕业设计
java·spring boot·python·mysql·架构·spark·课程设计
“AI国潮设计-小江”36 分钟前
Python实战 | SDXL批量生成“带炸英歌”国潮IP:从海报到门店落地(附核心Prompt与授权思路)
开发语言·人工智能·python·prompt·aigc
我就是不信40 分钟前
深入理解 Python 虚拟机:字典(dict)的优化
开发语言·python·哈希算法