from sklearn.metrics import roc_curve,auc,confusion_matrix import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt import numpy as np w=pd.read_csv("D:/pythonProject/venv/Trans.csv")#加载文件 w['intercept']=1.0#设定截距 x_c=w.columns[[4,0,1,2]];y_c=w.columns[3] X=w[x_c];y=w[y_c] X=np.array(X);y=np.array(y) zid=np.ones(len(y));zid[:int(len(y)*0.2)]=0 x_x=X[zid==1,:];y_x=y[zid==1] x_t=X[zid==0,:];y_t=y[zid==0] result=sm.Logit(y_x,x_x).fit() print(result.summary) y_p= result.predict(x_t) fpr,tpr, thresholds = roc_curve(y_t,y_p)# roc_auc=auc(fpr,tpr)#算auc的函数 print("Area under the ROC curve : %f" % roc_auc)#算出auc #画图 plt.plot(fpr,tpr,label='ROC')#画基本表 plt.xlabel('FPR')#x轴为fpr,假真率 plt.ylabel('TPR')#y轴是tpr,真真率 #得出结果 print(thresholds[np.argmin(np.abs(tpr-(1-fpr)))])#算最优阈值 print(np.sum(y_t!=1*(y_p>0.3421))/len(y_t))#算误判率 plt.show()#画图

时间: 2024-03-04 14:49:01 浏览: 20
这段代码是一个用于二分类问题的 logistic 回归模型,并使用 ROC 曲线和 AUC 值来评估模型性能的例子。具体解释如下: 1. 加载数据: ```python w=pd.read_csv("D:/pythonProject/venv/Trans.csv")#加载文件 w['intercept']=1.0#设定截距 x_c=w.columns[[4,0,1,2]];y_c=w.columns[3] X=w[x_c];y=w[y_c] X=np.array(X);y=np.array(y) zid=np.ones(len(y));zid[:int(len(y)*0.2)]=0 x_x=X[zid==1,:];y_x=y[zid==1] x_t=X[zid==0,:];y_t=y[zid==0] ``` 这段代码中,首先读取了一个 CSV 文件,然后根据数据的特点对数据进行了一些预处理,如添加了一个截距项,然后将数据集分成了训练集和测试集,比例为 8:2。 2. 训练模型: ```python result=sm.Logit(y_x,x_x).fit() print(result.summary) ``` 这段代码中,使用了 statsmodels 库的 Logit 函数来训练逻辑回归模型,并输出了模型的摘要信息。 3. 预测测试集结果并计算 ROC 曲线和 AUC 值: ```python y_p= result.predict(x_t) fpr,tpr, thresholds = roc_curve(y_t,y_p)# roc_auc=auc(fpr,tpr)#算auc的函数 print("Area under the ROC curve : %f" % roc_auc)#算出auc ``` 这段代码中,首先使用训练好的模型对测试集进行了预测,得到了每个样本属于正类的概率。然后使用 sklearn 库的 roc_curve 函数计算了 ROC 曲线上的 FPR 和 TPR,并使用 auc 函数计算了 ROC 曲线下的面积 AUC。 4. 输出结果并画图: ```python print(thresholds[np.argmin(np.abs(tpr-(1-fpr)))])#算最优阈值 print(np.sum(y_t!=1*(y_p>0.3421))/len(y_t))#算误判率 plt.show()#画图 ``` 这段代码中,首先计算了最优阈值和误判率。最优阈值是使得 FPR 和 TPR 的差值最小的阈值,误判率是分类错误的样本数占总样本数的比例。然后使用 matplotlib 库画出了 ROC 曲线的图像。

相关推荐

import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, recall_score, f1_score, roc_curve, roc_auc_score # 1. 数据读取与处理 data = pd.read_csv('data.csv') X = data.drop('target', axis=1) y = data['target'] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 2. 模型训练 model = LogisticRegression() model.fit(X_train, y_train) # 3. 模型预测 y_pred = model.predict(X_test) y_prob = model.predict_proba(X_test)[:, 1] # 4. 绘制二分类混淆矩阵 confusion_mat = confusion_matrix(y_test, y_pred) plt.imshow(confusion_mat, cmap=plt.cm.Blues) plt.title('Confusion Matrix') plt.colorbar() tick_marks = np.arange(2) plt.xticks(tick_marks, ['0', '1']) plt.yticks(tick_marks, ['0', '1']) plt.xlabel('Predicted Label') plt.ylabel('True Label') for i in range(2): for j in range(2): plt.text(j, i, confusion_mat[i, j], ha='center', va='center', color='white' if confusion_mat[i, j] > confusion_mat.max() / 2 else 'black') plt.show() # 5. 计算精确率、召回率和F1-score precision = precision_score(y_test, y_pred) recall = recall_score(y_test, y_pred) f1 = f1_score(y_test, y_pred) # 6. 计算AUC指标和绘制ROC曲线 auc = roc_auc_score(y_test, y_prob) fpr, tpr, thresholds = roc_curve(y_test, y_prob) plt.plot(fpr, tpr, label='ROC curve (area = %0.2f)' % auc) plt.plot([0, 1], [0, 1], 'k--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC Curve') plt.legend(loc="lower right") plt.show() # 7. 输出结果 print('Precision:', precision) print('Recall:', recall) print('F1-score:', f1) print('AUC:', auc)对每行代码进行注释

