我正在尝试使用scikit-learn
模块来计算AUC并绘制三个不同分类器输出的ROC曲线,以比较它们的性能。我对这个主题非常陌生,正在努力理解如何将我拥有的数据输入到roc_curve
和auc
函数中。
对于测试集中的每个项目,我都有真实值和三个分类器的输出。类别是['N', 'L', 'W', 'T']
。此外,我还有每个分类器输出的值的置信度得分。我如何将这些信息传递给roc_curve
函数?
我是否需要使用label_binarize
来处理我的输入数据?我如何将分类器输出的[class, confidence]
对列表转换为roc_curve
期望的y_score
?
感谢任何帮助!关于ROC曲线的好资源也将非常有帮助。
回答:
你需要使用label_binarize
函数,然后你就可以绘制多类ROC曲线了。
使用Iris数据的示例:
import matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import label_binarizefrom sklearn.metrics import roc_curve, aucfrom sklearn.multiclass import OneVsRestClassifierfrom itertools import cycleplt.style.use('ggplot')iris = datasets.load_iris()X = iris.datay = iris.target# Binarize the outputy = label_binarize(y, classes=[0, 1, 2])n_classes = y.shape[1]X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.5, random_state=0)classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=0))y_score = classifier.fit(X_train, y_train).decision_function(X_test)fpr = dict()tpr = dict()roc_auc = dict()for i in range(n_classes): fpr[i], tpr[i], _ = roc_curve(y_test[:, i], y_score[:, i]) roc_auc[i] = auc(fpr[i], tpr[i])colors = cycle(['blue', 'red', 'green'])for i, color in zip(range(n_classes), colors): plt.plot(fpr[i], tpr[i], color=color, lw=1.5, label='ROC curve of class {0} (area = {1:0.2f})' ''.format(i, roc_auc[i]))plt.plot([0, 1], [0, 1], 'k--', lw=1.5)plt.xlim([-0.05, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic for multi-class data')plt.legend(loc="lower right")plt.show()