Python 如何使用scikit learn绘制多类病例的ROC曲线?

Python 如何使用scikit learn绘制多类病例的ROC曲线?,python,python-2.7,matplotlib,machine-learning,scikit-learn,Python,Python 2.7,Matplotlib,Machine Learning,Scikit Learn,我想为我自己的数据集绘制多类情况的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

我想为我自己的数据集绘制多类情况的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曲线吗?

这个版本永远不会结束,因为这条线:

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

我认为你有一个概念上的缺陷。除了两个类之外,ROC还没有定义。谢谢@carlosdc的反馈。当然,这只适用于二进制分类的情况。所以这是不可能绘制的?你可以为每一对类绘制一条成对的ROC曲线。这可能会有帮助,因为到你的数据集的链接似乎断了。谢谢你的帮助,为什么SVM需要这么多?因为你将概率设置为真。在这种情况下,支持向量机也必须计算概率,这是内存和计算密集型的。@Eranyogev如何为交叉验证的多类绘制此图?