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
|
|
|
|
2011-09-04 22:15:43 +08:00
|
|
|
A recursive feature elimination example with automatic tuning of the
|
2011-09-04 21:59:50 +08:00
|
|
|
number of features selected with cross-validation.
|
2021-10-22 21:33:22 +08:00
|
|
|
|
2010-11-02 18:38:06 +08:00
|
|
|
"""
|
2010-09-01 02:45:52 +08:00
|
|
|
|
2015-02-13 17:41:49 +08:00
|
|
|
import matplotlib.pyplot as plt
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn.svm import SVC
|
2015-09-11 02:26:39 +08:00
|
|
|
from sklearn.model_selection import StratifiedKFold
|
2011-09-02 17:00:02 +08:00
|
|
|
from sklearn.feature_selection import RFECV
|
2011-12-19 20:27:35 +08:00
|
|
|
from sklearn.datasets import make_classification
|
2010-07-28 00:02:17 +08:00
|
|
|
|
2011-09-04 21:59:50 +08:00
|
|
|
# Build a classification task using 3 informative features
|
2012-04-28 18:04:36 +08:00
|
|
|
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
|
|
|
|
2011-09-04 21:59:50 +08:00
|
|
|
# Create the RFE object and compute a cross-validated score.
|
|
|
|
|
svc = SVC(kernel="linear")
|
2021-08-09 17:47:31 +08:00
|
|
|
# The "accuracy" scoring shows the proportion of correct classifications
|
2020-08-20 21:44:36 +08:00
|
|
|
|
|
|
|
|
min_features_to_select = 1 # Minimum number of features to consider
|
2015-09-11 02:26:39 +08:00
|
|
|
rfecv = RFECV(
|
|
|
|
|
estimator=svc,
|
|
|
|
|
step=1,
|
|
|
|
|
cv=StratifiedKFold(2),
|
2020-08-20 21:44:36 +08:00
|
|
|
scoring="accuracy",
|
|
|
|
|
min_features_to_select=min_features_to_select,
|
|
|
|
|
)
|
2011-09-04 21:59:50 +08:00
|
|
|
rfecv.fit(X, y)
|
2010-07-28 00:02:17 +08:00
|
|
|
|
2013-02-01 22:04:03 +08:00
|
|
|
print("Optimal number of features : %d" % rfecv.n_features_)
|
2010-07-28 00:02:17 +08:00
|
|
|
|
2011-09-04 21:59:50 +08:00
|
|
|
# Plot number of features VS. cross-validation scores
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.figure()
|
|
|
|
|
plt.xlabel("Number of features selected")
|
2021-08-09 17:47:31 +08:00
|
|
|
plt.ylabel("Cross validation score (accuracy)")
|
2020-08-20 21:44:36 +08:00
|
|
|
plt.plot(
|
|
|
|
|
range(min_features_to_select, len(rfecv.grid_scores_) + min_features_to_select),
|
|
|
|
|
rfecv.grid_scores_,
|
|
|
|
|
)
|
2014-05-15 04:31:03 +08:00
|
|
|
plt.show()
|