python计算precision@k、recall@k和f1_score@k

2024-04-24 20:38

本文主要是介绍python计算precision@k、recall@k和f1_score@k,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

sklearn.metrics中的评估函数只能对同一样本的单个预测结果进行评估,如下所示:

from sklearn.metrics import classification_reporty_true = [0, 5, 0, 3, 4, 2, 1, 1, 5, 4]
y_pred = [0, 2, 4, 5, 2, 3, 1, 1, 4, 2]print(classification_report(y_true, y_pred))

而我们经常会遇到需要对同一样本的top-k个预测结果进行评估的情况,此时算法针对单个样本的预测结果是一个按可能性排序的列表,如下所示:

y_true = [0, 5, 0, 3, 4, 2, 1, 1, 5, 4]
y_pred = [[0, 0, 2, 1, 5],[2, 2, 4, 1, 4],[4, 5, 1, 3, 5],[5, 4, 2, 4, 3],[2, 0, 0, 2, 3],[3, 3, 4, 1, 4],[1, 1, 0, 1, 2],[1, 4, 4, 2, 4],[4, 1, 3, 3, 5],[2, 4, 2, 2, 3]]

针对以上这种情况,我们要如何评估算法的好坏呢?我们需要precision@k、recall@k和f1_score@k等指标,下面给出计算这些指标的函数及示例。

from _tkinter import _flatten# 统计所有的类别
def get_unique_labels(y_true, y_pred):y_true_set = set(y_true)y_pred_set = set(_flatten(y_pred))unique_label_set = y_true_set | y_pred_setunique_label = list(unique_label_set)return unique_label# y_true: 1d-list-like
# y_pred: 2d-list-like
# k:针对top-k各结果进行计算(k <= y_pred.shape[1])
def precision_recall_fscore_k(y_trues, y_preds, k=3, digs=2):# 取每个样本的top-k个预测结果!y_preds = [pred[:k] for pred in y_preds]unique_labels = get_unique_labels(y_trues, y_preds)num_classes = len(unique_labels)# 计算每个类别的precision、recall、f1-score、supportresults_dict = {}results = ''for label in unique_labels:current_label_result = []# TP + FNtp_fn = y_trues.count(label)# TP + FPtp_fp = 0for y_pred in y_preds:if label in y_pred:tp_fp += 1# TPtp = 0for i in range(len(y_trues)):if y_trues[i] == label and label in y_preds[i]:tp += 1support = tp_fntry:precision = round(tp/tp_fp, digs)recall = round(tp/tp_fn, digs)f1_score = round(2*(precision * recall) / (precision + recall), digs)except ZeroDivisionError:precision = 0recall = 0f1_score = 0current_label_result.append(precision)current_label_result.append(recall)current_label_result.append(f1_score)current_label_result.append(support)# 输出第一行results_dict[str(label)] = current_label_resulttitle = '\t' + 'precision@' + str(k) + '\t' + 'recall@' + str(k) + '\t' + 'f1_score@' + str(k) + '\t' + 'support' + '\n'results += titlefor k, v in sorted(results_dict.items()):current_line = str(k) + '\t' + str(v[0]) + '\t' + str(v[1]) + '\t' + str(v[2]) + '\t' + str(v[3]) + '\n'results += current_linesums = len(y_trues)# 注意macro avg和weighted avg计算方式的不同macro_avg_results = [(v[0], v[1], v[2]) for k, v in sorted(results_dict.items())]weighted_avg_results = [(v[0]*v[3], v[1]*v[3], v[2]*v[3]) for k, v in sorted(results_dict.items())]# 计算macro avgmacro_precision = 0macro_recall = 0macro_f1_score = 0for macro_avg_result in macro_avg_results:macro_precision += macro_avg_result[0]macro_recall += macro_avg_result[1]macro_f1_score += macro_avg_result[2]macro_precision /= num_classesmacro_recall /= num_classesmacro_f1_score /= num_classes# 计算weighted avgweighted_precision = 0weighted_recall = 0weighted_f1_score = 0for weighted_avg_result in weighted_avg_results:weighted_precision += weighted_avg_result[0]weighted_recall += weighted_avg_result[1]weighted_f1_score += weighted_avg_result[2]weighted_precision /= sumsweighted_recall /= sumsweighted_f1_score /= sumsmacro_avg_line = 'macro avg' + '\t' + str(round(macro_precision, digs)) + '\t' + str(round(macro_recall, digs)) + '\t' + str(round(macro_f1_score, digs)) + '\t' + str(sums) +'\n'weighted_avg_line = 'weighted avg' + '\t' + str(round(weighted_precision, digs)) + '\t' + str(round(weighted_recall, digs)) + '\t' + str(round(weighted_f1_score, digs)) + '\t' + str(sums)results += macro_avg_lineresults += weighted_avg_linereturn resultsif __name__ == '__main__':y_true = [0, 5, 0, 3, 4, 2, 1, 1, 5, 4]y_pred = [[0, 3, 2, 1, 5],[2, 0, 4, 1, 3],[4, 5, 1, 3, 0],[5, 4, 2, 0, 3],[2, 0, 1, 3, 5],[3, 0, 4, 1, 2],[1, 0, 4, 2, 3],[1, 4, 5, 2, 3],[4, 1, 3, 2, 0],[2, 0, 1, 3, 4]]res = precision_recall_fscore_k(y_true, y_pred, k=5, digs=2)print(res)

