利用scikitlearn画ROC曲线实例


Posted in Python onJuly 02, 2020

一个完整的数据挖掘模型,最后都要进行模型评估,对于二分类来说,AUC,ROC这两个指标用到最多,所以 利用sklearn里面相应的函数进行模块搭建。

具体实现的代码可以参照下面博友的代码,评估svm的分类指标。注意里面的一些细节需要注意,一个是调用roc_curve 方法时,指明目标标签,否则会报错。

具体是这个参数的设置pos_label ,以前在unionbigdata实习时学到的。

重点是以下的代码需要根据实际改写:

mean_tpr = 0.0 
  mean_fpr = np.linspace(0, 1, 100) 
  all_tpr = []
  
  y_target = np.r_[train_y,test_y]
  cv = StratifiedKFold(y_target, n_folds=6)
 
    #画ROC曲线和计算AUC
    fpr, tpr, thresholds = roc_curve(test_y, predict,pos_label = 2)##指定正例标签,pos_label = ###########在数之联的时候学到的,要制定正例
    
    mean_tpr += interp(mean_fpr, fpr, tpr)     #对mean_tpr在mean_fpr处进行插值,通过scipy包调用interp()函数 
    mean_tpr[0] = 0.0                #初始处为0 
    roc_auc = auc(fpr, tpr) 
    #画图,只需要plt.plot(fpr,tpr),变量roc_auc只是记录auc的值,通过auc()函数能计算出来 
    plt.plot(fpr, tpr, lw=1, label='ROC %s (area = %0.3f)' % (classifier, roc_auc))

然后是博友的参考代码:

# -*- coding: utf-8 -*- 
""" 
Created on Sun Apr 19 08:57:13 2015 
@author: shifeng 
""" 
print(__doc__) 
 
import numpy as np 
from scipy import interp 
import matplotlib.pyplot as plt 
 
from sklearn import svm, datasets 
from sklearn.metrics import roc_curve, auc 
from sklearn.cross_validation import StratifiedKFold 
 
############################################################################### 
# Data IO and generation,导入iris数据,做数据准备 
 
# import some data to play with 
iris = datasets.load_iris() 
X = iris.data 
y = iris.target 
X, y = X[y != 2], y[y != 2]#去掉了label为2,label只能二分,才可以。 
n_samples, n_features = X.shape 
 
# Add noisy features 
random_state = np.random.RandomState(0) 
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)] 
 
############################################################################### 
# Classification and ROC analysis 
#分类,做ROC分析 
 
# Run classifier with cross-validation and plot ROC curves 
#使用6折交叉验证,并且画ROC曲线 
cv = StratifiedKFold(y, n_folds=6) 
classifier = svm.SVC(kernel='linear', probability=True, 
           random_state=random_state)#注意这里,probability=True,需要,不然预测的时候会出现异常。另外rbf核效果更好些。 
mean_tpr = 0.0 
mean_fpr = np.linspace(0, 1, 100) 
all_tpr = [] 
 
for i, (train, test) in enumerate(cv): 
  #通过训练数据,使用svm线性核建立模型,并对测试集进行测试,求出预测得分 
  probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) 
#  print set(y[train])           #set([0,1]) 即label有两个类别 
#  print len(X[train]),len(X[test])    #训练集有84个,测试集有16个 
#  print "++",probas_           #predict_proba()函数输出的是测试集在lael各类别上的置信度, 
#  #在哪个类别上的置信度高,则分为哪类 
  # Compute ROC curve and area the curve 
  #通过roc_curve()函数,求出fpr和tpr,以及阈值 
  fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) 
  mean_tpr += interp(mean_fpr, fpr, tpr)     #对mean_tpr在mean_fpr处进行插值,通过scipy包调用interp()函数 
  mean_tpr[0] = 0.0                #初始处为0 
  roc_auc = auc(fpr, tpr) 
  #画图,只需要plt.plot(fpr,tpr),变量roc_auc只是记录auc的值,通过auc()函数能计算出来 
  plt.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc)) 
 
#画对角线 
plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') 
 
mean_tpr /= len(cv)           #在mean_fpr100个点,每个点处插值插值多次取平均 
mean_tpr[-1] = 1.0           #坐标最后一个点为(1,1) 
mean_auc = auc(mean_fpr, mean_tpr)   #计算平均AUC值 
#画平均ROC曲线 
#print mean_fpr,len(mean_fpr) 
#print mean_tpr 
plt.plot(mean_fpr, mean_tpr, 'k--', 
     label='Mean ROC (area = %0.2f)' % mean_auc, lw=2) 
 
