#### ROC、AUC python实现方法 ####
from sklearn.metrics import roc_curve, auc
import pandas as pd
import matplotlib.pyplot as plt
# 读取数据
# data = pd.read_excel('.xlsx') # 一般需要读取两列数据,其中包括好坏标记,打分
data = pd.DataFrame({'Flag_bad':[0,0,0,0,0,1,1,1,1,1],
'Score':[890,990,985,922,881,521,600,560,611,742]})
# 将打分转化为概率
data['P'] = 1-(data['Score']-500)/500 # 500分为最低分
# 计算真正率和假正率
#真正率即判定为正样本且实际为正样本的样本数/所有的正样本数,
#假正率为判定为正样本实际为负样本的样本数/所有的负样本数。
fpr,tpr,_ = roc_curve(data['Flag_bad'],data['P'])
# 画图
plt.figure()
plt.plot(fpr, tpr, color = 'darkorange', lw = 2, label = 'ROC')
#d 对比线 y=x
plt.plot([0, 1], [0, 1], color = 'navy', lw = 2, linestyle = '--', label = 'Random')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.legend(loc = 'lower right')
plt.title('Receiver operating charateristic')
# 输出保存
plt.savefig('test.png')
plt.show()
# 计算AUC
print(auc(fpr,tpr))
网友评论