from sklearn.metrics import classification_report,confusion_matrix,plot_roc_curve,roc_auc_score,f1_score,roc_curve,auc

时间: 2024-01-01 14:06:52 浏览: 40
这是Python的一个常用机器学习库Scikit-learn中的一些评价指标和可视化函数。其中,classification_report和confusion_matrix可以用于分类问题的评价,plot_roc_curve和roc_auc_score可以用于二分类问题的评价,f1_score可以同时考虑模型的精确度和召回率,roc_curve和auc可以用于绘制ROC曲线和计算AUC值。这些评价指标和可视化函数能够帮助我们更好地了解模型的性能和优化方向。
相关问题

X_train,X_test,y_train,y_test=train_test_split(X ,y,test_size=0.2,random_state=1);reg = 0.01 LogRegModel = LogisticRegression(C=1/reg, solver = 'liblinear').fit(X_train, y_train) preds = LogRegModel.predict(X_test) print('accuracy', metrics.accuracy_score(y_test, preds)) print('recall', metrics.recall_score(y_test, preds)) print('precision', metrics.precision_score(y_test, preds)) print('f1-score', metrics.f1_score(y_test, preds));from sklearn. metrics import classification_report print(classification_report(y_test, preds));from sklearn.metrics import roc_curve from sklearn.metrics import confusion_matrix import matplotlib import matplotlib.pyplot as plt %matplotlib inline y_scores = LogRegModel.predict_proba(X_test) print(y_scores) # calculate ROC curve fpr, tpr, thresholds = roc_curve(y_test, y_scores[:,1]) # plot ROC curve fig = plt.figure(figsize=(6, 6)) # Plot the diagonal 50% line plt.plot([0, 1], [0, 1], 'k--') # Plot the FPR and TPR achieved by our model plt.plot(fpr, tpr) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.show()

这是一个二分类问题的逻辑回归模型的评估过程,其中使用了 train_test_split 进行数据集的划分,然后使用 LogisticRegression 进行模型的训练,并对测试集进行预测,使用了多个评价指标,如准确率、召回率、精确率、F1-score 和分类报告等;此外还使用了 ROC 曲线和 AUC 值来评估模型的性能。

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()

这是一段 Python 代码,主要包括从Scikit-learn库中导入了一些数据集、分类器、评估指标和可视化工具的模块。其中load_iris用于加载鸢尾花数据集,train_test_split用于将数据集分为训练集和测试集,classification_report用于评估分类器的性能,KNeighborsClassifier是K近邻分类器,roc_curve和auc用于评估二元分类器的性能,matplotlib.pyplot和seaborn是可视化工具,confusion_matrix和scikitplot是评估和可视化混淆矩阵的工具。

相关推荐

import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix,classification_report import seaborn as sns import matplotlib.pyplot as plt # 读取数据 data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测样本.xlsx') # 分割训练集和验证集 train_data = data.sample(frac=0.8, random_state=1) test_data = data.drop(train_data.index) # 定义特征变量和目标变量 features = ['高程', '起伏度', '桥梁长', '道路长', '平均坡度', '平均地温', 'T小于0', '相态'] target = '交通风险' # 训练随机森林模型 rf = RandomForestClassifier(n_estimators=100, random_state=1) rf.fit(train_data[features], train_data[target]) # 在验证集上进行预测并计算精度、召回率和F1值等指标 pred = rf.predict(test_data[features]) accuracy = accuracy_score(test_data[target], pred) confusion_mat = confusion_matrix(test_data[target], pred) classification_rep = classification_report(test_data[target], pred) print('Accuracy:', accuracy) print('Confusion matrix:') print(confusion_mat) print('Classification report:') print(classification_rep) # 输出混淆矩阵图片 sns.heatmap(confusion_mat, annot=True, cmap="Blues") plt.show() # 读取新数据文件并预测结果 new_data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096.xlsx') new_pred = rf.predict(new_data[features]) new_data['交通风险预测结果'] = new_pred new_data.to_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096结果.xlsx', index=False)修改代码使得显示决策树模型以及多分类的roc曲线和auc值