plt.xlim([-0.05, 1.05]) 
plt.ylim([-0.05, 1.05]) 
plt.xlabel('False Positive Rate') 
plt.ylabel('True Positive Rate') 
plt.title('Receiver operating characteristic example') 
plt.legend(loc="lower right") 
plt.show()

补充知识:批量进行One-hot-encoder且进行特征字段拼接,并完成模型训练demo

import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.feature.{StringIndexer, OneHotEncoder}
import org.apache.spark.ml.feature.VectorAssembler
import ml.dmlc.xgboost4j.scala.spark.{XGBoostEstimator, XGBoostClassificationModel}
import org.apache.spark.ml.evaluation.BinaryClassificationEvaluator
import org.apache.spark.ml.tuning.{ParamGridBuilder, CrossValidator}
import org.apache.spark.ml.PipelineModel
 
val data = (spark.read.format("csv")
 .option("sep", ",")
 .option("inferSchema", "true")
 .option("header", "true")
 .load("/Affairs.csv"))
 
data.createOrReplaceTempView("res1")
val affairs = "case when affairs>0 then 1 else 0 end as affairs,"
val df = (spark.sql("select " + affairs +
 "gender,age,yearsmarried,children,religiousness,education,occupation,rating" +
 " from res1 "))
 
val categoricals = df.dtypes.filter(_._2 == "StringType") map (_._1)
val indexers = categoricals.map(
 c => new StringIndexer().setInputCol(c).setOutputCol(s"${c}_idx")
)
 
val encoders = categoricals.map(
 c => new OneHotEncoder().setInputCol(s"${c}_idx").setOutputCol(s"${c}_enc").setDropLast(false)
)
 
val colArray_enc = categoricals.map(x => x + "_enc")
val colArray_numeric = df.dtypes.filter(_._2 != "StringType") map (_._1)
val final_colArray = (colArray_numeric ++ colArray_enc).filter(!_.contains("affairs"))
val vectorAssembler = new VectorAssembler().setInputCols(final_colArray).setOutputCol("features")
 
/*
val pipeline = new Pipeline().setStages(indexers ++ encoders ++ Array(vectorAssembler))
pipeline.fit(df).transform(df)
*/
 
///
// Create an XGBoost Classifier 
val xgb = new XGBoostEstimator(Map("num_class" -> 2, "num_rounds" -> 5, "objective" -> "binary:logistic", "booster" -> "gbtree")).setLabelCol("affairs").setFeaturesCol("features")
 
// XGBoost paramater grid
val xgbParamGrid = (new ParamGridBuilder()
  .addGrid(xgb.round, Array(10))
  .addGrid(xgb.maxDepth, Array(10,20))
  .addGrid(xgb.minChildWeight, Array(0.1))
  .addGrid(xgb.gamma, Array(0.1))
  .addGrid(xgb.subSample, Array(0.8))
  .addGrid(xgb.colSampleByTree, Array(0.90))
  .addGrid(xgb.alpha, Array(0.0))
  .addGrid(xgb.lambda, Array(0.6))
  .addGrid(xgb.scalePosWeight, Array(0.1))
  .addGrid(xgb.eta, Array(0.4))
  .addGrid(xgb.boosterType, Array("gbtree"))
  .addGrid(xgb.objective, Array("binary:logistic")) 
  .build())
 
// Create the XGBoost pipeline
val pipeline = new Pipeline().setStages(indexers ++ encoders ++ Array(vectorAssembler, xgb))
 
// Setup the binary classifier evaluator
val evaluator = (new BinaryClassificationEvaluator()
  .setLabelCol("affairs")
  .setRawPredictionCol("prediction")
  .setMetricName("areaUnderROC"))
 
// Create the Cross Validation pipeline, using XGBoost as the estimator, the
// Binary Classification evaluator, and xgbParamGrid for hyperparameters
val cv = (new CrossValidator()
  .setEstimator(pipeline)
  .setEvaluator(evaluator)
  .setEstimatorParamMaps(xgbParamGrid)
  .setNumFolds(3)
  .setSeed(0))
 
 // Create the model by fitting the training data
val xgbModel = cv.fit(df)
 
 // Test the data by scoring the model
val results = xgbModel.transform(df)
 
