Feature ranking with recursive feature elimination.
Given an external estimator that assigns weights to features (e.g., the
coefficients of a linear model), the goal of recursive feature elimination
(RFE) is to select features by recursively considering smaller and smaller
sets of features. First, the estimator is trained on the initial set of
features and the importance of each feature is obtained either through
any specific attribute or callable.
Then, the least important features are pruned from current set of features.
That procedure is recursively repeated on the pruned set until the desired
number of features to select is eventually reached.
Read more in the User Guide.
:param estimator: A supervised learning estimator with a fit method that provides
information about feature importance
(e.g. coef_, feature_importances_).
Parameters:
n_features_to_select (int or float, default=None) –
The number of features to select. If None, half of the features are
selected. If integer, the parameter is the absolute number of features
to select. If float between 0 and 1, it is the fraction of features to
select.
.. versionchanged:: 0.24
Added float values for fractions.
step (int or float, default=1) – If greater than or equal to 1, then step corresponds to the
(integer) number of features to remove at each iteration.
If within (0.0, 1.0), then step corresponds to the percentage
(rounded down) of features to remove at each iteration.
verbose (int, default=0) – Controls verbosity of output.
importance_getter (str or callable, default='auto') – If ‘auto’, uses the feature importance either through a coef_
or feature_importances_ attributes of estimator.
Also accepts a string that specifies an attribute name/path
for extracting feature importance (implemented with attrgetter).
For example, give regressor_.coef_ in case of
TransformedTargetRegressor or
named_steps.clf.feature_importances_ in case of
class:~sklearn.pipeline.Pipeline with its last step named clf.
If callable, overrides the default feature importance getter.
The callable is passed with the fitted estimator and it should
return importance for each feature.
.. versionadded:: 0.24
The feature ranking, such that ranking_[i] corresponds to the
ranking position of the i-th feature. Selected (i.e., estimated
best) features are assigned rank 1.
Recursive feature elimination with built-in cross-validated selection of the best number of features.
SelectFromModel
Feature selection based on thresholds of importance weights.
SequentialFeatureSelector
Sequential cross-validation based feature selection. Does not rely on importance weights.
Notes
Allows NaN/Inf in the input if the underlying estimator does as well.
References
Examples
The following example shows how to retrieve the 5 most informative
features in the Friedman #1 dataset.
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.feature_selection import RFE
>>> from sklearn.svm import SVR
>>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
>>> estimator = SVR(kernel=”linear”)
>>> selector = RFE(estimator, n_features_to_select=5, step=1)
>>> selector = selector.fit(X, y)
>>> selector.support_
array([ True, True, True, True, True, False, False, False, False,
Fit the RFE model and then the underlying estimator on the selected features.
:param X: The training input samples.
:type X: {array-like, sparse matrix} of shape (n_samples, n_features)
:param y: The target values.
:type y: array-like of shape (n_samples,)
:param **fit_params: Additional parameters passed to the fit method of the underlying
Reduce X to the selected features and then predict using the underlying estimator.
:param X: The input samples.
:type X: array of shape [n_samples, n_features]
Reduce X to the selected features and return the score of the underlying estimator.
:param X: The input samples.
:type X: array of shape [n_samples, n_features]
:param y: The target values.
:type y: array of shape [n_samples]
:param **fit_params: Parameters to pass to the score method of the underlying
estimator.
.. versionadded:: 1.0
Returns:
score – Score of the underlying base estimator computed with the selected
features returned by rfe.transform(X) and y.
Compute the decision function of X.
:param X: The input samples. Internally, it will be converted to
dtype=np.float32 and if a sparse matrix is provided
to a sparse csr_matrix.
Returns:
score – The decision function of the input samples. The order of the
classes corresponds to that in the attribute classes_.
Regression and binary classification produce an array of shape
[n_samples].
Return type:
array, shape = [n_samples, n_classes] or [n_samples]
Recursive feature elimination with cross-validation to select the number of features.
See glossary entry for cross-validation estimator.
Read more in the User Guide.
:param estimator: A supervised learning estimator with a fit method that provides
information about feature importance either through a coef_
attribute or through a feature_importances_ attribute.
Parameters:
step (int or float, default=1) – If greater than or equal to 1, then step corresponds to the
(integer) number of features to remove at each iteration.
If within (0.0, 1.0), then step corresponds to the percentage
(rounded down) of features to remove at each iteration.
Note that the last iteration may remove fewer than step features in
order to reach min_features_to_select.
min_features_to_select (int, default=1) – The minimum number of features to be selected. This number of features
will always be scored, even if the difference between the original
feature count and min_features_to_select isn’t divisible by
step.
.. versionadded:: 0.20
cv (int, cross-validation generator or an iterable, default=None) –
Determines the cross-validation splitting strategy.
Possible inputs for cv are:
- None, to use the default 5-fold cross-validation,
- integer, to specify the number of folds.
- CV splitter,
- An iterable yielding (train, test) splits as arrays of indices.
For integer/None inputs, if y is binary or multiclass,
StratifiedKFold is used. If the
estimator is a classifier or if y is neither binary nor multiclass,
KFold is used.
Refer User Guide for the various
cross-validation strategies that can be used here.
.. versionchanged:: 0.22
cv default value of None changed from 3-fold to 5-fold.
scoring (str, callable or None, default=None) – A string (see model evaluation documentation) or
a scorer callable object / function with signature
scorer(estimator,X,y).
verbose (int, default=0) – Controls verbosity of output.
n_jobs (int or None, default=None) – Number of cores to run in parallel while fitting across folds.
None means 1 unless in a joblib.parallel_backend context.
-1 means using all processors. See Glossary
for more details.
.. versionadded:: 0.18
importance_getter (str or callable, default='auto') – If ‘auto’, uses the feature importance either through a coef_
or feature_importances_ attributes of estimator.
Also accepts a string that specifies an attribute name/path
for extracting feature importance.
For example, give regressor_.coef_ in case of
TransformedTargetRegressor or
named_steps.clf.feature_importances_ in case of
Pipeline with its last step named clf.
If callable, overrides the default feature importance getter.
The callable is passed with the fitted estimator and it should
return importance for each feature.
.. versionadded:: 0.24
The feature ranking, such that ranking_[i]
corresponds to the ranking
position of the i-th feature.
Selected (i.e., estimated best)
features are assigned rank 1.
The size of grid_scores_ is equal to
ceil((n_features-min_features_to_select)/step)+1,
where step is the number of features removed at each iteration.
Allows NaN/Inf in the input if the underlying estimator does as well.
References
Examples
The following example shows how to retrieve the a-priori not known 5
informative features in the Friedman #1 dataset.
>>> from sklearn.datasets import make_friedman1
>>> from sklearn.feature_selection import RFECV
>>> from sklearn.svm import SVR
>>> X, y = make_friedman1(n_samples=50, n_features=10, random_state=0)
>>> estimator = SVR(kernel=”linear”)
>>> selector = RFECV(estimator, step=1, cv=5)
>>> selector = selector.fit(X, y)
>>> selector.support_
array([ True, True, True, True, True, False, False, False, False,
Fit the RFE model and automatically tune the number of selected features.
:param X: Training vector, where n_samples is the number of samples and
n_features is the total number of features.
Parameters:
y (array-like of shape (n_samples,)) – Target values (integers for classification, real numbers for
regression).
groups (array-like of shape (n_samples,) or None, default=None) – Group labels for the samples used while splitting the dataset into
train/test set. Only used in conjunction with a “Group” cv
instance (e.g., GroupKFold).
.. versionadded:: 0.20