scpanel.SVMRFECV

Recursive feature elimination for feature ranking

Classes

RFE

Feature ranking with recursive feature elimination.

RFECV

Recursive feature elimination with cross-validation to select the number of features.

Functions

_rfe_single_fit(rfe, estimator, X, y, train_idx, ...)

Return the score for a fit across one fold.

Module Contents

scpanel.SVMRFECV._rfe_single_fit(rfe, estimator, X, y, train_idx, val_idx, scorer, sample_weight=None)

Return the score for a fit across one fold.

class scpanel.SVMRFECV.RFE(estimator: sklearn.svm._classes.SVC, *, n_features_to_select=None, step=1, verbose=0, importance_getter='auto')

Bases: sklearn.feature_selection._base.SelectorMixin, sklearn.base.MetaEstimatorMixin, sklearn.base.BaseEstimator

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

classes_

The classes labels. Only available when estimator is a classifier.

Type:

ndarray of shape (n_classes,)

estimator_

The fitted estimator used to select features.

Type:

Estimator instance

n_features_

The number of selected features.

Type:

int

n_features_in_

Number of features seen during fit. Only defined if the underlying estimator exposes such an attribute when fit. .. versionadded:: 0.24

Type:

int

feature_names_in_

Names of features seen during fit. Defined only when X has feature names that are all strings. .. versionadded:: 1.0

Type:

ndarray of shape (n_features_in_,)

ranking_

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.

Type:

ndarray of shape (n_features,)

support_

The mask of selected features.

Type:

ndarray of shape (n_features,)

See also

RFECV

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,

False])

>>> selector.ranking_
array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
estimator
n_features_to_select
step
importance_getter
verbose
property _estimator_type
fit(X: numpy.ndarray, y: numpy.ndarray, **fit_params) RFE

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

estimator.

Returns:

self – Fitted estimator.

Return type:

object

_fit(X: numpy.ndarray, y: numpy.ndarray, step_score: None = None, **fit_params) RFE
predict(X)

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]

Returns:

y – The predicted target values.

Return type:

array of shape [n_samples]

score(X, y, **fit_params)

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.

Return type:

float

_get_support_mask()
decision_function(X)

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]

predict_proba(X)

Predict class probabilities for 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:

p – The class probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.

Return type:

array of shape (n_samples, n_classes)

predict_log_proba(X)

Predict class log-probabilities for X. :param X: The input samples. :type X: array of shape [n_samples, n_features]

Returns:

p – The class log-probabilities of the input samples. The order of the classes corresponds to that in the attribute classes_.

Return type:

array of shape (n_samples, n_classes)

_more_tags() Dict[str, bool]
class scpanel.SVMRFECV.RFECV(estimator: sklearn.svm._classes.SVC, *, step=1, min_features_to_select=1, cv=None, scoring=None, verbose=0, n_jobs=None, importance_getter='auto')

Bases: RFE

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

classes_

The classes labels. Only available when estimator is a classifier.

Type:

ndarray of shape (n_classes,)

estimator_

The fitted estimator used to select features.

Type:

Estimator instance

grid_scores_

The cross-validation scores such that grid_scores_[i] corresponds to the CV score of the i-th subset of features. .. deprecated:: 1.0

The grid_scores_ attribute is deprecated in version 1.0 in favor of cv_results_ and will be removed in version 1.2.

Type:

ndarray of shape (n_subsets_of_features,)

cv_results_

A dict with keys: split(k)_test_score : ndarray of shape (n_features,)

The cross-validation scores across (k)th fold.

mean_test_scorendarray of shape (n_features,)

Mean of scores over the folds.

std_test_scorendarray of shape (n_features,)

Standard deviation of scores over the folds.

Added in version 1.0.

Type:

dict of ndarrays

n_features_

The number of selected features with cross-validation.

Type:

int

n_features_in_

Number of features seen during fit. Only defined if the underlying estimator exposes such an attribute when fit. .. versionadded:: 0.24

Type:

int

feature_names_in_

Names of features seen during fit. Defined only when X has feature names that are all strings. .. versionadded:: 1.0

Type:

ndarray of shape (n_features_in_,)

ranking_

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.

Type:

narray of shape (n_features,)

support_

The mask of selected features.

Type:

ndarray of shape (n_features,)

See also

RFE

Recursive feature elimination.

Notes

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,

False])

>>> selector.ranking_
array([1, 1, 1, 1, 1, 6, 4, 3, 2, 5])
estimator
step
importance_getter
cv
scoring
verbose
n_jobs
min_features_to_select
fit(X: numpy.ndarray, y: numpy.ndarray, train_idx_list: List[List[int]], val_idx_list: List[List[int]], groups: None = None, sample_weight_list: List[List[float]] | None = None) RFECV

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

Returns:

self – Fitted estimator.

Return type:

object

property grid_scores_