如何使用scikit-learn绘制多类别情况下的ROC曲线?

我想为我自己的数据集绘制多类别情况下的ROC曲线。根据文档,我了解到标签必须是二元的(我有从1到5的5个标签),所以我按照文档中提供的示例进行了操作:

print(__doc__)import numpy as npimport matplotlib.pyplot as pltfrom sklearn import svm, datasetsfrom sklearn.metrics import roc_curve, aucfrom sklearn.cross_validation import train_test_splitfrom sklearn.preprocessing import label_binarizefrom sklearn.svm import SVCfrom sklearn.multiclass import OneVsRestClassifierfrom sklearn.feature_extraction.text import TfidfVectorizerimport numpy as nptfidf_vect= TfidfVectorizer(use_idf=True, smooth_idf=True, sublinear_tf=False, ngram_range=(2,2))from sklearn.cross_validation import train_test_split, cross_val_scoreimport pandas as pddf = pd.read_csv('path/file.csv',                     header=0, sep=',', names=['id', 'content', 'label'])X = tfidf_vect.fit_transform(df['content'].values)y = df['label'].values# Binarize the outputy = label_binarize(y, classes=[1,2,3,4,5])n_classes = y.shape[1]# Add noisy features to make the problem harderrandom_state = np.random.RandomState(0)n_samples, n_features = X.shapeX = np.c_[X, random_state.randn(n_samples, 200 * n_features)]# shuffle and split training and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33                                                    ,random_state=0)# Learn to predict each class against the otherclassifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True,                                 random_state=random_state))y_score = classifier.fit(X_train, y_train).decision_function(X_test)# Compute ROC curve and ROC area for each classfpr = 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])# Compute micro-average ROC curve and ROC areafpr["micro"], tpr["micro"], _ = roc_curve(y_test.ravel(), y_score.ravel())roc_auc["micro"] = auc(fpr["micro"], tpr["micro"])# Plot of a ROC curve for a specific classplt.figure()plt.plot(fpr[2], tpr[2], label='ROC curve (area = %0.2f)' % roc_auc[2])plt.plot([0, 1], [0, 1], 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Receiver operating characteristic example')plt.legend(loc="lower right")plt.show()# Plot ROC curveplt.figure()plt.plot(fpr["micro"], tpr["micro"],         label='micro-average ROC curve (area = {0:0.2f})'               ''.format(roc_auc["micro"]))for i in range(n_classes):    plt.plot(fpr[i], tpr[i], label='ROC curve of class {0} (area = {1:0.2f})'                                   ''.format(i, roc_auc[i]))plt.plot([0, 1], [0, 1], 'k--')plt.xlim([0.0, 1.0])plt.ylim([0.0, 1.05])plt.xlabel('False Positive Rate')plt.ylabel('True Positive Rate')plt.title('Some extension of Receiver operating characteristic to multi-class')plt.legend(loc="lower right")plt.show()

问题在于这种方法永远不会结束。您对如何为这个数据集绘制ROC曲线有何建议?


回答:

这个版本永远不会结束是因为这行代码:

classifier = OneVsRestClassifier(svm.SVC(kernel='linear', probability=True, random_state=random_state))

svm分类器需要很长时间才能完成,可以尝试使用其他分类器,如AdaBoost或您选择的其他分类器:

classifier = OneVsRestClassifier(AdaBoostClassifier())

记得添加导入语句:

from sklearn.ensemble import AdaBoostClassifier

删除以下代码,这些代码是无用的:

# Add noisy features to make the problem harderrandom_state = np.random.RandomState(0)n_samples, n_features = X.shapeX = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

改为添加以下代码:

random_state = 0

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注