from sklearn.feature_selection import SelectKBest, chi2
selector = SelectKBest(score_func=chi2, k=2)
X_new = selector.fit_transform(X, y)
Wrapper methods follow the selection process as a search problem. These methods train a particular machine learning estimator on different combinations of features and evaluate performance to add or remove columns.
from sklearn.linear_model import LogisticRegression
X, y = load_iris(return_X_y=True)
estimator = LogisticRegression(max_iter=200)
rfe_selector = RFE(estimator=estimator, n_features_to_select=2)
rfe_selector.fit(X, y)
print("Feature Support:", rfe_selector.support_)
print("Feature Ranking:", rfe_selector.ranking_)
Embedded methods perform feature selection internally as part of the model's training process.
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_selection import SelectFromModel
X, y = load_iris(return_X_y=True)
clf = RandomForestClassifier(n_estimators=50, random_state=42)
sfm_selector = SelectFromModel(estimator=clf)
X_new = sfm_selector.fit_transform(X, y)
print("Features kept after tree-based selection:", X_new.shape[1])
No More
Statlearner
Statlearner