解析ROC曲線繪制(python+sklearn+多分類)
ROC曲線繪制要點(diǎn)(僅記錄)
1、ROC用于度量模型性能
2、用于二分類問題,如若遇到多分類也以二分類的思想進(jìn)行操作。
3、二分類問題代碼實(shí)現(xiàn)(至于實(shí)現(xiàn),文檔說的很清楚了:官方文檔)
原理看懂就好,實(shí)現(xiàn)直接調(diào)用API即可
提取數(shù)據(jù)(標(biāo)簽值和模型預(yù)測值)
from sklearn.metrics import roc_curve, auc fpr, tpr, thresholds = roc_curve(y_true,y_sore) roc_auc = auc(fpr, tpr) plt.title('Receiver Operating Characteristic') plt.plot(fpr, tpr, '#9400D3',label=u'AUC = %0.3f'% roc_auc) plt.legend(loc='lower right') plt.plot([0,1],[0,1],'r--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.grid(linestyle='-.') plt.grid(True) plt.show() print(roc_auc)
4、多分類問題代碼實(shí)現(xiàn)
對于兩個以上類的分類問題,
這里就有ROC的宏觀平均(macro-average)和微觀平均(micro-average)的做法了(具體查閱機(jī)器學(xué)習(xí))
在這之前,我想肯定會有人想把每個類別的ROC的都繪制出來,實(shí)現(xiàn)起來,無非就是獲得每個單類的標(biāo)簽值和模型預(yù)測值數(shù)據(jù)
不過你怎么解釋呢?有什么意義呢?其實(shí)這個問題我也想了很久,查閱了很多文獻(xiàn),也沒有個所以然。
PS:(如果有人知道,麻煩告知下~)
多分類的ROC曲線畫出來并不難
具體如下
import numpy as np import matplotlib.pyplot as plt from scipy import interp from sklearn.preprocessing import label_binarize from sklearn.metrics import confusion_matrix,classification_report from sklearn.metrics import roc_curve, auc from sklearn.metrics import cohen_kappa_score, accuracy_score
fpr0, tpr0, thresholds0 = roc_curve(y_true0,y_sore0) fpr1, tpr1, thresholds1 = roc_curve(y_true1,y_sore1) fpr2, tpr2, thresholds2 = roc_curve(y_true2,y_sore2) fpr3, tpr3, thresholds3 = roc_curve(y_true3,y_sore3) fpr4, tpr4, thresholds4 = roc_curve(y_true4,y_sore4) roc_auc0 = auc(fpr0, tpr0) roc_auc1 = auc(fpr1, tpr1) roc_auc2 = auc(fpr2, tpr2) roc_auc3 = auc(fpr3, tpr3) roc_auc4 = auc(fpr4, tpr4) plt.title('Receiver Operating Characteristic') plt.rcParams['figure.figsize'] = (10.0, 10.0) plt.rcParams['image.interpolation'] = 'nearest' plt.rcParams['image.cmap'] = 'gray' plt.rcParams['font.sans-serif']=['SimHei'] plt.rcParams['axes.unicode_minus']=False # 設(shè)置標(biāo)題大小 plt.rcParams['font.size'] = '16' plt.plot(fpr0, tpr0, 'k-',color='k',linestyle='-.',linewidth=3,markerfacecolor='none',label=u'AA_AUC = %0.5f'% roc_auc0) plt.plot(fpr1, tpr1, 'k-',color='grey',linestyle='-.',linewidth=3,label=u'A_AUC = %0.5f'% roc_auc1) plt.plot(fpr2, tpr2, 'k-',color='r',linestyle='-.',linewidth=3,markerfacecolor='none',label=u'B_AUC = %0.5f'% roc_auc2) plt.plot(fpr3, tpr3, 'k-',color='red',linestyle='-.',linewidth=3,markerfacecolor='none',label=u'C_AUC = %0.5f'% roc_auc3) plt.plot(fpr4, tpr4, 'k-',color='y',linestyle='-.',linewidth=3,markerfacecolor='none',label=u'D_AUC = %0.5f'% roc_auc4) plt.legend(loc='lower right') plt.plot([0,1],[0,1],'r--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.grid(linestyle='-.') plt.grid(True) plt.show()
在上面的基礎(chǔ)上,我們將標(biāo)簽二值化
(如果你不使用二分類思想去畫ROC曲線,大概率會出現(xiàn)報(bào)錯:ValueError: multilabel-indicator format is not supported)
y_test_all = label_binarize(true_labels_i, classes=[0,1,2,3,4]) y_score_all=test_Y_i_hat fpr = dict() tpr = dict() roc_auc = dict() for i in range(len(classes)): fpr[i], tpr[i], thresholds = roc_curve(y_test_all[:, i],y_score_all[:, i]) roc_auc[i] = auc(fpr[i], tpr[i])
注意看,宏觀平均(macro-average)和微觀平均(micro-average)的處理方式
(y_test_all(真實(shí)標(biāo)簽值)和y_score_all(與真實(shí)標(biāo)簽值維度匹配,如果十個類就對應(yīng)十個值,↓行代表數(shù)據(jù)序號,列代表每個類別的預(yù)測值)
# micro-average ROC curve(方法一) fpr["micro"], tpr["micro"], thresholds = roc_curve(y_test_all.ravel(),y_score_all.ravel()) roc_auc["micro"] = auc(fpr["micro"], tpr["micro"]) # macro-average ROC curve 方法二) all_fpr = np.unique(np.concatenate([fpr[i] for i in range(len(classes))])) mean_tpr = np.zeros_like(all_fpr) for i in range(len(classes)): mean_tpr += interp(all_fpr, fpr[i], tpr[i]) # 求平均計(jì)算ROC包圍的面積AUC mean_tpr /= len(classes) fpr["macro"] = all_fpr tpr["macro"] = mean_tpr roc_auc["macro"] = auc(fpr["macro"], tpr["macro"]) #畫圖部分 plt.figure() plt.plot(fpr["micro"], tpr["micro"],'k-',color='y', label='XXXX ROC curve micro-average(AUC = {0:0.4f})' ''.format(roc_auc["micro"]), linestyle='-.', linewidth=3) plt.plot(fpr["macro"], tpr["macro"],'k-',color='k', label='XXXX ROC curve macro-average(AUC = {0:0.4f})' ''.format(roc_auc["macro"]), linestyle='-.', linewidth=3) plt.plot([0,1],[0,1],'r--') plt.xlim([-0.1,1.1]) plt.ylim([-0.1,1.1]) plt.ylabel('True Positive Rate') plt.xlabel('False Positive Rate') plt.legend(loc="lower right") plt.grid(linestyle='-.') plt.grid(True) plt.show()
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
淺談Python_Openpyxl使用(最全總結(jié))
這篇文章主要介紹了淺談Python_Openpyxl使用(最全總結(jié)),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09利用Python的Twisted框架實(shí)現(xiàn)webshell密碼掃描器的教程
這篇文章主要介紹了利用Python的Twisted框架實(shí)現(xiàn)webshell密碼掃描器的教程,用到了Twisted框架的異步通信機(jī)制,需要的朋友可以參考下2015-04-04python使用urlparse分析網(wǎng)址中域名的方法
這篇文章主要介紹了python使用urlparse分析網(wǎng)址中域名的方法,涉及Python使用urlparse模塊操作URL的技巧,需要的朋友可以參考下2015-04-04pyqt彈出新對話框,以及關(guān)閉對話框獲取數(shù)據(jù)的實(shí)例
今天小編就為大家分享一篇pyqt彈出新對話框,以及關(guān)閉對話框獲取數(shù)據(jù)的實(shí)例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06Pytorch實(shí)現(xiàn)tensor序列化和并行化的示例詳解
這篇文章主要介紹了Pytorch實(shí)現(xiàn)tensor序列化和并行化,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,感興趣的同學(xué)們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-12-12