scikit-learn/examples/plot_roc_crossval.py

68 lines
2.0 KiB
Python
Raw Normal View History

"""
=============================================================
2010-07-27 06:50:50 +08:00
Receiver operating characteristic (ROC) with cross validation
=============================================================
Example of Receiver operating characteristic (ROC) metric to
evaluate the quality of the output of a classifier using
2010-06-16 17:12:21 +08:00
cross-validation.
"""
print __doc__
import numpy as np
from scipy import interp
import pylab as pl
2010-06-16 17:12:21 +08:00
from sklearn import svm, datasets
from sklearn.metrics import roc_curve, auc
2011-09-06 20:44:32 +08:00
from sklearn.cross_validation import StratifiedKFold
2011-12-20 01:16:51 +08:00
###############################################################################
2010-06-16 17:12:21 +08:00
# Data IO and generation
# import some data to play with
iris = datasets.load_iris()
X = iris.data
y = iris.target
2011-12-20 01:16:51 +08:00
X, y = X[y != 2], y[y != 2]
n_samples, n_features = X.shape
# Add noisy features
2011-12-20 01:16:51 +08:00
X = np.c_[X, np.random.randn(n_samples, 200 * n_features)]
2011-12-20 01:16:51 +08:00
###############################################################################
2010-06-16 17:12:21 +08:00
# Classification and ROC analysis
# Run classifier with crossvalidation and plot ROC curves
cv = StratifiedKFold(y, n_folds=6)
classifier = svm.SVC(kernel='linear', probability=True)
mean_tpr = 0.0
mean_fpr = np.linspace(0, 1, 100)
all_tpr = []
for i, (train, test) in enumerate(cv):
2010-06-16 17:12:21 +08:00
probas_ = classifier.fit(X[train], y[train]).predict_proba(X[test])
# Compute ROC curve and area the curve
2011-12-20 01:16:51 +08:00
fpr, tpr, thresholds = roc_curve(y[test], probas_[:, 1])
mean_tpr += interp(mean_fpr, fpr, tpr)
mean_tpr[0] = 0.0
roc_auc = auc(fpr, tpr)
pl.plot(fpr, tpr, lw=1, label='ROC fold %d (area = %0.2f)' % (i, roc_auc))
2011-12-20 01:16:51 +08:00
pl.plot([0, 1], [0, 1], '--', color=(0.6, 0.6, 0.6), label='Luck')
mean_tpr /= len(cv)
mean_tpr[-1] = 1.0
mean_auc = auc(mean_fpr, mean_tpr)
2010-10-13 12:20:00 +08:00
pl.plot(mean_fpr, mean_tpr, 'k--',
2010-06-16 17:12:21 +08:00
label='Mean ROC (area = %0.2f)' % mean_auc, lw=2)
2011-12-20 01:16:51 +08:00
pl.xlim([-0.05, 1.05])
pl.ylim([-0.05, 1.05])
pl.xlabel('False Positive Rate')
pl.ylabel('True Positive Rate')
pl.title('Receiver operating characteristic example')
pl.legend(loc="lower right")
2010-06-16 17:12:21 +08:00
pl.show()