python实现 P-R曲线类,不用sklearn

时间: 2024-04-18 07:33:37 浏览: 14
你可以使用Python来实现P-R曲线类,以下是一个简单的示例代码: ```python import matplotlib.pyplot as plt class PRCurve: def __init__(self, y_true, y_scores): self.y_true = y_true self.y_scores = y_scores def precision_recall_curve(self): thresholds = sorted(set(self.y_scores), reverse=True) precisions = [] recalls = [] for threshold in thresholds: y_pred = [1 if score >= threshold else 0 for score in self.y_scores] true_positives = sum([1 for yt, yp in zip(self.y_true, y_pred) if yt == 1 and yp == 1]) false_positives = sum([1 for yt, yp in zip(self.y_true, y_pred) if yt == 0 and yp == 1]) false_negatives = sum([1 for yt, yp in zip(self.y_true, y_pred) if yt == 1 and yp == 0]) precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0 recall = true_positives / (true_positives + false_negatives) if (true_positives + false_negatives) > 0 else 0 precisions.append(precision) recalls.append(recall) return precisions, recalls def plot(self): precisions, recalls = self.precision_recall_curve() plt.plot(recalls, precisions, marker='.') plt.xlabel('Recall') plt.ylabel('Precision') plt.title('P-R Curve') plt.show() ``` 使用示例: ```python # 实例化 PRCurve 类,传入真实标签和预测分数 y_true = [1, 0, 1, 1, 0, 0, 1] y_scores = [0.9, 0.6, 0.8, 0.7, 0.4, 0.3, 0.5] pr_curve = PRCurve(y_true, y_scores) # 绘制 P-R 曲线 pr_curve.plot() ``` 这段代码实现了一个P-R曲线类,其中`y_true`是真实的标签,`y_scores`是预测的分数。`precision_recall_curve`方法计算并返回精确率和召回率的列表,`plot`方法用于绘制P-R曲线。你可以根据你的实际需求进行修改和优化。

相关推荐

from sklearn.datasets import load_iris from sklearn. model_selection import train_test_split from sklearn.metrics import classification_report from sklearn. neighbors import KNeighborsClassifier from sklearn. metrics import roc_curve, auc import matplotlib.pyplot as plt from sklearn. metrics import confusion_matrix import seaborn as sns import scikitplot as skplt #加载数据集 iris = load_iris() data = iris['data'] label = iris['target'] #数据集的划分 x_train,x_test,y_train,y_test = train_test_split(data,label,test_size=0.3) print(x_train) #模型构建 model = KNeighborsClassifier(n_neighbors=5) model.fit(x_train,y_train) #模型评估 #(1)精确率,召回率,F1分数,准确率(宏平均和微平均) predict = model. predict(x_test) result = classification_report(y_test,predict) print(result) # (2) 混淆矩阵 confusion_matrix = confusion_matrix(y_test, predict) print('混淆矩阵:', confusion_matrix) sns.set(font_scale=1) sns.heatmap(confusion_matrix, annot=True, annot_kws={"size", 16}, cmap=plt.cm.Blues) plt.title('Confusion Matrix') plt.ylabel('True label' ) plt.xlabel('Predicted label') plt.savefig('Confusion matrix. pdf') plt.show() #(3)ROC曲线 Y_pred_prob = model. predict_proba(x_test) plt.figure(figsize= (7,7)) ax= plt. subplot() skplt.metrics.plot_roc_curve(y_test,Y_pred_prob,ax= ax) ax.set_xlabel('False Positive Rate', fontsize = 20) ax.set_ylabel('True Positive Rate ',fontsize = 20) ax.set_title('ROC Areas ',fontsize = 20) plt.xlim((0, 1)) plt.ylim((0, 1)) plt.xticks(fontsize = 18) plt.yticks(fontsize = 18) plt.legend(fontsize =18) plt.savefig(' ROC.pdf') plt.show( ) #(4)P_R曲线 from sklearn.metrics import precision_recall_curve precision, recall, _ =precision_recall_curve(y_test) plt.fill_between(recall, precision,color='b') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.0]) plt.xlim([0.0, 1.0]) plt.plot(recall, precision) plt.title("Precision-Recall") plt.show()

最新推荐

recommend-type

对python sklearn one-hot编码详解

今天小编就为大家分享一篇对python sklearn one-hot编码详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

python实点云分割k-means(sklearn)详解

主要为大家详细介绍了Python实点云分割k-means,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

TF-IDF算法解析与Python实现方法详解

主要介绍了TF-IDF算法解析与Python实现方法详解,文章介绍了tf-idf算法的主要思想,分享了Python实现tr-idf算法所必要的预处理过程,以及具体实现代码等相关内容,具有一定参考价值,需要的朋友可以了解下。
recommend-type

python sklearn包——混淆矩阵、分类报告等自动生成方式

今天小编就为大家分享一篇python sklearn包——混淆矩阵、分类报告等自动生成方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
recommend-type

Python使用sklearn库实现的各种分类算法简单应用小结

主要介绍了Python使用sklearn库实现的各种分类算法,结合实例形式分析了Python使用sklearn库实现的KNN、SVM、LR、决策树、随机森林等算法实现技巧,需要的朋友可以参考下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

前端深拷贝 和浅拷贝有哪些方式,你在哪里使用过

前端深拷贝和浅拷贝的方式有很多,下面列举几种常用的方式: 深拷贝: 1. JSON.parse(JSON.stringify(obj)),该方法可以将对象序列化为字符串,再将字符串反序列化为新的对象,从而实现深拷贝。但是该方法有一些限制,例如无法拷贝函数、RegExp等类型的数据。 2. 递归拷贝,即遍历对象的每个属性并进行拷贝,如果属性值是对象,则递归进行拷贝。 3. 使用第三方库如lodash、jQuery等提供的深拷贝方法。 浅拷贝: 1. Object.assign(target, obj1, obj2, ...),该方法可以将源对象的属性浅拷贝到目标对象中,如果有相同的属性,则会
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。