All selectors below are transformers: put them in a Pipeline after preprocessing so they are fitted on training folds only.
Filter
from sklearn.feature_selection import (VarianceThreshold, SelectKBest, SelectPercentile, f_classif,
mutual_info_classif, mutual_info_regression, chi2)
VarianceThreshold(threshold=0.0) # constant columns (after scaling, pick a small threshold)
SelectKBest(score_func=mutual_info_classif, k=30) # non-linear univariate dependence; set random_state via partial
SelectPercentile(score_func=f_classif, percentile=20) # linear univariate (ANOVA F)
SelectKBest(chi2, k=50) # non-negative features (counts, TF-IDF)from functools import partial
mi = partial(mutual_info_classif, random_state=0, discrete_features="auto")
selector = SelectKBest(mi, k=30)Embedded: L1 and elastic net
from sklearn.feature_selection import SelectFromModel
from sklearn.linear_model import LogisticRegression, LassoCV, ElasticNetCV
l1 = SelectFromModel(LogisticRegression(penalty="l1", solver="saga", C=0.1, max_iter=5000))
lasso = SelectFromModel(LassoCV(cv=5, random_state=0)) # regression
enet = SelectFromModel(ElasticNetCV(l1_ratio=[0.2, 0.5, 0.8], cv=5, random_state=0))- Scale features first (the penalty is unit-dependent).
- L1 keeps one arbitrary member of a correlated group; elastic net spreads weight over the group (more stable).
- Inspect the regularisation path (
lasso_path,l1_min_c) to see the order in which features enter.
Embedded: tree importance
from sklearn.ensemble import RandomForestClassifier
SelectFromModel(RandomForestClassifier(n_estimators=500, random_state=0), threshold="median")Impurity-based importance (feature_importances_) is computed on training data and biased toward
high-cardinality and continuous features; use permutation importance on held-out data for decisions.
Wrapper: RFE / RFECV
from sklearn.feature_selection import RFECV
from sklearn.model_selection import StratifiedKFold
rfecv = RFECV(estimator=LogisticRegression(max_iter=2000), step=0.1, cv=StratifiedKFold(5),
scoring="average_precision", min_features_to_select=5, n_jobs=-1)
rfecv.fit(X_train_prepped, y_train)
print(rfecv.n_features_, rfecv.cv_results_["mean_test_score"])step as a fraction removes that share of features per round (much faster on wide data).
Wrapper: sequential selection
from sklearn.feature_selection import SequentialFeatureSelector
sfs = SequentialFeatureSelector(model, n_features_to_select="auto", tol=0.001, direction="forward",
scoring="average_precision", cv=5, n_jobs=-1)Costs O(features²) model fits; use on tens, not thousands, of features.
Permutation importance (held-out)
from sklearn.inspection import permutation_importance
r = permutation_importance(fitted_pipe, X_valid, y_valid, scoring="average_precision", n_repeats=20,
random_state=0, n_jobs=-1)
order = r.importances_mean.argsort()[::-1]
for i in order[:20]:
print(f"{X_valid.columns[i]:<25} {r.importances_mean[i]:.4f} ± {r.importances_std[i]:.4f}")Features whose mean minus 2 std is <= 0 are not distinguishable from zero on this validation set.
Boruta-style shadow features
import numpy as np
rng = np.random.default_rng(0)
shadow = X_train.apply(lambda c: rng.permutation(c.values)).add_prefix("shadow_")
X_aug = pd.concat([X_train, shadow], axis=1)
# fit a tree model on X_aug; a real feature must beat the best shadow importance (repeat many times)The boruta package (BorutaPy) implements the full iterative test.
Stability selection
import numpy as np
from sklearn.utils import resample
def stability_selection(X, y, make_selector, n_runs=50, frac=0.5, seed=0):
rng = np.random.default_rng(seed)
counts = np.zeros(X.shape[1])
for _ in range(n_runs):
idx = rng.choice(len(X), int(frac * len(X)), replace=False)
sel = make_selector().fit(X.iloc[idx], y.iloc[idx])
counts += sel.get_support()
return counts / n_runs # keep features with frequency >= 0.6-0.8Write each run's importances in long format (run, feature, importance) and feed them to
importance_stability.py.
anomaly-detection-model-builder
Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.
catboost-model-builder
Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).
categorical-encoding-selector
Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).
classification-model-selector
Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.
clustering-algorithm-selector
Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.
collaborative-filtering-implementer
Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.