2010-05-26 20:40:29 +08:00
|
|
|
"""
|
|
|
|
|
================
|
|
|
|
|
Precision-Recall
|
|
|
|
|
================
|
|
|
|
|
|
|
|
|
|
Example of Precision-Recall metric to evaluate the quality
|
|
|
|
|
of the output of a classifier.
|
|
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
print __doc__
|
2010-05-26 20:40:29 +08:00
|
|
|
|
|
|
|
|
import random
|
|
|
|
|
import pylab as pl
|
|
|
|
|
import numpy as np
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn import svm, datasets
|
|
|
|
|
from sklearn.metrics import precision_recall_curve
|
|
|
|
|
from sklearn.metrics import auc
|
2010-05-26 20:40:29 +08:00
|
|
|
|
|
|
|
|
# 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] # Keep also 2 classes (0 and 1)
|
2010-05-26 20:40:29 +08:00
|
|
|
n_samples, n_features = X.shape
|
2011-12-20 01:16:51 +08:00
|
|
|
p = range(n_samples) # Shuffle samples
|
2010-05-26 20:40:29 +08:00
|
|
|
random.seed(0)
|
|
|
|
|
random.shuffle(p)
|
|
|
|
|
X, y = X[p], y[p]
|
2011-12-20 01:16:51 +08:00
|
|
|
half = int(n_samples / 2)
|
2010-05-26 20:40:29 +08:00
|
|
|
|
|
|
|
|
# Add noisy features
|
|
|
|
|
np.random.seed(0)
|
2011-12-20 01:16:51 +08:00
|
|
|
X = np.c_[X, np.random.randn(n_samples, 200 * n_features)]
|
2010-05-26 20:40:29 +08:00
|
|
|
|
|
|
|
|
# Run classifier
|
2012-01-31 16:08:59 +08:00
|
|
|
classifier = svm.SVC(kernel='linear', probability=True, scale_C=True)
|
2010-11-01 09:21:46 +08:00
|
|
|
probas_ = classifier.fit(X[:half], y[:half]).predict_proba(X[half:])
|
2010-05-26 20:40:29 +08:00
|
|
|
|
|
|
|
|
# Compute Precision-Recall and plot curve
|
2011-12-20 01:16:51 +08:00
|
|
|
precision, recall, thresholds = precision_recall_curve(y[half:], probas_[:, 1])
|
2010-11-01 09:21:46 +08:00
|
|
|
area = auc(recall, precision)
|
|
|
|
|
print "Area Under Curve: %0.2f" % area
|
2010-05-26 20:40:29 +08:00
|
|
|
|
|
|
|
|
pl.clf()
|
|
|
|
|
pl.plot(recall, precision, label='Precision-Recall curve')
|
|
|
|
|
pl.xlabel('Recall')
|
|
|
|
|
pl.ylabel('Precision')
|
2011-12-20 01:16:51 +08:00
|
|
|
pl.ylim([0.0, 1.05])
|
|
|
|
|
pl.xlim([0.0, 1.0])
|
2010-11-01 09:21:46 +08:00
|
|
|
pl.title('Precision-Recall example: AUC=%0.2f' % area)
|
2010-05-26 20:40:29 +08:00
|
|
|
pl.legend(loc="lower left")
|
2010-10-13 10:32:45 +08:00
|
|
|
pl.show()
|