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

9

我想为我的数据集绘制多类情况下的ROC曲线。根据文档的说明,标签必须是二进制的(我有从1到5的5个标签),因此我遵循了文档中提供的示例:

print(__doc__)

import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import label_binarize
from sklearn.svm import SVC
from sklearn.multiclass import OneVsRestClassifier



from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
tfidf_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_score

import pandas as pd

df = 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 output
y = label_binarize(y, classes=[1,2,3,4,5])
n_classes = y.shape[1]

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

# shuffle and split training and test sets
X_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 other
classifier = 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 class
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])

# Compute micro-average ROC curve and ROC area
fpr["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 class
plt.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 curve
plt.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曲线呢?

4
我认为你有一个概念上的错误。ROC只适用于两个类别,其他情况下都是未定义的。 - carlosdc
感谢@carlosdc的反馈。当然,这仅适用于二元分类情况。所以无法绘制吗? - john doe
1
你可以为每一对类别做一个成对的ROC曲线。 - Scott
2
这可能会有所帮助:http://stats.stackexchange.com/questions/2151/how-to-plot-roc-curves-in-multiclass-classification - Scott
您的数据集链接似乎已经失效。 - Archie
有人知道如何在多类和交叉验证情况下绘制这个吗? - Bambi
1个回答

4

这个版本永远不会完成,因为这行代码:

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 harder
random_state = np.random.RandomState(0)
n_samples, n_features = X.shape
X = np.c_[X, random_state.randn(n_samples, 200 * n_features)]

只需添加以下内容:

random_state = 0

谢谢您的帮助,为什么使用SVMs会花费这么多时间? - john doe
4
是因为你将概率设置为True。在这种情况下,支持向量机还必须计算概率,这需要占用大量的内存和计算资源。 - Salamander
@Eranyogev,您如何使用交叉验证绘制多类别图形? - Bambi

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接