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提取视频文件中的音频

《详解如何使用Python提取视频文件中的音频》在多媒体处理中,有时我们需要从视频文件中提取音频,本文为大家整理了几种使用Python编程语言提取视频文件中的音频的方法,大家可以根据需要进行选择... 目录引言代码部分方法扩展引言在多媒体处理中,有时我们需要从视频文件中提取音频,以便进一步处理或分析。本文

python多种数据类型输出为Excel文件

《python多种数据类型输出为Excel文件》本文主要介绍了将Python中的列表、元组、字典和集合等数据类型输出到Excel文件中,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参... 目录一.列表List二.字典dict三.集合set四.元组tuplepython中的列表、元组、字典

VSCode配置Anaconda Python环境的实现

《VSCode配置AnacondaPython环境的实现》VisualStudioCode中可以使用Anaconda环境进行Python开发,本文主要介绍了VSCode配置AnacondaPytho... 目录前言一、安装 Visual Studio Code 和 Anaconda二、创建或激活 conda

pytorch+torchvision+python版本对应及环境安装

《pytorch+torchvision+python版本对应及环境安装》本文主要介绍了pytorch+torchvision+python版本对应及环境安装,安装过程中需要注意Numpy版本的降级,... 目录一、版本对应二、安装命令(pip)1. 版本2. 安装全过程3. 命令相关解释参考文章一、版本对

讯飞webapi语音识别接口调用示例代码(python)

《讯飞webapi语音识别接口调用示例代码(python)》:本文主要介绍如何使用Python3调用讯飞WebAPI语音识别接口,重点解决了在处理语音识别结果时判断是否为最后一帧的问题,通过运行代... 目录前言一、环境二、引入库三、代码实例四、运行结果五、总结前言基于python3 讯飞webAPI语音

基于Python开发PDF转PNG的可视化工具

《基于Python开发PDF转PNG的可视化工具》在数字文档处理领域,PDF到图像格式的转换是常见需求,本文介绍如何利用Python的PyMuPDF库和Tkinter框架开发一个带图形界面的PDF转P... 目录一、引言二、功能特性三、技术架构1. 技术栈组成2. 系统架构javascript设计3.效果图

Python如何在Word中生成多种不同类型的图表

《Python如何在Word中生成多种不同类型的图表》Word文档中插入图表不仅能直观呈现数据,还能提升文档的可读性和专业性,本文将介绍如何使用Python在Word文档中创建和自定义各种图表,需要的... 目录在Word中创建柱形图在Word中创建条形图在Word中创建折线图在Word中创建饼图在Word

Python Excel实现自动添加编号

《PythonExcel实现自动添加编号》这篇文章主要为大家详细介绍了如何使用Python在Excel中实现自动添加编号效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1、背景介绍2、库的安装3、核心代码4、完整代码1、背景介绍简单的说,就是在Excel中有一列h=会有重复

Python FastAPI入门安装使用

《PythonFastAPI入门安装使用》FastAPI是一个现代、快速的PythonWeb框架,用于构建API,它基于Python3.6+的类型提示特性,使得代码更加简洁且易于绶护,这篇文章主要介... 目录第一节:FastAPI入门一、FastAPI框架介绍什么是ASGI服务(WSGI)二、FastAP

Python中Windows和macOS文件路径格式不一致的解决方法

《Python中Windows和macOS文件路径格式不一致的解决方法》在Python中,Windows和macOS的文件路径字符串格式不一致主要体现在路径分隔符上,这种差异可能导致跨平台代码在处理文... 目录方法 1:使用 os.path 模块方法 2:使用 pathlib 模块(推荐)方法 3:统一使