2010-07-28 00:02:17 +08:00
|
|
|
"""
|
2010-11-02 18:38:06 +08:00
|
|
|
===================================================
|
2010-09-01 02:45:52 +08:00
|
|
|
Recursive feature elimination with cross-validation
|
|
|
|
|
===================================================
|
2010-07-28 00:02:17 +08:00
|
|
|
|
2010-11-02 18:38:06 +08:00
|
|
|
Recursive feature elimination with automatic tuning of the
|
|
|
|
|
number of features selected with cross-validation
|
|
|
|
|
"""
|
|
|
|
|
print __doc__
|
2010-11-27 20:32:14 +08:00
|
|
|
import numpy as np
|
2010-09-01 02:45:52 +08:00
|
|
|
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn.svm import SVC
|
|
|
|
|
from sklearn.cross_val import StratifiedKFold
|
|
|
|
|
from sklearn.feature_selection import RFECV
|
|
|
|
|
from sklearn.datasets import samples_generator
|
|
|
|
|
from sklearn.metrics import zero_one
|
2010-07-28 00:02:17 +08:00
|
|
|
|
|
|
|
|
################################################################################
|
|
|
|
|
# Loading a dataset
|
|
|
|
|
|
2011-08-09 22:53:31 +08:00
|
|
|
X, y = samples_generator.make_classification(n_samples=1000, n_features=20,
|
|
|
|
|
n_informative=3, n_redundant=2,
|
|
|
|
|
n_repeated=0, n_classes=8,
|
|
|
|
|
n_clusters_per_class=1,
|
|
|
|
|
random_state=0)
|
2010-07-28 00:02:17 +08:00
|
|
|
|
|
|
|
|
################################################################################
|
|
|
|
|
# Create the RFE object and compute a cross-validated score
|
|
|
|
|
|
|
|
|
|
svc = SVC(kernel='linear')
|
|
|
|
|
rfecv = RFECV(estimator=svc, n_features=2, percentage=0.1, loss_func=zero_one)
|
|
|
|
|
rfecv.fit(X, y, cv=StratifiedKFold(y, 2))
|
|
|
|
|
|
|
|
|
|
print 'Optimal number of features : %d' % rfecv.support_.sum()
|
|
|
|
|
|
|
|
|
|
import pylab as pl
|
|
|
|
|
pl.figure()
|
2010-11-27 20:32:14 +08:00
|
|
|
pl.semilogx(rfecv.n_features_, rfecv.cv_scores_)
|
|
|
|
|
pl.xlabel('Number of features selected')
|
|
|
|
|
pl.ylabel('Cross validation score (nb of misclassifications)')
|
|
|
|
|
# 15 ticks regularly-space in log
|
2011-05-04 23:49:17 +08:00
|
|
|
x_ticks = np.unique(np.logspace(np.log10(2),
|
2010-11-27 20:32:14 +08:00
|
|
|
np.log10(rfecv.n_features_.max()),
|
|
|
|
|
15,
|
|
|
|
|
).astype(np.int))
|
|
|
|
|
pl.xticks(x_ticks, x_ticks)
|
2010-07-31 21:04:43 +08:00
|
|
|
pl.show()
|
2010-07-28 00:02:17 +08:00
|
|
|
|