我们分别取k=1、k=2、k=3、k=4和k=5,看一下效果。

k=1时:

k=3时:

k=5时:

我们进一步看一下随着k值的增大,precision@k、recall@k和f1_score@k值的变化:

写作过程参考了

https://blog.csdn.net/dipizhong7224/article/details/104579159

https://blog.csdn.net/ybdesire/article/details/96507733

这篇关于python计算precision@k、recall@k和f1_score@k的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!


原文地址:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.chinasem.cn/article/932786

相关文章

使用Python实现Windows系统垃圾清理

《使用Python实现Windows系统垃圾清理》Windows自带的磁盘清理工具功能有限,无法深度清理各类垃圾文件,所以本文为大家介绍了如何使用Python+PyQt5开发一个Windows系统垃圾... 目录一、开发背景与工具概述1.1 为什么需要专业清理工具1.2 工具设计理念二、工具核心功能解析2.

Python实现一键PDF转Word(附完整代码及详细步骤)

《Python实现一键PDF转Word(附完整代码及详细步骤)》pdf2docx是一个基于Python的第三方库,专门用于将PDF文件转换为可编辑的Word文档,下面我们就来看看如何通过pdf2doc... 目录引言:为什么需要PDF转Word一、pdf2docx介绍1. pdf2docx 是什么2. by

Python函数返回多个值的多种方法小结

《Python函数返回多个值的多种方法小结》在Python中,函数通常用于封装一段代码,使其可以重复调用,有时,我们希望一个函数能够返回多个值,Python提供了几种不同的方法来实现这一点,需要的朋友... 目录一、使用元组(Tuple):二、使用列表(list)三、使用字典(Dictionary)四、 使

Python程序的文件头部声明小结

《Python程序的文件头部声明小结》在Python文件的顶部声明编码通常是必须的,尤其是在处理非ASCII字符时,下面就来介绍一下两种头部文件声明,具有一定的参考价值,感兴趣的可以了解一下... 目录一、# coding=utf-8二、#!/usr/bin/env python三、运行Python程序四、

python web 开发之Flask中间件与请求处理钩子的最佳实践

《pythonweb开发之Flask中间件与请求处理钩子的最佳实践》Flask作为轻量级Web框架,提供了灵活的请求处理机制,中间件和请求钩子允许开发者在请求处理的不同阶段插入自定义逻辑,实现诸如... 目录Flask中间件与请求处理钩子完全指南1. 引言2. 请求处理生命周期概述3. 请求钩子详解3.1

使用Python实现网页表格转换为markdown

《使用Python实现网页表格转换为markdown》在日常工作中,我们经常需要从网页上复制表格数据,并将其转换成Markdown格式,本文将使用Python编写一个网页表格转Markdown工具,需... 在日常工作中,我们经常需要从网页上复制表格数据,并将其转换成Markdown格式,以便在文档、邮件或

Python使用pynput模拟实现键盘自动输入工具

《Python使用pynput模拟实现键盘自动输入工具》在日常办公和软件开发中,我们经常需要处理大量重复的文本输入工作,所以本文就来和大家介绍一款使用Python的PyQt5库结合pynput键盘控制... 目录概述:当自动化遇上可视化功能全景图核心功能矩阵技术栈深度效果展示使用教程四步操作指南核心代码解析

Python实现pdf电子发票信息提取到excel表格

《Python实现pdf电子发票信息提取到excel表格》这篇文章主要为大家详细介绍了如何使用Python实现pdf电子发票信息提取并保存到excel表格,文中的示例代码讲解详细,感兴趣的小伙伴可以跟... 目录应用场景详细代码步骤总结优化应用场景电子发票信息提取系统主要应用于以下场景:企业财务部门:需

基于Python实现智能天气提醒助手

《基于Python实现智能天气提醒助手》这篇文章主要来和大家分享一个实用的Python天气提醒助手开发方案,这个工具可以方便地集成到青龙面板或其他调度框架中使用,有需要的小伙伴可以参考一下... 目录项目概述核心功能技术实现1. 天气API集成2. AI建议生成3. 消息推送环境配置使用方法完整代码项目特点

使用Python获取JS加载的数据的多种实现方法

《使用Python获取JS加载的数据的多种实现方法》在当今的互联网时代,网页数据的动态加载已经成为一种常见的技术手段,许多现代网站通过JavaScript(JS)动态加载内容,这使得传统的静态网页爬取... 目录引言一、动态 网页与js加载数据的原理二、python爬取JS加载数据的方法(一)分析网络请求1