scikit-learn/examples/plot_rfe_with_cross_validat...

37 lines
1.3 KiB
Python
Raw Normal View History

2010-07-28 00:02:17 +08:00
"""
===================================================
2010-09-01 02:45:52 +08:00
Recursive feature elimination with cross-validation
===================================================
2010-07-28 00:02:17 +08:00
2011-09-04 22:15:43 +08:00
A recursive feature elimination example with automatic tuning of the
number of features selected with cross-validation.
"""
print(__doc__)
2010-09-01 02:45:52 +08:00
from sklearn.svm import SVC
2011-09-06 20:44:32 +08:00
from sklearn.cross_validation import StratifiedKFold
from sklearn.feature_selection import RFECV
2011-12-19 20:27:35 +08:00
from sklearn.datasets import make_classification
from sklearn.metrics import zero_one_loss
2010-07-28 00:02:17 +08:00
# Build a classification task using 3 informative features
X, y = make_classification(n_samples=1000, n_features=25, n_informative=3,
2012-12-25 20:16:05 +08:00
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, step=1, cv=StratifiedKFold(y, 2),
scoring='accuracy')
rfecv.fit(X, y)
2010-07-28 00:02:17 +08:00
print("Optimal number of features : %d" % rfecv.n_features_)
2010-07-28 00:02:17 +08:00
# Plot number of features VS. cross-validation scores
2010-07-28 00:02:17 +08:00
import pylab as pl
pl.figure()
pl.xlabel("Number of features selected")
pl.ylabel("Cross validation score (nb of misclassifications)")
pl.plot(range(1, len(rfecv.grid_scores_) + 1), rfecv.grid_scores_)
2010-07-31 21:04:43 +08:00
pl.show()