// Print out a copy of the parameters used by XGBoost, attention pipeline
(xgbModel.bestModel.asInstanceOf[PipelineModel]
 .stages(5).asInstanceOf[XGBoostClassificationModel]
 .extractParamMap().toSeq.foreach(println))
results.select("affairs","prediction").show
 
println("---Confusion Matrix------")
results.stat.crosstab("affairs","prediction").show()
 
// What was the overall accuracy of the model, using AUC
val auc = evaluator.evaluate(results)
println("----AUC--------")
println("auc="+auc)

以上这篇利用scikitlearn画ROC曲线实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python在多玩图片上下载妹子图的实现代码
Aug 13 Python
Python实现股市信息下载的方法
Jun 15 Python
python+requests+unittest API接口测试实例(详解)
Jun 10 Python
Python3.4编程实现简单抓取爬虫功能示例
Sep 14 Python
使用pandas中的DataFrame数据绘制柱状图的方法
Apr 10 Python
pytorch训练imagenet分类的方法
Jul 27 Python
Selenium+Python 自动化操控登录界面实例(有简单验证码图片校验)
Jun 28 Python
Python 使用 docopt 解析json参数文件过程讲解
Aug 13 Python
Python定时发送天气预报邮件代码实例
Sep 09 Python
Django实现WebSSH操作物理机或虚拟机的方法
Nov 06 Python
python装饰器实现对异常代码出现进行自动监控的实现方法
Sep 15 Python
python 对xml解析的示例
Feb 27 Python
Python使用文件操作实现一个XX信息管理系统的示例
Jul 02 #Python
keras用auc做metrics以及早停实例
Jul 02 #Python
keras 简单 lstm实例(基于one-hot编码)
Jul 02 #Python
Python装饰器结合递归原理解析
Jul 02 #Python
Python OpenCV读取中文路径图像的方法
Jul 02 #Python
keras.utils.to_categorical和one hot格式解析
Jul 02 #Python
python 使用多线程创建一个Buffer缓存器的实现思路
Jul 02 #Python
You might like
windows下PHP APACHE MYSQ完整配置
2007/01/02 PHP
mysql数据库差异比较的PHP代码
2012/02/05 PHP
回帖脱衣服的图片实现代码
2014/02/15 PHP
PHP多线程类及用法实例
2014/12/03 PHP
Laravel中基于Artisan View扩展包创建及删除应用视图文件的方法
2016/10/08 PHP
PHP编写daemon process 实例详解
2016/11/13 PHP
由php中字符offset特征造成的绕过漏洞详解
2017/07/07 PHP
JS的数组的扩展实例代码
2008/07/09 Javascript
javascript中的绑定与解绑函数应用示例
2013/06/24 Javascript
js获取浏览器基本信息大全
2014/11/27 Javascript
javascript操作表格排序实例分析
2015/05/06 Javascript
jquery实现简单实用的打分程序实例
2015/07/23 Javascript
javascript判断复选框是否选中的方法
2015/10/16 Javascript
浅析$.getJSON异步请求和同步请求
2016/06/06 Javascript
Node.js中文件操作模块File System的详细介绍
2017/01/05 Javascript
js实现导航吸顶效果
2017/02/24 Javascript
AngularJS 将再发布一个重要版本 然后进入长期支持阶段
2018/01/31 Javascript
JavaScript 判断iPhone X Series机型的方法
2019/01/28 Javascript
Vue打包后访问静态资源路径问题
2019/11/08 Javascript
JS实现简易日历效果
2021/01/25 Javascript
Python使用稀疏矩阵节省内存实例
2014/06/27 Python
利用python下载scihub成文献为PDF操作
2020/07/09 Python
python中的split、rsplit、splitlines用法说明
2020/10/23 Python
python list的index()和find()的实现
2020/11/16 Python
澳大利亚女士时装在线:Rockmans
2018/09/26 全球购物
美国手机支架公司:PopSockets
2019/11/27 全球购物
宝宝周岁宴答谢词
2014/01/26 职场文书
大学生应聘导游自荐信
2014/06/02 职场文书
承诺书范文
2014/06/03 职场文书
司法局火灾防控方案
2014/06/05 职场文书
大型公益活动策划方案
2014/08/20 职场文书
行政复议决定书
2015/06/24 职场文书
《田忌赛马》教学反思
2016/02/19 职场文书
css中z-index: 0和z-index: auto的区别
2021/08/23 HTML / CSS
Python实现双向链表基本操作
2022/05/25 Python
Windows10安装Apache2.4的方法步骤
2022/06/25 Servers