python 分类问题 画roc曲线实战

目录

roc曲线详解:

首先看一下需要的数据:

完整的代码:


roc曲线详解:

受试者工作特征曲线 (receiver operating characteristic curve,简称ROC曲线),又称为感受性曲线(sensitivity curve)。得此名的原因在于曲线上各点反映着相同的感受性,它们都是对同一信号刺激的反应,只不过是在几种不同的判定标准下所得的结果而已。为了了解ROC曲线的意义,我们首先得了解一些变量。以下定义引自维基百科
最近在做一些分类的任务,评价中的ROC曲线在很多地方都会用得到,特别在论文中。在此记录一下在做ROC曲线的过程中遇到的一些坑。
 

首先看一下需要的数据:

第一列是真实值 第二列是分数 第三列是预测值
0 0.9777694940567017 0
0 0.4195287823677063 1
0 0.6916269063949585 0
1 0.6496472954750061 1
1 0.13310739398002625 0
1 0.5438785552978516 0
0 0.9020959734916687 0
0 0.9027289748191833 0
0 0.9631645083427429 0
1 0.5531736612319946 1
1 0.5298251509666443 1
0 0.8946734070777893 0
0 1.011642336845398 0
0 0.22767378389835358 1
1 0.6624225974082947 1
1 0.6401157975196838 1
1 0.23411975800991058 1
0 0.6916269063949585 0
1 0.892021119594574 0
0 0.5835625529289246 0

完整的代码:

import numpy as np
import matplotlib.pyplot as plt
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
# y1=[0,1,0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0]

with open("batch_16_epoch_2.txt","r",encoding="utf-8") as f:

        y_true, y_sore,y_pre=[],[],[]
        f=f.readlines()
        data=[i.split("\n")[0].split(" ") for i in f ]
        print("# 第一列是真实值 第二列是分数 第三列是预测值",data)
        for line in data:
            y_true.append(int(line[0]))
            y_sore.append(float(line[1]))
            y_pre.append(int(line[2]))
from sklearn.metrics import roc_curve, auc
fpr, tpr, thresholds = roc_curve(y_true,y_pre)
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)

猜你喜欢

转载自blog.csdn.net/qq_38735017/article/details/126178246