
正文
roc值函数python python ros
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
python 怎么画与其他方法进行比较的ROC曲线?
使用sklearn的一系列方法后可以很方便的绘制处ROC曲线,这里简单实现以下。
主要是利用混淆矩阵中的知识作为绘制的数据(如果不是很懂可以先看看这里的基础):
tpr(Ture Positive Rate):真阳率 图像的纵坐标
fpr(False Positive Rate):阳率(伪阳率) 图像的横坐标
mean_tpr:累计真阳率求平均值
mean_fpr:累计阳率求平均值
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.model_selection import StratifiedKFold
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
# 增加噪声特征
random_state = np.random.RandomState(0)
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]
cv = StratifiedKFold(n_splits=6) #导入该模型,后面将数据划分6份
classifier = svm.SVC(kernel='linear', probability=True,random_state=random_state) # SVC模型 可以换作AdaBoost模型试试
# 画平均ROC曲线的两个参数
mean_tpr = 0.0 # 用来记录画平均ROC曲线的信息
mean_fpr = np.linspace(0, 1, 100)
cnt = 0
for i, (train, test) in enumerate(cv.split(X,y)): #利用模型划分数据集和目标变量 为一一对应的下标
cnt +=1
probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test]) # 训练模型后预测每条样本得到两种结果的概率
fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1]) # 该函数得到伪正例、真正例、阈值,这里只使用前两个
mean_tpr += np.interp(mean_fpr, fpr, tpr) # 插值函数 interp(x坐标,每次x增加距离,y坐标) 累计每次循环的总值后面求平均值
mean_tpr[0] = 0.0 # 将第一个真正例=0 以0为起点
roc_auc = auc(fpr, tpr) # 求auc面积
plt.plot(fpr, tpr, lw=1, label='ROC fold {0:.2f} (area = {1:.2f})'.format(i, roc_auc)) # 画出当前分割数据的ROC曲线
plt.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck') # 画对角线
mean_tpr /= cnt # 求数组的平均值
mean_tpr[-1] = 1.0 # 坐标最后一个点为(1,1) 以1为终点
mean_auc = auc(mean_fpr, mean_tpr)
plt.plot(mean_fpr, mean_tpr, 'k--',label='Mean ROC (area = {0:.2f})'.format(mean_auc), lw=2)
plt.xlim([-0.05, 1.05]) # 设置x、y轴的上下限,设置宽一点,以免和边缘重合,可以更好的观察图像的整体
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()
相关问答
Q1: python如何掉包实现ROC
1、sklearn里有现成的函数计算ROC曲线坐标点。
2、把随机生成的置信度只保留小数点后一位,那么数据里有很多相同置信度的值,就可以实现ROC。
Q2: 求python写的随机森林的roc代码
随机森林在R packages和Python scikit-learn中的实现是当下非常流行的,下列是在R和Python中载入随机森林模型的具体代码:
Python
#Import Library
fromsklearn.ensemble import RandomForestClassifier #use RandomForestRegressor for regression problem
#Assumed you have, X (predictor) and Y (target) for training data set and x_test(predictor) of test_dataset
# Create Random Forest object
model= RandomForestClassifier(n_estimators=1000)
# Train the model using the training sets and check score
model.fit(X, y)
#Predict Output
predicted= model.predict(x_test)
R Code
library(randomForest)
x- cbind(x_train,y_train)
# Fitting model
fit- randomForest(Species ~ ., x,ntree=500)
summary(fit)
#Predict Output
predicted= predict(fit,x_test)
Q3: python评分卡之LR及混淆矩阵、ROC
import pandas as pd
import numpy as np
from sklearn import linear_model
# 读取数据
sports = pd.read_csv(r'C:\Users\Administrator\Desktop\Run or Walk.csv')
# 提取出所有自变量名称
predictors = sports.columns[4:]
# 构建自变量矩阵
X = sports.ix[:,predictors]
# 提取y变量值
y = sports.activity
# 将数据集拆分为训练集和测试集
X_train, X_test, y_train, y_test = model_selection.train_test_split(X, y, test_size = 0.25, random_state = 1234)
# 利用训练集建模
sklearn_logistic = linear_model.LogisticRegression()
sklearn_logistic.fit(X_train, y_train)
# 返回模型的各个参数
print(sklearn_logistic.intercept_, sklearn_logistic.coef_)
# 模型预测
sklearn_predict = sklearn_logistic.predict(X_test)
# 预测结果统计
pd.Series(sklearn_predict).value_counts()
-------------------------------------------------------------------------------------------------------------------------------------------
# 导入第三方模块
from sklearn import metrics
# 混淆矩阵
cm = metrics.confusion_matrix(y_test, sklearn_predict, labels = [0,1])
cm
Accuracy = metrics.scorer.accuracy_score(y_test, sklearn_predict)
Sensitivity = metrics.scorer.recall_score(y_test, sklearn_predict)
Specificity = metrics.scorer.recall_score(y_test, sklearn_predict, pos_label=0)
print('模型准确率为%.2f%%:' %(Accuracy*100))
print('正例覆盖率为%.2f%%' %(Sensitivity*100))
print('负例覆盖率为%.2f%%' %(Specificity*100))
-------------------------------------------------------------------------------------------------------------------------------------------
# 混淆矩阵的可视化
# 导入第三方模块
import seaborn as sns
import matplotlib.pyplot as plt
# 绘制热力图
sns.heatmap(cm, annot = True, fmt = '.2e',cmap = 'GnBu')
plt.show()
------------------------------------------------------------------------------------------------------------------------------------------
# 绘制ROC曲线
# 计算真正率和假正率
fpr,tpr,threshold = metrics.roc_curve(y_test, sm_y_probability)
# 计算auc的值
roc_auc = metrics.auc(fpr,tpr)
# 绘制面积图
plt.stackplot(fpr, tpr, color='steelblue', alpha = 0.5, edgecolor = 'black')
# 添加边际线
plt.plot(fpr, tpr, color='black', lw = 1)
# 添加对角线
plt.plot([0,1],[0,1], color = 'red', linestyle = '--')
# 添加文本信息
plt.text(0.5,0.3,'ROC curve (area = %0.2f)' % roc_auc)
# 添加x轴与y轴标签
plt.xlabel('1-Specificity')
plt.ylabel('Sensitivity')
plt.show()
-------------------------------------------------------------------------------------------------------------------------------------------
#ks曲线 链接: 风控数据分析学习笔记(二)Python建立信用评分卡 -
fig, ax = plt.subplots()
ax.plot(1 - threshold, tpr, label='tpr')# ks曲线要按照预测概率降序排列,所以需要1-threshold镜像
ax.plot(1 - threshold, fpr, label='fpr')
ax.plot(1 - threshold, tpr-fpr,label='KS')
plt.xlabel('score')
plt.title('KS Curve')
plt.ylim([0.0, 1.0])
plt.figure(figsize=(20,20))
legend = ax.legend(loc='upper left')
plt.show()
Q4: 理解ROC和AUC
放在具体领域来理解上述两个指标。如在医学诊断中,判断有病的样本。那么尽量把有病的揪出来是主要任务,也就是第一个指标TPR,要越高越好。而把没病的样本误诊为有病的,也就是第二个指标FPR,要越低越好。不难发现,这两个指标之间是相互制约的。如果某个医生对于有病的症状比较敏感,稍微的小症状都判断为有病,那么他的第一个指标应该会很高,但是第二个指标也就相应地变高。最极端的情况下,他把所有的样本都看做有病,那么第一个指标达到1,第二个指标也为1。
在上述癌症检测中(正反例极度不平衡的情况下),
有时我们还会见到sensitivity和specificity两个概念:
也就是说想要sensitivity高一点相当于要True Positive Rate高一点,要specificity高一点相当于False Positive Rate低一点/。为了权衡recall和precision,对于评判二分类器的优劣,可以使用ROC(Receiver Operating Characteristic)曲线以及AUC(Area Under roc Curve)指标。
ROC曲线的几个概念:
以医生诊断为例,我们可以看出:
上图中一个阈值,得到一个点。现在我们需要一个独立于阈值的评价指标来衡量这个医生的医术如何,也就是 遍历所有的阈值 ,得到ROC曲线。还是一开始的那幅图,假设如下就是某个医生的诊断统计图,直线代表阈值。我们遍历所有的阈值,能够在ROC平面上得到如下的ROC曲线。
以一个简单的模拟数据来计算下ROC曲线每个点的值
Python可以用sklearn,R可以用ROCR包或者pROC包,这里以ROCR包来检验下上述计算结果:
x.values对应FPR,y.values对应TPR, alpha.values对应预测打分cutoff,结果跟上面完全一致,然后简单做个ROC图。
AUC值就相当于ROC曲线的所覆盖的面积,可以从ROC曲线看出AUC值越大,其分类效果越好。
理解ROC和AUC
ROC曲线与AUC值
Q5: Python数据分析(4)决策树模型
时间:2021/06/30
系统环境:Windows 10
所用工具:Jupyter Notebook\Python 3.0
涉及的库:pandas\train_test_split\DecisionTreeClassifier\accuracy_score\roc_curve\matplotlib.pyplot\roc_auc_score\export_graphviz\graphviz\os\GridSearchCV
蛋肥想法: 通过测试集数据,检验预测准确度,测得准确度为95.47%。
蛋肥想法: 通过绘制ROC曲线,得出AUC值为0.966,表明预测效果不错。
蛋肥想法: 特征重要性最高的是“satisfaction_level”,而“salary”在该模型中的特征重要性为0,并不符合实际(钱可太重要了~),应该是因为数据处理时单纯将工资分为“高”“中”“低”3个档次,使得该特征变量在决策树模型中发挥的作用较小。
蛋肥想法: GridSearch网格搜索可以进行单参数和多参数调优,蛋肥这里以max_depth参数来练习调优,得出'max_depth': 7时,AUC更好为0.985。
roc值函数python的介绍就聊到这里吧,感谢你花时间阅读本站内容,更多关于python ros、roc值函数python的信息别忘了在本站进行查找喔。