import pandas as pd from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import accuracy_score, confusion_matrix,classification_report, roc_curve, auc import seaborn as sns import matplotlib.pyplot as plt # 读取数据 data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测样本.xlsx') # 分割训练集和验证集 train_data = data.sample(frac=0.8, random_state=1) test_data = data.drop(train_data.index) # 定义特征变量和目标变量 features = ['高程', '起伏度', '桥梁长', '道路长', '平均坡度', '平均地温', 'T小于0', '相态'] target = '交通风险' # 训练随机森林模型 rf = RandomForestClassifier(n_estimators=100, random_state=1) rf.fit(train_data[features], train_data[target]) # 在验证集上进行预测并计算精度、召回率和F1值等指标 pred = rf.predict(test_data[features]) accuracy = accuracy_score(test_data[target], pred) confusion_mat = confusion_matrix(test_data[target], pred) classification_rep = classification_report(test_data[target], pred) print('Accuracy:', accuracy) print('Confusion matrix:') print(confusion_mat) print('Classification report:') print(classification_rep) # 输出混淆矩阵图片 sns.heatmap(confusion_mat, annot=True, cmap="Blues") plt.show() # 计算并绘制ROC曲线和AUC值 fpr, tpr, thresholds = roc_curve(test_data[target], pred) roc_auc = auc(fpr, tpr) print('AUC:', roc_auc) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.2f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() # 读取新数据文件并预测结果 new_data = pd.read_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096.xlsx') new_pred = rf.predict(new_data[features]) new_data['交通风险预测结果'] = new_pred new_data.to_excel('E:/桌面/预测脆弱性/20230523/预测样本/预测结果/交通风险预测096结果.xlsx', index=False)改进代码使用多元roc曲线

修改和补充下列代码得到十折交叉验证的平均auc值和平均aoc曲线,平均分类报告以及平均混淆矩阵 min_max_scaler = MinMaxScaler() X_train1, X_test1 = x[train_id], x[test_id] y_train1, y_test1 = y[train_id], y[test_id] # apply the same scaler to both sets of data X_train1 = min_max_scaler.fit_transform(X_train1) X_test1 = min_max_scaler.transform(X_test1) X_train1 = np.array(X_train1) X_test1 = np.array(X_test1) config = get_config() tree = gcForest(config) tree.fit(X_train1, y_train1) y_pred11 = tree.predict(X_test1) y_pred1.append(y_pred11 X_train.append(X_train1) X_test.append(X_test1) y_test.append(y_test1) y_train.append(y_train1) X_train_fuzzy1, X_test_fuzzy1 = X_fuzzy[train_id], X_fuzzy[test_id] y_train_fuzzy1, y_test_fuzzy1 = y_sampled[train_id], y_sampled[test_id] X_train_fuzzy1 = min_max_scaler.fit_transform(X_train_fuzzy1) X_test_fuzzy1 = min_max_scaler.transform(X_test_fuzzy1) X_train_fuzzy1 = np.array(X_train_fuzzy1) X_test_fuzzy1 = np.array(X_test_fuzzy1) config = get_config() tree = gcForest(config) tree.fit(X_train_fuzzy1, y_train_fuzzy1) y_predd = tree.predict(X_test_fuzzy1) y_pred.append(y_predd) X_test_fuzzy.append(X_test_fuzzy1) y_test_fuzzy.append(y_test_fuzzy1)y_pred = to_categorical(np.concatenate(y_pred), num_classes=3) y_pred1 = to_categorical(np.concatenate(y_pred1), num_classes=3) y_test = to_categorical(np.concatenate(y_test), num_classes=3) y_test_fuzzy = to_categorical(np.concatenate(y_test_fuzzy), num_classes=3) print(y_pred.shape) print(y_pred1.shape) print(y_test.shape) print(y_test_fuzzy.shape) # 深度森林 report1 = classification_report(y_test, y_prprint("DF",report1) report = classification_report(y_test_fuzzy, y_pred) print("DF-F",report) mse = mean_squared_error(y_test, y_pred1) rmse = math.sqrt(mse) print('深度森林RMSE:', rmse) print('深度森林Accuracy:', accuracy_score(y_test, y_pred1)) mse = mean_squared_error(y_test_fuzzy, y_pred) rmse = math.sqrt(mse) print('F深度森林RMSE:', rmse) print('F深度森林Accuracy:', accuracy_score(y_test_fuzzy, y_pred)) mse = mean_squared_error(y_test, y_pred) rmse = math.sqrt(mse) print('F?深度森林RMSE:', rmse) print('F?深度森林Accuracy:', accuracy_score(y_test, y_pred))

