Here's a Python function that uses the scikit-learn pipeline to perform recursive feature selection and a grid search:
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import RFECV
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVC
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
def rfe_gridsearch_pipeline(X, y):
# Create a pipeline
pipeline = Pipeline([
('scaler', StandardScaler()),
('rfe', RFECV(estimator=SVC(kernel='linear'))),
('clf', SVC())
])
# Define the parameter grid for grid search
param_grid = {
'rfe__step': [1, 2],
'rfe__cv': [3, 5],
'clf__C': [0.1, 1, 10],
'clf__kernel': ['linear', 'rbf']
}
# Perform grid search with cross-validation
grid_search = GridSearchCV(pipeline, param_grid, cv=5, scoring='accuracy', n_jobs=-1)
grid_search.fit(X, y)
# Print the best parameters and score
print("Best parameters: ", grid_search.best_params_)
print("Best score: ", grid_search.best_score_)
# Return the best model
return grid_search.best_estimator_
# Example usage
X, y = make_classification(n_samples=100, n_features=20, n_informative=5, n_redundant=5, random_state=42)
best_model = rfe_gridsearch_pipeline(X, y)
In this function:
-
We create a pipeline that consists of three steps:
StandardScaler(): Standardizes the features by removing the mean and scaling to unit variance.
RFECV(estimator=SVC(kernel='linear')): Performs recursive feature elimination with cross-validation using a linear SVM estimator.
SVC(): The final estimator, which is a support vector machine classifier.
-
We define the parameter grid for the grid search. It includes different values for the following parameters:
rfe__step: The number of features to remove at each iteration.
rfe__cv: The number of folds for cross-validation in RFECV.
clf__C: The regularization parameter for the SVM classifier.
clf__kernel: The kernel type for the SVM classifier.
-
We create a GridSearchCV object with the pipeline, parameter grid, 5-fold cross-validation, accuracy scoring, and parallel processing (n_jobs=-1).
-
We fit the grid search object with the input features X and target labels y.
-
We print the best parameters and the corresponding best score found by the grid search.
-
Finally, we return the best model obtained from the grid search.
In the example usage, we generate a random classification dataset using make_classification() and pass it to the rfe_gridsearch_pipeline() function. The function performs the recursive feature selection and grid search, and returns the best model.
Note: Make sure you have scikit-learn installed (pip install scikit-learn) before running this code.