解析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)
對(duì)于兩個(gè)以上類的分類問題,
這里就有ROC的宏觀平均(macro-average)和微觀平均(micro-average)的做法了(具體查閱機(jī)器學(xué)習(xí))
在這之前,我想肯定會(huì)有人想把每個(gè)類別的ROC的都繪制出來,實(shí)現(xiàn)起來,無非就是獲得每個(gè)單類的標(biāo)簽值和模型預(yù)測值數(shù)據(jù)
不過你怎么解釋呢?有什么意義呢?其實(shí)這個(gè)問題我也想了很久,查閱了很多文獻(xiàn),也沒有個(gè)所以然。
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曲線,大概率會(huì)出現(xiàn)報(bào)錯(cuò):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)簽值維度匹配,如果十個(gè)類就對(duì)應(yīng)十個(gè)值,↓行代表數(shù)據(jù)序號(hào),列代表每個(gè)類別的預(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()
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
瘋狂上漲的Python 開發(fā)者應(yīng)從2.x還是3.x著手?
熱度瘋漲的 Python,開發(fā)者應(yīng)從 2.x 還是 3.x 著手?這篇文章就為大家分析一下了Python開發(fā)者應(yīng)從2.x還是3.x學(xué)起,感興趣的小伙伴們可以參考一下2017-11-11
Python os.listdir與os.walk實(shí)現(xiàn)獲取路徑詳解
這篇文章主要介紹了Python使用os.listdir和os.walk獲取文件路徑,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-10-10
解決pytorch下出現(xiàn)multi-target not supported at的一種可能原因
這篇文章主要介紹了解決pytorch下出現(xiàn)multi-target not supported at的一種可能原因,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-02-02
詳解python列表(list)的使用技巧及高級(jí)操作
這篇文章主要介紹了詳解python列表(list)的使用技巧及高級(jí)操作,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-08-08
python實(shí)現(xiàn)中文轉(zhuǎn)換url編碼的方法
這篇文章主要介紹了python實(shí)現(xiàn)中文轉(zhuǎn)換url編碼的方法,結(jié)合實(shí)例形式分析了Python針對(duì)中文的gbk與utf-8編碼轉(zhuǎn)換的相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2016-06-06
python實(shí)現(xiàn)遠(yuǎn)程控制電腦
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)遠(yuǎn)程控制電腦,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-05-05
pygame實(shí)現(xiàn)飛機(jī)大戰(zhàn)
這篇文章主要為大家詳細(xì)介紹了pygame實(shí)現(xiàn)飛機(jī)大戰(zhàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-03-03
python+opencv圖像分割實(shí)現(xiàn)分割不規(guī)則ROI區(qū)域方法匯總
這篇文章主要介紹了python+opencv圖像分割實(shí)現(xiàn)分割不規(guī)則ROI區(qū)域方法匯總,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04