from sklearn import metrics from sklearn.model_selection import train_test_split from sklearn.linear_model import LogisticRegression from imblearn.combine import SMOTETomek from sklearn.metrics import auc, roc_curve, roc_auc_score from sklearn.feature_selection import SelectFromModel import pandas as pd import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix #1、数据输入 df_table_all = pd.read_csv(r"D:\trainafter.csv",index_col=0) #2、目标和特征区分 X = df_table_all.drop(["Y"],axis=1).values Y = np.array(df_table_all["Y"]) #3、按比例切割数据 X_train,X_test,Y_train,Y_test = train_test_split(X,Y,test_size=0.3,random_state=0) #4、样本平衡, st= SMOTETomek() X_train_st,Y_train_st = st.fit_resample(X_train,Y_train) #4、特征选择: #创建特征选择模型 sfm = SelectFromModel(LogisticRegression(penalty='l1',C=1.0,solver="liblinear")) #训练特征选择模型 sfm.fit(X_train,Y_train) #讲数据转换,剩下重要的特征 X_train_tiny = sfm.transform(X_train) X_test_tiny = sfm.transform(X_test) #5、创建模型 model = LogisticRegression(penalty='l1',C=1.0,solver="liblinear") model.fit(X_train_st_tiny,Y_train_st) #6、预测 y_pred = model.predict_proba(X_test_st_tiny) y_cate = model.predict(X_test_st_tiny) c=confusion_matrix(Y_test,y_cate) print(c) def report_auc(y_true,y_prob,title,out_name="",lw=2): fpr,tpr,_=roc_curve(y_true,y_prob,pos_label=1) print(fpr) print(tpr) plt.figure() plt.plot(fpr,tpr,color="darkorange",lw=lw,lable="ROC curve") plt.plot([0,1],[0,1],color="yellow",lw=lw,linestyle="--") plt.xlim([0,1]) plt.ylim([0,1.05]) plt.title(title) plt.legend(loc='lower right') plt.show(0) plt.savefig(r"d:\LR"+out_name,dpi=800) plt.close("all") report_auc(Y_test,y_pred[:,1],"Logistic with L1 panetly",'LG')

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曲线

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() # 读取新数据文件并预测结果 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)输出混淆矩阵图片以及各分类精度

最新推荐

recommend-type

微信小程序-番茄时钟源码

微信小程序番茄时钟的源码,支持进一步的修改。番茄钟,指的是把工作任务分解成半小时左右,集中精力工作25分钟后休息5分钟,如此视作种一个“番茄”,而“番茄工作法”的流程能使下一个30分钟更有动力。
recommend-type

激光雷达专题研究:迈向高阶智能化关键,前瞻布局把握行业脉搏.pdf

电子元件 电子行业 行业分析 数据分析 数据报告 行业报告
recommend-type

安享智慧理财测试项目Mock服务代码

安享智慧理财测试项目Mock服务代码
recommend-type

课程设计 基于SparkMLlib的ALS算法的电影推荐系统源码+详细文档+全部数据齐全.zip

【资源说明】 课程设计 基于SparkMLlib的ALS算法的电影推荐系统源码+详细文档+全部数据齐全.zip课程设计 基于SparkMLlib的ALS算法的电影推荐系统源码+详细文档+全部数据齐全.zip 【备注】 1、该项目是高分毕业设计项目源码,已获导师指导认可通过,答辩评审分达到95分 2、该资源内项目代码都经过测试运行成功,功能ok的情况下才上传的,请放心下载使用! 3、本项目适合计算机相关专业(如软件工程、计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载使用,也可作为毕业设计、课程设计、作业、项目初期立项演示等,当然也适合小白学习进阶。 4、如果基础还行,可以在此代码基础上进行修改,以实现其他功能,也可直接用于毕设、课设、作业等。 欢迎下载,沟通交流,互相学习,共同进步!
recommend-type

华中科技大学电信专业 课程资料 作业 代码 实验报告-雷达与信息对抗-内含源码和说明书.zip

华中科技大学电信专业 课程资料 作业 代码 实验报告-雷达与信息对抗-内含源码和说明书.zip
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

解释minorization-maximization (MM) algorithm,并给出matlab代码编写的例子

Minorization-maximization (MM) algorithm是一种常用的优化算法,用于求解非凸问题或含有约束的优化问题。该算法的基本思想是通过构造一个凸下界函数来逼近原问题,然后通过求解凸下界函数的最优解来逼近原问题的最优解。具体步骤如下: 1. 初始化参数 $\theta_0$,设 $k=0$; 2. 构造一个凸下界函数 $Q(\theta|\theta_k)$,使其满足 $Q(\theta_k|\theta_k)=f(\theta_k)$; 3. 求解 $Q(\theta|\theta_k)$ 的最优值 $\theta_{k+1}=\arg\min_\theta Q(
recommend-type

JSBSim Reference Manual

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