最新推荐

recommend-type

nodejs-x64-0.10.21.tgz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

node-v4.1.1-linux-armv6l.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
recommend-type

node-v4.1.0-linux-arm64.tar.xz

Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。
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

实现实时数据湖架构:Kafka与Hive集成

![实现实时数据湖架构:Kafka与Hive集成](https://img-blog.csdnimg.cn/img_convert/10eb2e6972b3b6086286fc64c0b3ee41.jpeg) # 1. 实时数据湖架构概述** 实时数据湖是一种现代数据管理架构,它允许企业以低延迟的方式收集、存储和处理大量数据。与传统数据仓库不同,实时数据湖不依赖于预先定义的模式,而是采用灵活的架构,可以处理各种数据类型和格式。这种架构为企业提供了以下优势: - **实时洞察:**实时数据湖允许企业访问最新的数据,从而做出更明智的决策。 - **数据民主化:**实时数据湖使各种利益相关者都可
recommend-type

list根据id查询pid 然后依次获取到所有的子节点数据

可以使用递归的方式来实现根据id查询pid并获取所有子节点数据。具体实现可以参考以下代码: ``` def get_children_nodes(nodes, parent_id): children = [] for node in nodes: if node['pid'] == parent_id: node['children'] = get_children_nodes(nodes, node['id']) children.append(node) return children # 测试数
recommend-type

JSBSim Reference Manual

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

"互动学习:行动中的多样性与论文攻读经历"

多样性她- 事实上SCI NCES你的时间表ECOLEDO C Tora SC和NCESPOUR l’Ingén学习互动,互动学习以行动为中心的强化学习学会互动,互动学习,以行动为中心的强化学习计算机科学博士论文于2021年9月28日在Villeneuve d'Asq公开支持马修·瑟林评审团主席法布里斯·勒菲弗尔阿维尼翁大学教授论文指导奥利维尔·皮耶昆谷歌研究教授:智囊团论文联合主任菲利普·普雷教授,大学。里尔/CRISTAL/因里亚报告员奥利维耶·西格德索邦大学报告员卢多维奇·德诺耶教授,Facebook /索邦大学审查员越南圣迈IMT Atlantic高级讲师邀请弗洛里安·斯特鲁布博士,Deepmind对于那些及时看到自己错误的人...3谢谢你首先,我要感谢我的两位博士生导师Olivier和Philippe。奥利维尔,"站在巨人的肩膀上"这句话对你来说完全有意义了。从科学上讲,你知道在这篇论文的(许多)错误中,你是我可以依
recommend-type

实现实时监控告警系统:Kafka与Grafana整合

![实现实时监控告警系统:Kafka与Grafana整合](https://imgconvert.csdnimg.cn/aHR0cHM6Ly9tbWJpei5xcGljLmNuL21tYml6X2pwZy9BVldpY3ladXVDbEZpY1pLWmw2bUVaWXFUcEdLT1VDdkxRSmQxZXB5R1lxaWNlUjA2c0hFek5Qc3FyRktudFF1VDMxQVl3QTRXV2lhSWFRMEFRc0I1cW1ZOGcvNjQw?x-oss-process=image/format,png) # 1.1 Kafka集群架构 Kafka集群由多个称为代理的服务器组成,这