模型验证_python机器学习-sklearn挖掘乳腺癌细胞(五)

 python机器学习-sklearn挖掘乳腺癌细胞( 博主亲自录制)

网易云观看地址

https://study.163.com/course/introduction.htm?courseId=1005269003&utm_campaign=commission&utm_source=cp-400000000398149&utm_medium=share

 模型验证

分类器好坏验证,模型建立好后,不是万事大吉,需要进行crossvalidation, AUC,GINi,KS,GainTable检验

KS可以检测模型区分好坏客户能力,如果有一个分数段区分能力强,KS会大于0.2

AUC检测模型分类器效果,分类器敏感度越高,AUC越大,一般AUC大于0.7,分类器准确性就不错。

Gain Table可以检测模型收益情况和排序能力

 模型验证中数据要拆分为train(训练),test(测试),oot(跨时间)

train和test是同一个时间段,一般三七开,train占百分之70,test占百分之30

oot的时间段在train,test后面,用于测试未来数据

下图是模型验证的可视化:

包括ROC,提升图,KS,PSI四个指标

由于时间关系,我们只详细说明一下ROC/AUC检验

auc分数有两种计算方式,第一种是根据目标变量y_true,预测分数/预测概率y_socres,通过roc_auc_score(y_true, y_scores)计算AUC

第二种方法是通过fpr,tpr,通过auc(fpr,tpr)来计算AUC

excel 绘图ROC

ROC的前置条件是分数越高,阳性率越高,但风控模型中,有的分数越低,坏客户概率越高,例如蜜罐分数,因此ROC绘制出来是反的,需要对阳性标签反转pos_label=0 

由于分数越低,坏客户概率越高,画出来的ROC曲线是反转的,需要纠正

AUC/ROC检验代码

# -*- coding: utf-8 -*-
"""
Created on Thu Apr 12 22:31:31 2018
 
@author: 231469242@qq.com
"""
import numpy as np
from sklearn import metrics
from sklearn.metrics import roc_curve, auc,roc_auc_score  ###计算roc和auc
 
import pandas as pd
from sklearn.datasets import load_breast_cancer
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import mglearn
import matplotlib.pyplot as plt
 
cancer=load_breast_cancer()
 
#mglearn.plots.plot_knn_classification(n_neighbors=3)
X_train,x_test,y_train,y_test=train_test_split(cancer.data,cancer.target,stratify=cancer.target,random_state=42)
 
knn=KNeighborsClassifier()
knn.fit(X_train,y_train)
print("accuracy on the training subset:{:.3f}".format(knn.score(X_train,y_train)))
print("accuracy on the test subset:{:.3f}".format(knn.score(x_test,y_test)))
 
#Auc验证,数据采用测试集数据
#癌症的概率
proba_cancer=knn.predict_proba(x_test)
y_scores=pd.DataFrame(proba_cancer)[1]
y_scores=np.array(y_scores)
y_true=y_test
#auc分数
#auc分数有两种计算方式,第一种是根据目标变量y_true,预测分数/预测概率y_socres,通过roc_auc_score(y_true, y_scores)计算AUC
AUC=roc_auc_score(y_true, y_scores)
print("AUC:",AUC)
#auc第二种方法是通过fpr,tpr,通过auc(fpr,tpr)来计算AUC
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_scores, pos_label=1)
AUC1 = auc(fpr,tpr) ###计算auc的值 
 
#print("fpr:",fpr)
#print("tpr:",tpr)
#print("thresholds:",thresholds)
print("AUC1:",AUC1)
 
if AUC >=0.7:
    print("good classifier")
if 0.7>AUC>0.6:
    print("not very good classifier")
if 0.6>=AUC>0.5:
    print("useless classifier")
if 0.5>=AUC:
    print("bad classifier,with sorting problems")
     
 
#绘制ROC曲线
#画对角线 
plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Diagonal line') 
plt.plot(fpr,tpr,label='ROC curve (area = %0.2f)' % AUC) 
plt.title('ROC curve')  
plt.legend(loc="lower right")   

  

python信用评分卡建模(附代码,博主录制,包含模型验证内容)

原文地址:https://www.cnblogs.com/webRobot/p/9743585.html